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,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Features/Core/Portable/AddImport/AddImportFixData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Runtime.Serialization;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.AddImport
{
[DataContract]
internal sealed class AddImportFixData
{
[DataMember(Order = 0)]
public AddImportFixKind Kind { get; }
/// <summary>
/// Text changes to make to the document. Usually just the import to add. May also
/// include a change to the name node the feature was invoked on to fix the casing of it.
/// May be empty for fixes that don't need to add an import and only do something like
/// add a project/metadata reference.
/// </summary>
[DataMember(Order = 1)]
public readonly ImmutableArray<TextChange> TextChanges;
/// <summary>
/// String to display in the lightbulb menu.
/// </summary>
[DataMember(Order = 2)]
public readonly string Title;
/// <summary>
/// Tags that control what glyph is displayed in the lightbulb menu.
/// </summary>
[DataMember(Order = 3)]
public readonly ImmutableArray<string> Tags;
/// <summary>
/// The priority this item should have in the lightbulb list.
/// </summary>
[DataMember(Order = 4)]
public readonly CodeActionPriority Priority;
#region When adding P2P references.
/// <summary>
/// The optional id for a <see cref="Project"/> we'd like to add a reference to.
/// </summary>
[DataMember(Order = 5)]
public readonly ProjectId ProjectReferenceToAdd;
#endregion
#region When adding a metadata reference
/// <summary>
/// If we're adding <see cref="PortableExecutableReferenceFilePathToAdd"/> then this
/// is the id for the <see cref="Project"/> we can find that <see cref="PortableExecutableReference"/>
/// referenced from.
/// </summary>
[DataMember(Order = 6)]
public readonly ProjectId PortableExecutableReferenceProjectId;
/// <summary>
/// If we want to add a <see cref="PortableExecutableReference"/> metadata reference, this
/// is the <see cref="PortableExecutableReference.FilePath"/> for it.
/// </summary>
[DataMember(Order = 7)]
public readonly string PortableExecutableReferenceFilePathToAdd;
#endregion
#region When adding an assembly reference
[DataMember(Order = 8)]
public readonly string AssemblyReferenceAssemblyName;
[DataMember(Order = 9)]
public readonly string AssemblyReferenceFullyQualifiedTypeName;
#endregion
#region When adding a package reference
[DataMember(Order = 10)]
public readonly string PackageSource;
[DataMember(Order = 11)]
public readonly string PackageName;
[DataMember(Order = 12)]
public readonly string PackageVersionOpt;
#endregion
// Must be public since it's used for deserialization.
public AddImportFixData(
AddImportFixKind kind,
ImmutableArray<TextChange> textChanges,
string title = null,
ImmutableArray<string> tags = default,
CodeActionPriority priority = default,
ProjectId projectReferenceToAdd = null,
ProjectId portableExecutableReferenceProjectId = null,
string portableExecutableReferenceFilePathToAdd = null,
string assemblyReferenceAssemblyName = null,
string assemblyReferenceFullyQualifiedTypeName = null,
string packageSource = null,
string packageName = null,
string packageVersionOpt = null)
{
Kind = kind;
TextChanges = textChanges;
Title = title;
Tags = tags;
Priority = priority;
ProjectReferenceToAdd = projectReferenceToAdd;
PortableExecutableReferenceProjectId = portableExecutableReferenceProjectId;
PortableExecutableReferenceFilePathToAdd = portableExecutableReferenceFilePathToAdd;
AssemblyReferenceAssemblyName = assemblyReferenceAssemblyName;
AssemblyReferenceFullyQualifiedTypeName = assemblyReferenceFullyQualifiedTypeName;
PackageSource = packageSource;
PackageName = packageName;
PackageVersionOpt = packageVersionOpt;
}
public static AddImportFixData CreateForProjectSymbol(ImmutableArray<TextChange> textChanges, string title, ImmutableArray<string> tags, CodeActionPriority priority, ProjectId projectReferenceToAdd)
=> new(AddImportFixKind.ProjectSymbol,
textChanges,
title: title,
tags: tags,
priority: priority,
projectReferenceToAdd: projectReferenceToAdd);
public static AddImportFixData CreateForMetadataSymbol(ImmutableArray<TextChange> textChanges, string title, ImmutableArray<string> tags, CodeActionPriority priority, ProjectId portableExecutableReferenceProjectId, string portableExecutableReferenceFilePathToAdd)
=> new(AddImportFixKind.MetadataSymbol,
textChanges,
title: title,
tags: tags,
priority: priority,
portableExecutableReferenceProjectId: portableExecutableReferenceProjectId,
portableExecutableReferenceFilePathToAdd: portableExecutableReferenceFilePathToAdd);
public static AddImportFixData CreateForReferenceAssemblySymbol(ImmutableArray<TextChange> textChanges, string title, string assemblyReferenceAssemblyName, string assemblyReferenceFullyQualifiedTypeName)
=> new(AddImportFixKind.ReferenceAssemblySymbol,
textChanges,
title: title,
tags: WellKnownTagArrays.AddReference,
priority: CodeActionPriority.Low,
assemblyReferenceAssemblyName: assemblyReferenceAssemblyName,
assemblyReferenceFullyQualifiedTypeName: assemblyReferenceFullyQualifiedTypeName);
public static AddImportFixData CreateForPackageSymbol(ImmutableArray<TextChange> textChanges, string packageSource, string packageName, string packageVersionOpt)
=> new(AddImportFixKind.PackageSymbol,
textChanges,
packageSource: packageSource,
priority: CodeActionPriority.Low,
packageName: packageName,
packageVersionOpt: packageVersionOpt);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Runtime.Serialization;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.AddImport
{
[DataContract]
internal sealed class AddImportFixData
{
[DataMember(Order = 0)]
public AddImportFixKind Kind { get; }
/// <summary>
/// Text changes to make to the document. Usually just the import to add. May also
/// include a change to the name node the feature was invoked on to fix the casing of it.
/// May be empty for fixes that don't need to add an import and only do something like
/// add a project/metadata reference.
/// </summary>
[DataMember(Order = 1)]
public readonly ImmutableArray<TextChange> TextChanges;
/// <summary>
/// String to display in the lightbulb menu.
/// </summary>
[DataMember(Order = 2)]
public readonly string Title;
/// <summary>
/// Tags that control what glyph is displayed in the lightbulb menu.
/// </summary>
[DataMember(Order = 3)]
public readonly ImmutableArray<string> Tags;
/// <summary>
/// The priority this item should have in the lightbulb list.
/// </summary>
[DataMember(Order = 4)]
public readonly CodeActionPriority Priority;
#region When adding P2P references.
/// <summary>
/// The optional id for a <see cref="Project"/> we'd like to add a reference to.
/// </summary>
[DataMember(Order = 5)]
public readonly ProjectId ProjectReferenceToAdd;
#endregion
#region When adding a metadata reference
/// <summary>
/// If we're adding <see cref="PortableExecutableReferenceFilePathToAdd"/> then this
/// is the id for the <see cref="Project"/> we can find that <see cref="PortableExecutableReference"/>
/// referenced from.
/// </summary>
[DataMember(Order = 6)]
public readonly ProjectId PortableExecutableReferenceProjectId;
/// <summary>
/// If we want to add a <see cref="PortableExecutableReference"/> metadata reference, this
/// is the <see cref="PortableExecutableReference.FilePath"/> for it.
/// </summary>
[DataMember(Order = 7)]
public readonly string PortableExecutableReferenceFilePathToAdd;
#endregion
#region When adding an assembly reference
[DataMember(Order = 8)]
public readonly string AssemblyReferenceAssemblyName;
[DataMember(Order = 9)]
public readonly string AssemblyReferenceFullyQualifiedTypeName;
#endregion
#region When adding a package reference
[DataMember(Order = 10)]
public readonly string PackageSource;
[DataMember(Order = 11)]
public readonly string PackageName;
[DataMember(Order = 12)]
public readonly string PackageVersionOpt;
#endregion
// Must be public since it's used for deserialization.
public AddImportFixData(
AddImportFixKind kind,
ImmutableArray<TextChange> textChanges,
string title = null,
ImmutableArray<string> tags = default,
CodeActionPriority priority = default,
ProjectId projectReferenceToAdd = null,
ProjectId portableExecutableReferenceProjectId = null,
string portableExecutableReferenceFilePathToAdd = null,
string assemblyReferenceAssemblyName = null,
string assemblyReferenceFullyQualifiedTypeName = null,
string packageSource = null,
string packageName = null,
string packageVersionOpt = null)
{
Kind = kind;
TextChanges = textChanges;
Title = title;
Tags = tags;
Priority = priority;
ProjectReferenceToAdd = projectReferenceToAdd;
PortableExecutableReferenceProjectId = portableExecutableReferenceProjectId;
PortableExecutableReferenceFilePathToAdd = portableExecutableReferenceFilePathToAdd;
AssemblyReferenceAssemblyName = assemblyReferenceAssemblyName;
AssemblyReferenceFullyQualifiedTypeName = assemblyReferenceFullyQualifiedTypeName;
PackageSource = packageSource;
PackageName = packageName;
PackageVersionOpt = packageVersionOpt;
}
public static AddImportFixData CreateForProjectSymbol(ImmutableArray<TextChange> textChanges, string title, ImmutableArray<string> tags, CodeActionPriority priority, ProjectId projectReferenceToAdd)
=> new(AddImportFixKind.ProjectSymbol,
textChanges,
title: title,
tags: tags,
priority: priority,
projectReferenceToAdd: projectReferenceToAdd);
public static AddImportFixData CreateForMetadataSymbol(ImmutableArray<TextChange> textChanges, string title, ImmutableArray<string> tags, CodeActionPriority priority, ProjectId portableExecutableReferenceProjectId, string portableExecutableReferenceFilePathToAdd)
=> new(AddImportFixKind.MetadataSymbol,
textChanges,
title: title,
tags: tags,
priority: priority,
portableExecutableReferenceProjectId: portableExecutableReferenceProjectId,
portableExecutableReferenceFilePathToAdd: portableExecutableReferenceFilePathToAdd);
public static AddImportFixData CreateForReferenceAssemblySymbol(ImmutableArray<TextChange> textChanges, string title, string assemblyReferenceAssemblyName, string assemblyReferenceFullyQualifiedTypeName)
=> new(AddImportFixKind.ReferenceAssemblySymbol,
textChanges,
title: title,
tags: WellKnownTagArrays.AddReference,
priority: CodeActionPriority.Low,
assemblyReferenceAssemblyName: assemblyReferenceAssemblyName,
assemblyReferenceFullyQualifiedTypeName: assemblyReferenceFullyQualifiedTypeName);
public static AddImportFixData CreateForPackageSymbol(ImmutableArray<TextChange> textChanges, string packageSource, string packageName, string packageVersionOpt)
=> new(AddImportFixKind.PackageSymbol,
textChanges,
packageSource: packageSource,
priority: CodeActionPriority.Low,
packageName: packageName,
packageVersionOpt: packageVersionOpt);
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/EditorFeatures/Core/Implementation/RenameTracking/RenameTrackingTag.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
internal class RenameTrackingTag : TextMarkerTag
{
internal const string TagId = "RenameTrackingTag";
public static readonly RenameTrackingTag Instance = new();
private RenameTrackingTag()
: base(TagId)
{
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
{
internal class RenameTrackingTag : TextMarkerTag
{
internal const string TagId = "RenameTrackingTag";
public static readonly RenameTrackingTag Instance = new();
private RenameTrackingTag()
: base(TagId)
{
}
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Features/LanguageServer/Protocol/Handler/IRequestHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Top level type for LSP request handler.
/// </summary>
internal interface IRequestHandler
{
/// <summary>
/// The LSP method that this <see cref="IRequestHandler"/> implements.
/// </summary>
string Method { get; }
/// <summary>
/// Whether or not the solution state on the server is modified
/// as a part of handling this request.
/// </summary>
bool MutatesSolutionState { get; }
/// <summary>
/// Whether or not the handler execution queue should build a solution that represents the LSP
/// state of the world. If this property is not set <see cref="RequestContext.Solution"/> will be <see langword="null"/>
/// and <see cref="RequestContext.Document"/> will be <see langword="null"/>, even if <see cref="IRequestHandler{RequestType, ResponseType}.GetTextDocumentIdentifier(RequestType)"/>
/// doesn't return null. Handlers should still provide text document information if possible to
/// ensure the correct workspace is found and validated.
/// </summary>
bool RequiresLSPSolution { get; }
}
internal interface IRequestHandler<RequestType, ResponseType> : IRequestHandler
{
/// <summary>
/// Gets the <see cref="TextDocumentIdentifier"/> from the request, if the request provides one.
/// </summary>
TextDocumentIdentifier? GetTextDocumentIdentifier(RequestType request);
/// <summary>
/// Handles an LSP request in the context of the supplied document and/or solutuion.
/// </summary>
/// <param name="context">The LSP request context, which should have been filled in with document information from <see cref="GetTextDocumentIdentifier(RequestType)"/> if applicable.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the request processing.</param>
/// <returns>The LSP response.</returns>
Task<ResponseType> HandleRequestAsync(RequestType request, RequestContext context, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Top level type for LSP request handler.
/// </summary>
internal interface IRequestHandler
{
/// <summary>
/// The LSP method that this <see cref="IRequestHandler"/> implements.
/// </summary>
string Method { get; }
/// <summary>
/// Whether or not the solution state on the server is modified
/// as a part of handling this request.
/// </summary>
bool MutatesSolutionState { get; }
/// <summary>
/// Whether or not the handler execution queue should build a solution that represents the LSP
/// state of the world. If this property is not set <see cref="RequestContext.Solution"/> will be <see langword="null"/>
/// and <see cref="RequestContext.Document"/> will be <see langword="null"/>, even if <see cref="IRequestHandler{RequestType, ResponseType}.GetTextDocumentIdentifier(RequestType)"/>
/// doesn't return null. Handlers should still provide text document information if possible to
/// ensure the correct workspace is found and validated.
/// </summary>
bool RequiresLSPSolution { get; }
}
internal interface IRequestHandler<RequestType, ResponseType> : IRequestHandler
{
/// <summary>
/// Gets the <see cref="TextDocumentIdentifier"/> from the request, if the request provides one.
/// </summary>
TextDocumentIdentifier? GetTextDocumentIdentifier(RequestType request);
/// <summary>
/// Handles an LSP request in the context of the supplied document and/or solutuion.
/// </summary>
/// <param name="context">The LSP request context, which should have been filled in with document information from <see cref="GetTextDocumentIdentifier(RequestType)"/> if applicable.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the request processing.</param>
/// <returns>The LSP response.</returns>
Task<ResponseType> HandleRequestAsync(RequestType request, RequestContext context, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Analyzers/VisualBasic/CodeFixes/ConvertTypeOfToNameOf/VisualBasicConvertGetTypeToNameOfCodeFixProvider.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 System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.ConvertTypeOfToNameOf
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertTypeOfToNameOf
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.ConvertTypeOfToNameOf), [Shared]>
Friend Class VisualBasicConvertGetTypeToNameOfCodeFixProvider
Inherits AbstractConvertTypeOfToNameOfCodeFixProvider
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function GetCodeFixTitle() As String
Return VisualBasicCodeFixesResources.Convert_GetType_to_NameOf
End Function
Protected Overrides Function GetSymbolTypeExpression(semanticModel As SemanticModel, node As SyntaxNode, cancellationToken As CancellationToken) As SyntaxNode
Dim expression = DirectCast(node, MemberAccessExpressionSyntax).Expression
Dim type = DirectCast(expression, GetTypeExpressionSyntax).Type
Dim symbolType = semanticModel.GetSymbolInfo(type, cancellationToken).Symbol.GetSymbolType()
Dim symbolExpression = symbolType.GenerateExpressionSyntax()
If TypeOf symbolExpression Is IdentifierNameSyntax OrElse TypeOf symbolExpression Is MemberAccessExpressionSyntax Then
Return symbolExpression
End If
If TypeOf symbolExpression Is QualifiedNameSyntax Then
Dim qualifiedName = DirectCast(symbolExpression, QualifiedNameSyntax)
Return SyntaxFactory.SimpleMemberAccessExpression(qualifiedName.Left, qualifiedName.Right) _
.WithAdditionalAnnotations(Simplifier.Annotation)
End If
Return Nothing
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 System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.ConvertTypeOfToNameOf
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertTypeOfToNameOf
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.ConvertTypeOfToNameOf), [Shared]>
Friend Class VisualBasicConvertGetTypeToNameOfCodeFixProvider
Inherits AbstractConvertTypeOfToNameOfCodeFixProvider
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Protected Overrides Function GetCodeFixTitle() As String
Return VisualBasicCodeFixesResources.Convert_GetType_to_NameOf
End Function
Protected Overrides Function GetSymbolTypeExpression(semanticModel As SemanticModel, node As SyntaxNode, cancellationToken As CancellationToken) As SyntaxNode
Dim expression = DirectCast(node, MemberAccessExpressionSyntax).Expression
Dim type = DirectCast(expression, GetTypeExpressionSyntax).Type
Dim symbolType = semanticModel.GetSymbolInfo(type, cancellationToken).Symbol.GetSymbolType()
Dim symbolExpression = symbolType.GenerateExpressionSyntax()
If TypeOf symbolExpression Is IdentifierNameSyntax OrElse TypeOf symbolExpression Is MemberAccessExpressionSyntax Then
Return symbolExpression
End If
If TypeOf symbolExpression Is QualifiedNameSyntax Then
Dim qualifiedName = DirectCast(symbolExpression, QualifiedNameSyntax)
Return SyntaxFactory.SimpleMemberAccessExpression(qualifiedName.Left, qualifiedName.Right) _
.WithAdditionalAnnotations(Simplifier.Annotation)
End If
Return Nothing
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Compilers/VisualBasic/Portable/Lowering/SyntheticBoundNodeFactory.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Text
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' A helper class for synthesizing quantities of code.
''' </summary>
''' <remarks>
''' Code if the #If False out is code ported from C# that isn't currently used, and
''' hence has no code coverage. It may or may not work correctly, but should be a useful
''' starting point.
''' </remarks>
Friend Class SyntheticBoundNodeFactory
Private _currentClass As NamedTypeSymbol
Private _syntax As SyntaxNode
Public ReadOnly Diagnostics As BindingDiagnosticBag
Public ReadOnly TopLevelMethod As MethodSymbol
Public ReadOnly CompilationState As TypeCompilationState
Public Property CurrentMethod As MethodSymbol
Public ReadOnly Property CurrentType As NamedTypeSymbol
Get
Return Me._currentClass
End Get
End Property
Public ReadOnly Property Compilation As VisualBasicCompilation
Get
Return Me.CompilationState.Compilation
End Get
End Property
Public Property Syntax As SyntaxNode
Get
Return _syntax
End Get
Set(value As SyntaxNode)
_syntax = value
End Set
End Property
Private ReadOnly Property EmitModule As PEModuleBuilder
Get
Return If(Me.CompilationState IsNot Nothing, Me.CompilationState.ModuleBuilderOpt, Nothing)
End Get
End Property
Public Sub New(topLevelMethod As MethodSymbol, currentMethod As MethodSymbol, node As SyntaxNode, compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag)
Me.New(topLevelMethod, currentMethod, Nothing, node, compilationState, diagnostics)
End Sub
Public Sub New(topLevelMethod As MethodSymbol, currentMethod As MethodSymbol, currentClass As NamedTypeSymbol, node As SyntaxNode, compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag)
Debug.Assert(compilationState IsNot Nothing)
Me.CompilationState = compilationState
Me.CurrentMethod = currentMethod
Me.TopLevelMethod = topLevelMethod
Me._currentClass = currentClass
Me._syntax = node
Me.Diagnostics = diagnostics
End Sub
Public Sub AddNestedType(nestedType As NamedTypeSymbol)
Dim [module] As PEModuleBuilder = Me.EmitModule
If [module] IsNot Nothing Then
[module].AddSynthesizedDefinition(_currentClass, nestedType.GetCciAdapter())
End If
End Sub
Public Sub OpenNestedType(nestedType As NamedTypeSymbol)
AddNestedType(nestedType)
Me._currentClass = nestedType
Me.CurrentMethod = Nothing
End Sub
Public Sub AddField(containingType As NamedTypeSymbol, field As FieldSymbol)
Dim [module] As PEModuleBuilder = Me.EmitModule
If [module] IsNot Nothing Then
[module].AddSynthesizedDefinition(containingType, field.GetCciAdapter())
End If
End Sub
Public Sub AddMethod(containingType As NamedTypeSymbol, method As MethodSymbol)
Dim [module] As PEModuleBuilder = Me.EmitModule
If [module] IsNot Nothing Then
[module].AddSynthesizedDefinition(containingType, method.GetCciAdapter())
End If
End Sub
Public Sub AddProperty(containingType As NamedTypeSymbol, prop As PropertySymbol)
Dim [module] As PEModuleBuilder = Me.EmitModule
If [module] IsNot Nothing Then
[module].AddSynthesizedDefinition(containingType, prop.GetCciAdapter())
End If
End Sub
Public Function StateMachineField(type As TypeSymbol, implicitlyDefinedBy As Symbol, name As String, Optional accessibility As Accessibility = Accessibility.Private) As SynthesizedFieldSymbol
Dim result As New StateMachineFieldSymbol(Me.CurrentType, implicitlyDefinedBy, type, name, accessibility:=accessibility)
AddField(CurrentType, result)
Return result
End Function
Public Function StateMachineField(type As TypeSymbol, implicitlyDefinedBy As Symbol, name As String, synthesizedKind As SynthesizedLocalKind, slotIndex As Integer, Optional accessibility As Accessibility = Accessibility.Private) As SynthesizedFieldSymbol
Dim result As New StateMachineFieldSymbol(Me.CurrentType, implicitlyDefinedBy, type, name, synthesizedKind, slotIndex, accessibility)
AddField(CurrentType, result)
Return result
End Function
Public Function StateMachineField(type As TypeSymbol, implicitlyDefinedBy As Symbol, name As String, slotDebugInfo As LocalSlotDebugInfo, slotIndex As Integer, Optional accessibility As Accessibility = Accessibility.Private) As SynthesizedFieldSymbol
Dim result As New StateMachineFieldSymbol(Me.CurrentType, implicitlyDefinedBy, type, name, slotDebugInfo, slotIndex, accessibility)
AddField(CurrentType, result)
Return result
End Function
#If False Then
Public Sub AddField(field As FieldSymbol)
EmitModule.AddCompilerGeneratedDefinition(_currentClass, field)
End Sub
Public Function AddField(type As TypeSymbol, name As [String], Optional isPublic As Boolean = False) As SynthesizedFieldSymbol
Dim result = New SynthesizedFieldSymbol(_currentClass, _currentClass, type, name, isPublic:=isPublic)
AddField(result)
Return result
End Function
Public Sub AddMethod(method As MethodSymbol)
EmitModule.AddCompilerGeneratedDefinition(_currentClass, method)
Me.CurrentMethod = method
End Sub
#End If
Public Function GenerateLabel(prefix As String) As GeneratedLabelSymbol
Return New GeneratedLabelSymbol(prefix)
End Function
Public Function [Me]() As BoundMeReference
Debug.Assert(Me.CurrentMethod IsNot Nothing AndAlso Not Me.CurrentMethod.IsShared)
Dim boundNode = New BoundMeReference(_syntax, Me.CurrentMethod.MeParameter.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function ReferenceOrByrefMe() As BoundExpression
Debug.Assert(Me.CurrentMethod IsNot Nothing AndAlso Not Me.CurrentMethod.IsShared)
Dim type = Me.CurrentMethod.MeParameter.Type
Dim boundNode = If(type.IsReferenceType,
DirectCast(Me.Me, BoundExpression),
New BoundValueTypeMeReference(_syntax, Me.CurrentMethod.MeParameter.Type))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Base() As BoundMyBaseReference
Debug.Assert(Me.CurrentMethod IsNot Nothing AndAlso Not Me.CurrentMethod.IsShared)
Dim boundNode = New BoundMyBaseReference(_syntax, Me.CurrentMethod.MeParameter.Type.BaseTypeNoUseSiteDiagnostics)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Parameter(p As ParameterSymbol) As BoundParameter
Dim boundNode = New BoundParameter(_syntax, p, p.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Field(receiver As BoundExpression, f As FieldSymbol, isLValue As Boolean) As BoundFieldAccess
Dim boundNode = New BoundFieldAccess(_syntax, receiver, f, isLValue, f.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [Property](member As WellKnownMember) As BoundExpression
Dim propertySym As PropertySymbol = WellKnownMember(Of PropertySymbol)(member)
'if (propertySym == null) return BoundBadExpression
Debug.Assert(propertySym.IsShared)
Return [Call](Nothing, propertySym.GetMethod())
End Function
Public Function [Property](receiver As BoundExpression, member As WellKnownMember) As BoundExpression
Dim propertySym As PropertySymbol = WellKnownMember(Of PropertySymbol)(member)
Debug.Assert(receiver.Type.GetMembers(propertySym.Name).OfType(Of PropertySymbol)().Single() = propertySym)
'if (propertySym == null) return BoundBadExpression
Debug.Assert(Not propertySym.IsShared)
Return [Call](receiver, propertySym.GetMethod())
End Function
Public Function [Property](receiver As BoundExpression, name As String) As BoundExpression
' TODO: unroll loop and add diagnostics for failure
' TODO: should we use GetBaseProperty() to ensure we generate a call to the overridden method?
' TODO: replace this with a mechanism that uses WellKnownMember instead of string names.
Dim propertySym = receiver.Type.GetMembers(name).OfType(Of PropertySymbol)().[Single]()
Debug.Assert(Not propertySym.IsShared)
Return [Call](receiver, propertySym.GetMethod())
End Function
Public Function [Property](receiver As NamedTypeSymbol, name As String) As BoundExpression
' TODO: unroll loop and add diagnostics for failure
Dim propertySym = receiver.GetMembers(name).OfType(Of PropertySymbol)().[Single]()
Debug.Assert(propertySym.IsShared)
Return [Call](Nothing, propertySym.GetMethod())
End Function
Public Function SpecialType(st As SpecialType) As NamedTypeSymbol
Return Binder.GetSpecialType(Me.Compilation, st, _syntax, Me.Diagnostics)
End Function
Public Function NullableOf(type As TypeSymbol) As NamedTypeSymbol
' Get the Nullable type
Dim nullableType As NamedTypeSymbol = SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Nullable_T)
If nullableType.IsErrorType Then
Return nullableType
End If
Debug.Assert(nullableType.IsGenericType AndAlso nullableType.Arity = 1)
' Construct the Nullable(Of T).
Return nullableType.Construct(ImmutableArray.Create(type))
End Function
Public Function WellKnownType(wt As WellKnownType) As NamedTypeSymbol
Return Binder.GetWellKnownType(Me.Compilation, wt, _syntax, Me.Diagnostics)
End Function
Public Function WellKnownMember(Of T As Symbol)(wm As WellKnownMember, Optional isOptional As Boolean = False) As T
Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing
Dim member = DirectCast(Binder.GetWellKnownTypeMember(Me.Compilation, wm, useSiteInfo), T)
If useSiteInfo.DiagnosticInfo IsNot Nothing AndAlso isOptional Then
member = Nothing
Else
Me.Diagnostics.Add(useSiteInfo, _syntax)
End If
Return member
End Function
Public Function SpecialMember(sm As SpecialMember) As Symbol
Dim memberSymbol As Symbol = Me.Compilation.GetSpecialTypeMember(sm)
Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol)
If memberSymbol Is Nothing Then
Dim memberDescriptor As MemberDescriptor = SpecialMembers.GetDescriptor(sm)
useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(GetDiagnosticForMissingRuntimeHelper(memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name, CompilationState.Compilation.Options.EmbedVbCoreRuntime))
Else
useSiteInfo = Binder.GetUseSiteInfoForMemberAndContainingType(memberSymbol)
End If
Me.Diagnostics.Add(useSiteInfo, _syntax)
Return memberSymbol
End Function
#If False Then
Public Function SpecialMember(sm As SpecialMember) As Symbol
Return Compilation.GetSpecialTypeMember(sm)
End Function
#End If
Public Function Assignment(left As BoundExpression, right As BoundExpression) As BoundExpressionStatement
Return ExpressionStatement(AssignmentExpression(left, right))
End Function
Public Function ExpressionStatement(expr As BoundExpression) As BoundExpressionStatement
Dim boundNode = New BoundExpressionStatement(_syntax, expr)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Assignment expressions in lowered form should always have suppressObjectClone = True
''' </summary>
Public Function AssignmentExpression(left As BoundExpression, right As BoundExpression) As BoundAssignmentOperator
Debug.Assert(left.Type.IsSameTypeIgnoringAll(right.Type) OrElse right.Type.IsErrorType() OrElse left.Type.IsErrorType())
Dim boundNode = New BoundAssignmentOperator(_syntax, left, right, True)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function ReferenceAssignment(byRefLocal As LocalSymbol, lValue As BoundExpression) As BoundReferenceAssignment
Debug.Assert(TypeSymbol.Equals(byRefLocal.Type, lValue.Type, TypeCompareKind.ConsiderEverything))
Debug.Assert(byRefLocal.IsByRef)
Dim boundNode = New BoundReferenceAssignment(_syntax, Local(byRefLocal, isLValue:=True), lValue, isLValue:=True, type:=lValue.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Block(statements As ImmutableArray(Of BoundStatement)) As BoundBlock
Return Block(ImmutableArray(Of LocalSymbol).Empty, statements)
End Function
Public Function Block(locals As ImmutableArray(Of LocalSymbol), statements As ImmutableArray(Of BoundStatement)) As BoundBlock
Dim boundNode = New BoundBlock(_syntax, Nothing, locals, statements)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Block() As BoundBlock
Return Block(ImmutableArray(Of BoundStatement).Empty)
End Function
Public Function Block(ParamArray statements As BoundStatement()) As BoundBlock
Return Block(ImmutableArray.Create(Of BoundStatement)(statements))
End Function
Public Function Block(locals As ImmutableArray(Of LocalSymbol), ParamArray statements As BoundStatement()) As BoundBlock
Return Block(locals, ImmutableArray.Create(Of BoundStatement)(statements))
End Function
Public Function StatementList() As BoundStatementList
Return StatementList(ImmutableArray(Of BoundStatement).Empty)
End Function
Public Function StatementList(statements As ImmutableArray(Of BoundStatement)) As BoundStatementList
Dim boundNode As New BoundStatementList(Syntax, statements)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function StatementList(first As BoundStatement, second As BoundStatement) As BoundStatementList
Dim boundNode As New BoundStatementList(Syntax, ImmutableArray.Create(first, second))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [Return](Optional expression As BoundExpression = Nothing) As BoundReturnStatement
If expression IsNot Nothing Then
' If necessary, add a conversion on the return expression.
Dim useSiteInfo As New CompoundUseSiteInfo(Of AssemblySymbol)(Diagnostics, Me.Compilation.Assembly)
Dim conversion = Conversions.ClassifyDirectCastConversion(expression.Type, Me.CurrentMethod.ReturnType, useSiteInfo)
Debug.Assert(Conversions.IsWideningConversion(conversion))
Diagnostics.Add(expression, useSiteInfo)
If Not Conversions.IsIdentityConversion(conversion) Then
expression = New BoundDirectCast(Me.Syntax, expression, conversion, Me.CurrentMethod.ReturnType)
End If
End If
Dim boundNode = New BoundReturnStatement(_syntax, expression, Nothing, Nothing)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#If False Then
Public Sub Generate(body As BoundStatement)
Debug.Assert(Me.CurrentMethod IsNot Nothing)
If body.Kind <> BoundKind.Block Then
body = Block(body)
End If
Me.compilationState.AddGeneratedMethod(Me.CurrentMethod, body)
Me.CurrentMethod = Nothing
End Sub
Public Function SynthesizedImplementation(type As NamedTypeSymbol, methodName As String, Optional debuggerHidden As Boolean = False) As SynthesizedImplementationMethod
' TODO: use WellKnownMembers instead of strings.
Dim methodToImplement = DirectCast(type.GetMembers(methodName).[Single](), MethodSymbol)
Dim result = New SynthesizedImplementationMethod(methodToImplement, CurrentClass, debuggerHidden:=debuggerHidden)
EmitModule.AddCompilerGeneratedDefinition(_currentClass, result)
Me.MethodImplementations.Add(New MethodImplementation(result, methodToImplement))
Me.CurrentMethod = result
Return result
End Function
Public Function SynthesizedPropertyImplementation(type As NamedTypeSymbol, propertyName As String, Optional debuggerHidden As Boolean = False) As SynthesizedImplementationMethod
' TODO: use WellKnownMembers instead of strings.
' TODO: share code with SynthesizedImplementation(...)
Dim methodToImplement = (DirectCast(type.GetMembers(propertyName).[Single](), PropertySymbol)).GetMethod
Dim result = New SynthesizedImplementationMethod(methodToImplement, CurrentClass, debuggerHidden:=debuggerHidden)
EmitModule.AddCompilerGeneratedDefinition(_currentClass, result)
Me.MethodImplementations.Add(New MethodImplementation(result, methodToImplement))
Me.CurrentMethod = result
Return result
End Function
#End If
Public Function SynthesizedLocal(type As TypeSymbol, Optional kind As SynthesizedLocalKind = SynthesizedLocalKind.LoweringTemp, Optional syntax As SyntaxNode = Nothing) As LocalSymbol
Return New SynthesizedLocal(Me.CurrentMethod, type, kind, syntax)
End Function
Public Function SynthesizedParameter(type As TypeSymbol, name As String, Optional container As MethodSymbol = Nothing, Optional ordinal As Integer = 0) As ParameterSymbol
Return New SynthesizedParameterSymbol(container, type, ordinal, False, name)
End Function
#If False Then
Public Function Binary(kind As BinaryOperatorKind, type As TypeSymbol, left As BoundExpression, right As BoundExpression, isChecked As Boolean) As BoundBinaryOperator
Dim boundNode = New BoundBinaryOperator(Me._syntax, kind, left, right, isChecked, type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function IntNotEqual(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Return Binary(BinaryOperatorKind.NotEquals, SpecialType(Roslyn.Compilers.SpecialType.System_Boolean), left, right, False)
End Function
#End If
Public Function LogicalAndAlso(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Return Binary(BinaryOperatorKind.AndAlso, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right)
End Function
Public Function LogicalOrElse(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Return Binary(BinaryOperatorKind.OrElse, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right)
End Function
Public Function IntEqual(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Return Binary(BinaryOperatorKind.Equals, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right)
End Function
Public Function IntLessThan(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Return Binary(BinaryOperatorKind.LessThan, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right)
End Function
Public Function Literal(value As Boolean) As BoundLiteral
Dim boundNode = New BoundLiteral(_syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Literal(value As Integer) As BoundLiteral
Dim boundNode = New BoundLiteral(_syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function BadExpression(ParamArray subExpressions As BoundExpression()) As BoundExpression
Dim boundNode = New BoundBadExpression(_syntax, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(subExpressions), ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [New](type As NamedTypeSymbol) As BoundObjectCreationExpression
' TODO: add diagnostics for when things fall apart
Dim ctor = type.InstanceConstructors.Single(Function(c) c.ParameterCount = 0)
Return [New](ctor)
End Function
Public Function [New](ctor As MethodSymbol, ParamArray args As BoundExpression()) As BoundObjectCreationExpression
Dim boundNode = New BoundObjectCreationExpression(_syntax, ctor, ImmutableArray.Create(args), Nothing, ctor.ContainingType)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [New](ctor As MethodSymbol) As BoundObjectCreationExpression
Dim boundNode = New BoundObjectCreationExpression(_syntax,
ctor,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
ctor.ContainingType)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#If False Then
' These function do their own overload resolution. Probably will remove them or replace with helpers that use correct overload resolution.
Public Function StaticCall(receiver As TypeSymbol, name As String, ParamArray args As BoundExpression()) As BoundExpression
Return StaticCall(receiver, name, ImmutableArray(Of TypeSymbol).Empty, args)
End Function
Public Function StaticCall(receiver As TypeSymbol, name As String, typeArgs As ImmutableArray(Of TypeSymbol), ParamArray args As BoundExpression()) As BoundExpression
Dim m As MethodSymbol = FindMethod(receiver, name, typeArgs, args)
If m Is Nothing Then
Return New BoundBadExpression(_syntax, Nothing, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundNode).CreateFrom(Of BoundExpression)(args), receiver)
End If
Return [Call](Nothing, m, args)
End Function
Function FindMethod(receiver As TypeSymbol, name As String, typeArgs As ImmutableArray(Of TypeSymbol), args As BoundExpression()) As MethodSymbol
Dim found As MethodSymbol = Nothing
Dim ambiguous As Boolean = False
Dim candidates As ImmutableArray(Of Symbol) = receiver.GetMembers(name)
For Each m In candidates
Dim method = TryCast(m, MethodSymbol)
If method Is Nothing OrElse method.Arity <> typeArgs.Count OrElse method.ParameterCount <> args.Length Then
Continue For
End If
If method.Arity <> 0 Then
method = method.Construct(typeArgs)
End If
Dim parameters = method.Parameters
Dim exact As Boolean = True
For i = 0 To args.Length - 1
If parameters(i).IsByRef OrElse Not _compilation.ClassifyConversion(args(i).Type, parameters(i).Type).IsWidening Then
GoTo nextm
End If
exact = exact AndAlso args(i).Type = parameters(i).Type
Next
If exact Then
Return method
End If
If found IsNot Nothing Then
ambiguous = True
End If
found = method
nextm:
Next
' TODO: (EXPRTREE) These error codes are probably not correct. Fix them.
If ambiguous Then
ReportLibraryProblem(ERRID.ERR_MissingRuntimeHelper, receiver, name, typeArgs, args) ' C#: ERR_LibraryMethodNotUnique
ElseIf found Is Nothing Then
ReportLibraryProblem(ERRID.ERR_MissingRuntimeHelper, receiver, name, typeArgs, args) ' C#: ERR_LibraryMethodNotFound
End If
Return found
End Function
Function ReportLibraryProblem(code As ERRID, receiver As TypeSymbol, name As String, typeArgs As ImmutableArray(Of TypeSymbol), args As BoundExpression()) As MethodSymbol
Dim methodSig = New StringBuilder()
Dim wasFirst As Boolean
methodSig.Append(name)
If Not typeArgs.IsNullOrEmpty Then
methodSig.Append("(Of ")
wasFirst = True
For Each t In typeArgs
If Not wasFirst Then
methodSig.Append(", ")
End If
methodSig.Append(t.ToDisplayString())
wasFirst = False
Next
methodSig.Append(")")
End If
methodSig.Append("(")
wasFirst = True
For Each a In args
If Not wasFirst Then
methodSig.Append(", ")
End If
methodSig.Append(a.Type.ToDisplayString())
wasFirst = False
Next
methodSig.Append(")")
_diagnostics.Add(code, _syntax.GetLocation(), receiver, methodSig.ToString())
Return Nothing
End Function
#End If
Public Function [Call](receiver As BoundExpression, method As MethodSymbol) As BoundCall
Return [Call](receiver, method, ImmutableArray(Of BoundExpression).Empty)
End Function
Public Function [Call](receiver As BoundExpression, method As MethodSymbol, ParamArray args As BoundExpression()) As BoundCall
Return [Call](receiver, method, ImmutableArray.Create(Of BoundExpression)(args))
End Function
Public Function [Call](receiver As BoundExpression, method As MethodSymbol, args As ImmutableArray(Of BoundExpression)) As BoundCall
Debug.Assert(method.ParameterCount = args.Length)
Dim boundNode = New BoundCall(
Syntax,
method,
Nothing,
receiver,
args,
Nothing,
suppressObjectClone:=True,
type:=method.ReturnType)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [If](condition As BoundExpression, thenClause As BoundStatement, elseClause As BoundStatement) As BoundStatement
Debug.Assert(thenClause IsNot Nothing AndAlso elseClause IsNot Nothing)
Dim afterif = New GeneratedLabelSymbol("afterif")
Dim alt = New GeneratedLabelSymbol("alternative")
Dim boundCondGoto = New BoundConditionalGoto(_syntax, condition, False, alt)
boundCondGoto.SetWasCompilerGenerated()
Return Block(boundCondGoto, thenClause, [Goto](afterif), Label(alt), elseClause, Label(afterif))
End Function
Public Function TernaryConditionalExpression(condition As BoundExpression, ifTrue As BoundExpression, ifFalse As BoundExpression) As BoundTernaryConditionalExpression
Debug.Assert(ifTrue IsNot Nothing)
Debug.Assert(ifFalse IsNot Nothing)
Return New BoundTernaryConditionalExpression(Me.Syntax, condition, ifTrue, ifFalse, Nothing, ifTrue.Type).MakeCompilerGenerated()
End Function
Public Function [TryCast](expression As BoundExpression, type As TypeSymbol) As BoundTryCast
Debug.Assert(expression IsNot Nothing)
Debug.Assert(Not expression.IsNothingLiteral) ' Not supported yet
Debug.Assert(expression.Type.IsReferenceType) 'Others are not supported yet
Debug.Assert(type.IsReferenceType) 'Others are not supported yet
Debug.Assert(Not expression.Type.IsErrorType)
Debug.Assert(Not type.IsErrorType)
Return New BoundTryCast(Me.Syntax, expression, Conversions.ClassifyTryCastConversion(expression.Type, type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded), type)
End Function
Public Function [DirectCast](expression As BoundExpression, type As TypeSymbol) As BoundDirectCast
Debug.Assert(expression IsNot Nothing)
Debug.Assert(expression.IsNothingLiteral OrElse expression.Type.IsReferenceType OrElse expression.Type.IsTypeParameter()) 'Others are not supported yet
Debug.Assert(type.IsReferenceType OrElse (type.IsTypeParameter AndAlso expression.IsNothingLiteral)) 'Others are not supported yet
Debug.Assert(expression.Type Is Nothing OrElse Not expression.Type.IsErrorType)
Debug.Assert(Not type.IsErrorType)
Return New BoundDirectCast(Me.Syntax,
expression,
If(expression.IsNothingLiteral,
ConversionKind.WideningNothingLiteral,
Conversions.ClassifyDirectCastConversion(expression.Type, type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)),
type)
End Function
Public Function [If](condition As BoundExpression, thenClause As BoundStatement) As BoundStatement
Return [If](condition, thenClause, Block())
End Function
Public Function [Throw](Optional e As BoundExpression = Nothing) As BoundThrowStatement
Dim boundNode = New BoundThrowStatement(_syntax, e)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Local(localSym As LocalSymbol, isLValue As Boolean) As BoundLocal
Dim boundNode = New BoundLocal(_syntax, localSym, isLValue, localSym.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Sequence(temps As ImmutableArray(Of LocalSymbol), ParamArray parts As BoundExpression()) As BoundExpression
Debug.Assert(parts IsNot Nothing AndAlso parts.Length > 0)
Dim statements(parts.Length - 1 - 1) As BoundExpression
For i = 0 To parts.Length - 1 - 1
statements(i) = parts(i)
Next
Dim lastExpression = parts(parts.Length - 1)
Return Sequence(temps, statements.AsImmutableOrNull, lastExpression)
End Function
Public Function Sequence(temp As LocalSymbol, ParamArray parts As BoundExpression()) As BoundExpression
Return Sequence(ImmutableArray.Create(Of LocalSymbol)(temp), parts)
End Function
Public Function Sequence(ParamArray parts As BoundExpression()) As BoundExpression
Return Sequence(ImmutableArray(Of LocalSymbol).Empty, parts)
End Function
Public Function Sequence(locals As ImmutableArray(Of LocalSymbol), sideEffects As ImmutableArray(Of BoundExpression), result As BoundExpression) As BoundExpression
Dim boundNode = New BoundSequence(_syntax, locals, sideEffects, result, result.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [Select](ex As BoundExpression, sections As IEnumerable(Of BoundCaseBlock)) As BoundStatement
Dim sectionsArray = ImmutableArray.CreateRange(Of BoundCaseBlock)(sections)
If sectionsArray.Length = 0 Then
Return Me.ExpressionStatement(ex)
End If
Dim breakLabel As GeneratedLabelSymbol = New GeneratedLabelSymbol("break")
CheckSwitchSections(sectionsArray)
Dim boundNode = New BoundSelectStatement(_syntax, Me.ExpressionStatement(ex), Nothing, sectionsArray, True, breakLabel)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary> Check for (and assert that there are no) duplicate case labels in the switch. </summary>
<Conditional("DEBUG")>
Private Sub CheckSwitchSections(sections As ImmutableArray(Of BoundCaseBlock))
Dim labels = New HashSet(Of Integer)()
For Each s In sections
For Each l As BoundSimpleCaseClause In s.CaseStatement.CaseClauses
Dim v1 = l.ValueOpt.ConstantValueOpt.Int32Value
Debug.Assert(Not labels.Contains(v1))
labels.Add(v1)
Next
Next
End Sub
'Public Function SwitchSection(value As Integer, ParamArray statements As BoundStatement()) As BoundCaseBlock
' Dim boundCaseClause = New BoundSimpleCaseClause(_syntax, Literal(value), Nothing)
' boundCaseClause.SetWasCompilerGenerated()
' Dim boundCaseStatement = New BoundCaseStatement(_syntax, ImmutableArray(Of BoundCaseClause).CreateFrom(boundCaseClause), Nothing)
' boundCaseStatement.SetWasCompilerGenerated()
' Dim boundCaseBlock = New BoundCaseBlock(_syntax, boundCaseStatement, Block(statements))
' boundCaseBlock.SetWasCompilerGenerated()
' Return boundCaseBlock
'End Function
Public Function SwitchSection(values As List(Of Integer), ParamArray statements As BoundStatement()) As BoundCaseBlock
Dim builder = ArrayBuilder(Of BoundCaseClause).GetInstance()
For Each i In values
Dim boundCaseClause = New BoundSimpleCaseClause(_syntax, Literal(i), Nothing)
boundCaseClause.SetWasCompilerGenerated()
builder.Add(boundCaseClause)
Next
Dim boundCaseStatement = New BoundCaseStatement(_syntax, builder.ToImmutableAndFree(), Nothing)
boundCaseStatement.SetWasCompilerGenerated()
Dim boundCaseBlock = New BoundCaseBlock(_syntax, boundCaseStatement, Block(ImmutableArray.Create(Of BoundStatement)(statements)))
boundCaseBlock.SetWasCompilerGenerated()
Return boundCaseBlock
End Function
Public Function [Goto](label As LabelSymbol, Optional setWasCompilerGenerated As Boolean = True) As BoundGotoStatement
Dim boundNode = New BoundGotoStatement(_syntax, label, Nothing)
If setWasCompilerGenerated Then
boundNode.SetWasCompilerGenerated()
End If
Return boundNode
End Function
Public Function Label(labelSym As LabelSymbol) As BoundLabelStatement
Dim boundNode = New BoundLabelStatement(_syntax, labelSym)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Literal(value As String) As BoundLiteral
Dim boundNode = New BoundLiteral(_syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_String))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function StringLiteral(value As ConstantValue) As BoundLiteral
Debug.Assert(value.IsString OrElse value.IsNull)
Dim boundNode = New BoundLiteral(_syntax, value, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_String))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#If False Then
Public Function ArrayLength(array As BoundExpression) As BoundArrayLength
Debug.Assert(array.Type IsNot Nothing AndAlso array.Type.IsArrayType())
Return New BoundArrayLength(_syntax, array, SpecialType(Roslyn.Compilers.SpecialType.System_Int32))
End Function
Public Function ArrayAccessFirstElement(array As BoundExpression) As BoundArrayAccess
Debug.Assert(array.Type IsNot Nothing AndAlso array.Type.IsArrayType())
Dim rank As Integer = (DirectCast(array.Type, ArrayTypeSymbol)).Rank
Dim firstElementIndices As ImmutableArray(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance(rank, Literal(0)).ToReadOnlyAndFree()
Return ArrayAccess(array, firstElementIndices)
End Function
#End If
Public Function ArrayAccess(array As BoundExpression, isLValue As Boolean, ParamArray indices As BoundExpression()) As BoundArrayAccess
Return ArrayAccess(array, isLValue, indices.AsImmutableOrNull())
End Function
Public Function ArrayAccess(array As BoundExpression, isLValue As Boolean, indices As ImmutableArray(Of BoundExpression)) As BoundArrayAccess
Debug.Assert(array.Type IsNot Nothing AndAlso array.Type.IsArrayType())
Dim boundNode = New BoundArrayAccess(_syntax, array, indices, isLValue, (DirectCast(array.Type, ArrayTypeSymbol)).ElementType)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#If False Then
Public Function ThrowNull() As BoundStatement
Return [Throw](Null(_compilation.GetWellKnownType(Compilers.WellKnownType.System_Exception)))
End Function
#End If
Public Function BaseInitialization(ParamArray args As BoundExpression()) As BoundStatement
' TODO: add diagnostics for when things fall apart
Dim ctor = Me.CurrentMethod.MeParameter.Type.BaseTypeNoUseSiteDiagnostics.InstanceConstructors.Single(Function(c) c.ParameterCount = args.Length)
Dim boundNode = New BoundExpressionStatement(_syntax, [Call](Base(), ctor, args))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Shared Function HiddenSequencePoint(Optional statementOpt As BoundStatement = Nothing) As BoundStatement
Return New BoundSequencePoint(Nothing, statementOpt).MakeCompilerGenerated
End Function
Public Function Null() As BoundExpression
Dim nullLiteral As BoundExpression = New BoundLiteral(_syntax, ConstantValue.Null, Nothing)
nullLiteral.SetWasCompilerGenerated()
Return nullLiteral
End Function
Public Function Null(type As TypeSymbol) As BoundExpression
If Not type.IsTypeParameter() AndAlso type.IsReferenceType() Then
Dim nullLiteral As BoundExpression = New BoundLiteral(_syntax, ConstantValue.Null, type)
nullLiteral.SetWasCompilerGenerated()
Return nullLiteral
Else
Dim nullLiteral As BoundExpression = New BoundLiteral(_syntax, ConstantValue.Null, Nothing)
nullLiteral.SetWasCompilerGenerated()
Return Me.Convert(type, nullLiteral)
End If
End Function
Public Function Type(typeSym As TypeSymbol) As BoundTypeExpression
Dim boundNode = New BoundTypeExpression(_syntax, typeSym)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [Typeof](type As WellKnownType) As BoundExpression
Return [Typeof](WellKnownType(type))
End Function
Public Function [Typeof](typeSym As TypeSymbol) As BoundExpression
Dim boundNode = New BoundGetType(_syntax, Type(typeSym), WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Type))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function TypeArguments(typeArgs As ImmutableArray(Of TypeSymbol)) As BoundTypeArguments
Dim boundNode = New BoundTypeArguments(_syntax, typeArgs)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function MethodInfo(meth As WellKnownMember) As BoundExpression
Dim method = WellKnownMember(Of MethodSymbol)(meth)
If method Is Nothing Then
Return BadExpression()
Else
Return MethodInfo(method)
End If
End Function
Public Function MethodInfo(meth As SpecialMember) As BoundExpression
Dim method = DirectCast(SpecialMember(meth), MethodSymbol)
If method Is Nothing Then
Return BadExpression()
Else
Return MethodInfo(method)
End If
End Function
Public Function MethodInfo(method As MethodSymbol) As BoundExpression
Dim boundNode = New BoundMethodInfo(Syntax, method, WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_MethodInfo))
' Touch the method to be used to report use site diagnostics
WellKnownMember(Of MethodSymbol)(If(method.ContainingType.IsGenericType,
Microsoft.CodeAnalysis.WellKnownMember.System_Reflection_MethodBase__GetMethodFromHandle2,
Microsoft.CodeAnalysis.WellKnownMember.System_Reflection_MethodBase__GetMethodFromHandle))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function ConstructorInfo(meth As WellKnownMember) As BoundExpression
Dim method = WellKnownMember(Of MethodSymbol)(meth)
If method Is Nothing Then
Return BadExpression()
Else
Return ConstructorInfo(method)
End If
End Function
Public Function ConstructorInfo(meth As SpecialMember) As BoundExpression
Dim method = DirectCast(SpecialMember(meth), MethodSymbol)
If method Is Nothing Then
Return BadExpression()
Else
Return ConstructorInfo(method)
End If
End Function
Public Function ConstructorInfo(meth As MethodSymbol) As BoundExpression
Dim boundNode = New BoundMethodInfo(Syntax, meth, WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_ConstructorInfo))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#If False Then
Friend Function ConstructorInfo(ctor As MethodSymbol) As BoundExpression
Dim boundNode = New BoundMethodInfo(Syntax, ctor, WellKnownType(Compilers.WellKnownType.System_Reflection_ConstructorInfo))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#End If
Public Function FieldInfo(field As FieldSymbol) As BoundExpression
Dim boundNode = New BoundFieldInfo(_syntax, field, WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_FieldInfo))
' Touch the method to be used to report use site diagnostics
WellKnownMember(Of MethodSymbol)(If(field.ContainingType.IsGenericType,
Microsoft.CodeAnalysis.WellKnownMember.System_Reflection_FieldInfo__GetFieldFromHandle2,
Microsoft.CodeAnalysis.WellKnownMember.System_Reflection_FieldInfo__GetFieldFromHandle))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to the index portion of a method's metadata token.
''' </summary>
Public Function MethodDefIndex(method As MethodSymbol) As BoundExpression
Dim boundNode As New BoundMethodDefIndex(Syntax, method, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to the maximum value of the index portions of all method definition metadata tokens in current module.
''' </summary>
Public Function MaximumMethodDefIndex() As BoundExpression
Dim boundNode As New BoundMaximumMethodDefIndex(Syntax, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to the current module's MVID.
''' </summary>
Public Function ModuleVersionId(isLValue As Boolean) As BoundExpression
Dim boundNode As New BoundModuleVersionId(Syntax, isLValue, WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Guid))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to a text representation of the current module/s MVID.
''' </summary>
Public Function ModuleVersionIdString() As BoundExpression
Dim boundNode As New BoundModuleVersionIdString(Syntax, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_String))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to the root of the dynamic analysis payloads for a particular kind of dynamic analysis.
''' </summary>
''' <param name="analysisKind">Uniquely identifies the kind of dynamic analysis.</param>
''' <param name="payloadType">Type of an analysis payload cell for the particular analysis kind.</param>
Public Function InstrumentationPayloadRoot(analysisKind As Integer, payloadType As TypeSymbol, isLValue As Boolean) As BoundExpression
Dim boundNode As New BoundInstrumentationPayloadRoot(Syntax, analysisKind, isLValue, payloadType)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to the index of a source document in the table of debug source documents.
''' </summary>
Public Function SourceDocumentIndex(document As Cci.DebugSourceDocument) As BoundExpression
Dim boundNode As New BoundSourceDocumentIndex(Syntax, document, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Convert(type As TypeSymbol, arg As BoundExpression, Optional isChecked As Boolean = False) As BoundConversion
If arg.IsNothingLiteral() Then
Return Convert(type, arg, ConversionKind.WideningNothingLiteral, isChecked)
ElseIf type.IsErrorType() OrElse arg.Type.IsErrorType() Then
Return Convert(type, arg, ConversionKind.WideningReference, isChecked) ' will abort before code gen due to error, so doesn't matter if conversion kind is wrong.
Else
Return Convert(type, arg, Conversions.ClassifyConversion(arg.Type, type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key, isChecked)
End If
End Function
Public Function Convert(type As TypeSymbol, arg As BoundExpression, convKind As ConversionKind, Optional isChecked As Boolean = False) As BoundConversion
Debug.Assert((convKind And ConversionKind.UserDefined) = 0)
Dim boundNode = New BoundConversion(_syntax, arg, convKind, isChecked, True, ConstantValue.NotAvailable, type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Array(elementType As TypeSymbol, ParamArray elements As BoundExpression()) As BoundExpression
Return Array(elementType, elements.AsImmutableOrNull())
End Function
Public Function Array(elementType As TypeSymbol, elements As ImmutableArray(Of BoundExpression)) As BoundExpression
Dim arrayType = Me.Compilation.CreateArrayTypeSymbol(elementType)
Dim boundArrayInit = New BoundArrayInitialization(_syntax, elements, arrayType)
boundArrayInit.SetWasCompilerGenerated()
Return New BoundArrayCreation(_syntax, ImmutableArray.Create(Of BoundExpression)(Literal(elements.Length)), boundArrayInit, arrayType)
End Function
Public Function Array(elementType As TypeSymbol, bounds As ImmutableArray(Of BoundExpression), elements As ImmutableArray(Of BoundExpression)) As BoundExpression
Dim arrayType = Me.Compilation.CreateArrayTypeSymbol(elementType)
Dim arrayInitialization As BoundArrayInitialization = If(Not elements.IsDefaultOrEmpty, New BoundArrayInitialization(_syntax, elements, arrayType), Nothing)
arrayInitialization?.SetWasCompilerGenerated()
Dim arrayCreation As New BoundArrayCreation(_syntax, bounds, arrayInitialization, arrayType)
arrayCreation.SetWasCompilerGenerated()
Return arrayCreation
End Function
Public Function Conditional(condition As BoundExpression, consequence As BoundExpression, alternative As BoundExpression, type As TypeSymbol) As BoundTernaryConditionalExpression
Return New BoundTernaryConditionalExpression(Syntax, condition, consequence, alternative, Nothing, type)
End Function
Public Function BinaryConditional(left As BoundExpression, right As BoundExpression) As BoundBinaryConditionalExpression
Return New BoundBinaryConditionalExpression(Syntax, left, Nothing, Nothing, right, Nothing, left.Type)
End Function
Public Function Binary(kind As BinaryOperatorKind, type As TypeSymbol, left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Dim binOp = New BoundBinaryOperator(Syntax, kind, left, right, False, type)
binOp.SetWasCompilerGenerated()
Return binOp
End Function
Public Function ObjectReferenceEqual(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Dim boundNode = Binary(BinaryOperatorKind.Is, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function ReferenceIsNothing(operand As BoundExpression) As BoundBinaryOperator
Debug.Assert(operand.Type.IsReferenceType)
Dim boundNode = Binary(BinaryOperatorKind.Is, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), operand, Me.Null(operand.Type))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function ReferenceIsNotNothing(operand As BoundExpression) As BoundBinaryOperator
Debug.Assert(operand.Type.IsReferenceType)
Dim boundNode = Binary(BinaryOperatorKind.IsNot, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), operand, Me.Null(operand.Type))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [Not](expression As BoundExpression) As BoundExpression
Return New BoundUnaryOperator(expression.Syntax, UnaryOperatorKind.Not, expression, False, expression.Type)
End Function
Public Function [Try](tryBlock As BoundBlock,
catchBlocks As ImmutableArray(Of BoundCatchBlock),
Optional finallyBlock As BoundBlock = Nothing,
Optional exitLabel As LabelSymbol = Nothing) As BoundStatement
Return New BoundTryStatement(Syntax, tryBlock, catchBlocks, finallyBlock, exitLabel)
End Function
Public Function CatchBlocks(ParamArray blocks() As BoundCatchBlock) As ImmutableArray(Of BoundCatchBlock)
Return blocks.AsImmutableOrNull()
End Function
Public Function [Catch](local As LocalSymbol, block As BoundBlock, Optional isSynthesizedAsyncCatchAll As Boolean = False) As BoundCatchBlock
Dim m1 = WellKnownMember(Of MethodSymbol)(Microsoft.CodeAnalysis.WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError)
Dim m2 = WellKnownMember(Of MethodSymbol)(Microsoft.CodeAnalysis.WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError)
Return New BoundCatchBlock(Syntax, local, Me.Local(local, False), Nothing, Nothing, block,
hasErrors:=m1 Is Nothing OrElse m2 Is Nothing,
isSynthesizedAsyncCatchAll:=isSynthesizedAsyncCatchAll)
End Function
Public Function SequencePoint(syntax As SyntaxNode, statement As BoundStatement) As BoundStatement
Return New BoundSequencePoint(syntax, statement)
End Function
Public Function SequencePoint(syntax As SyntaxNode) As BoundStatement
Return New BoundSequencePoint(syntax, Nothing).MakeCompilerGenerated
End Function
Public Function SequencePointWithSpan(syntax As SyntaxNode, textSpan As TextSpan, boundStatement As BoundStatement) As BoundStatement
Return New BoundSequencePointWithSpan(syntax, boundStatement, textSpan)
End Function
Public Function NoOp(Optional flavor As NoOpStatementFlavor = NoOpStatementFlavor.Default) As BoundStatement
Return New BoundNoOpStatement(Me.Syntax, flavor).MakeCompilerGenerated
End Function
Public Sub CloseMethod(body As BoundStatement)
Debug.Assert(Me.CurrentMethod IsNot Nothing)
If body.Kind <> BoundKind.Block Then
body = Me.Block(body)
End If
CompilationState.AddSynthesizedMethod(Me.CurrentMethod, body)
Me.CurrentMethod = Nothing
End Sub
Public Function SpillSequence(locals As ImmutableArray(Of LocalSymbol), fields As ImmutableArray(Of FieldSymbol), statements As ImmutableArray(Of BoundStatement), valueOpt As BoundExpression) As BoundSpillSequence
Return New BoundSpillSequence(Me.Syntax, locals, fields, statements, valueOpt,
If(valueOpt Is Nothing,
Me.SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Void),
valueOpt.Type)).MakeCompilerGenerated()
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
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Text
Imports Microsoft.Cci
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' A helper class for synthesizing quantities of code.
''' </summary>
''' <remarks>
''' Code if the #If False out is code ported from C# that isn't currently used, and
''' hence has no code coverage. It may or may not work correctly, but should be a useful
''' starting point.
''' </remarks>
Friend Class SyntheticBoundNodeFactory
Private _currentClass As NamedTypeSymbol
Private _syntax As SyntaxNode
Public ReadOnly Diagnostics As BindingDiagnosticBag
Public ReadOnly TopLevelMethod As MethodSymbol
Public ReadOnly CompilationState As TypeCompilationState
Public Property CurrentMethod As MethodSymbol
Public ReadOnly Property CurrentType As NamedTypeSymbol
Get
Return Me._currentClass
End Get
End Property
Public ReadOnly Property Compilation As VisualBasicCompilation
Get
Return Me.CompilationState.Compilation
End Get
End Property
Public Property Syntax As SyntaxNode
Get
Return _syntax
End Get
Set(value As SyntaxNode)
_syntax = value
End Set
End Property
Private ReadOnly Property EmitModule As PEModuleBuilder
Get
Return If(Me.CompilationState IsNot Nothing, Me.CompilationState.ModuleBuilderOpt, Nothing)
End Get
End Property
Public Sub New(topLevelMethod As MethodSymbol, currentMethod As MethodSymbol, node As SyntaxNode, compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag)
Me.New(topLevelMethod, currentMethod, Nothing, node, compilationState, diagnostics)
End Sub
Public Sub New(topLevelMethod As MethodSymbol, currentMethod As MethodSymbol, currentClass As NamedTypeSymbol, node As SyntaxNode, compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag)
Debug.Assert(compilationState IsNot Nothing)
Me.CompilationState = compilationState
Me.CurrentMethod = currentMethod
Me.TopLevelMethod = topLevelMethod
Me._currentClass = currentClass
Me._syntax = node
Me.Diagnostics = diagnostics
End Sub
Public Sub AddNestedType(nestedType As NamedTypeSymbol)
Dim [module] As PEModuleBuilder = Me.EmitModule
If [module] IsNot Nothing Then
[module].AddSynthesizedDefinition(_currentClass, nestedType.GetCciAdapter())
End If
End Sub
Public Sub OpenNestedType(nestedType As NamedTypeSymbol)
AddNestedType(nestedType)
Me._currentClass = nestedType
Me.CurrentMethod = Nothing
End Sub
Public Sub AddField(containingType As NamedTypeSymbol, field As FieldSymbol)
Dim [module] As PEModuleBuilder = Me.EmitModule
If [module] IsNot Nothing Then
[module].AddSynthesizedDefinition(containingType, field.GetCciAdapter())
End If
End Sub
Public Sub AddMethod(containingType As NamedTypeSymbol, method As MethodSymbol)
Dim [module] As PEModuleBuilder = Me.EmitModule
If [module] IsNot Nothing Then
[module].AddSynthesizedDefinition(containingType, method.GetCciAdapter())
End If
End Sub
Public Sub AddProperty(containingType As NamedTypeSymbol, prop As PropertySymbol)
Dim [module] As PEModuleBuilder = Me.EmitModule
If [module] IsNot Nothing Then
[module].AddSynthesizedDefinition(containingType, prop.GetCciAdapter())
End If
End Sub
Public Function StateMachineField(type As TypeSymbol, implicitlyDefinedBy As Symbol, name As String, Optional accessibility As Accessibility = Accessibility.Private) As SynthesizedFieldSymbol
Dim result As New StateMachineFieldSymbol(Me.CurrentType, implicitlyDefinedBy, type, name, accessibility:=accessibility)
AddField(CurrentType, result)
Return result
End Function
Public Function StateMachineField(type As TypeSymbol, implicitlyDefinedBy As Symbol, name As String, synthesizedKind As SynthesizedLocalKind, slotIndex As Integer, Optional accessibility As Accessibility = Accessibility.Private) As SynthesizedFieldSymbol
Dim result As New StateMachineFieldSymbol(Me.CurrentType, implicitlyDefinedBy, type, name, synthesizedKind, slotIndex, accessibility)
AddField(CurrentType, result)
Return result
End Function
Public Function StateMachineField(type As TypeSymbol, implicitlyDefinedBy As Symbol, name As String, slotDebugInfo As LocalSlotDebugInfo, slotIndex As Integer, Optional accessibility As Accessibility = Accessibility.Private) As SynthesizedFieldSymbol
Dim result As New StateMachineFieldSymbol(Me.CurrentType, implicitlyDefinedBy, type, name, slotDebugInfo, slotIndex, accessibility)
AddField(CurrentType, result)
Return result
End Function
#If False Then
Public Sub AddField(field As FieldSymbol)
EmitModule.AddCompilerGeneratedDefinition(_currentClass, field)
End Sub
Public Function AddField(type As TypeSymbol, name As [String], Optional isPublic As Boolean = False) As SynthesizedFieldSymbol
Dim result = New SynthesizedFieldSymbol(_currentClass, _currentClass, type, name, isPublic:=isPublic)
AddField(result)
Return result
End Function
Public Sub AddMethod(method As MethodSymbol)
EmitModule.AddCompilerGeneratedDefinition(_currentClass, method)
Me.CurrentMethod = method
End Sub
#End If
Public Function GenerateLabel(prefix As String) As GeneratedLabelSymbol
Return New GeneratedLabelSymbol(prefix)
End Function
Public Function [Me]() As BoundMeReference
Debug.Assert(Me.CurrentMethod IsNot Nothing AndAlso Not Me.CurrentMethod.IsShared)
Dim boundNode = New BoundMeReference(_syntax, Me.CurrentMethod.MeParameter.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function ReferenceOrByrefMe() As BoundExpression
Debug.Assert(Me.CurrentMethod IsNot Nothing AndAlso Not Me.CurrentMethod.IsShared)
Dim type = Me.CurrentMethod.MeParameter.Type
Dim boundNode = If(type.IsReferenceType,
DirectCast(Me.Me, BoundExpression),
New BoundValueTypeMeReference(_syntax, Me.CurrentMethod.MeParameter.Type))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Base() As BoundMyBaseReference
Debug.Assert(Me.CurrentMethod IsNot Nothing AndAlso Not Me.CurrentMethod.IsShared)
Dim boundNode = New BoundMyBaseReference(_syntax, Me.CurrentMethod.MeParameter.Type.BaseTypeNoUseSiteDiagnostics)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Parameter(p As ParameterSymbol) As BoundParameter
Dim boundNode = New BoundParameter(_syntax, p, p.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Field(receiver As BoundExpression, f As FieldSymbol, isLValue As Boolean) As BoundFieldAccess
Dim boundNode = New BoundFieldAccess(_syntax, receiver, f, isLValue, f.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [Property](member As WellKnownMember) As BoundExpression
Dim propertySym As PropertySymbol = WellKnownMember(Of PropertySymbol)(member)
'if (propertySym == null) return BoundBadExpression
Debug.Assert(propertySym.IsShared)
Return [Call](Nothing, propertySym.GetMethod())
End Function
Public Function [Property](receiver As BoundExpression, member As WellKnownMember) As BoundExpression
Dim propertySym As PropertySymbol = WellKnownMember(Of PropertySymbol)(member)
Debug.Assert(receiver.Type.GetMembers(propertySym.Name).OfType(Of PropertySymbol)().Single() = propertySym)
'if (propertySym == null) return BoundBadExpression
Debug.Assert(Not propertySym.IsShared)
Return [Call](receiver, propertySym.GetMethod())
End Function
Public Function [Property](receiver As BoundExpression, name As String) As BoundExpression
' TODO: unroll loop and add diagnostics for failure
' TODO: should we use GetBaseProperty() to ensure we generate a call to the overridden method?
' TODO: replace this with a mechanism that uses WellKnownMember instead of string names.
Dim propertySym = receiver.Type.GetMembers(name).OfType(Of PropertySymbol)().[Single]()
Debug.Assert(Not propertySym.IsShared)
Return [Call](receiver, propertySym.GetMethod())
End Function
Public Function [Property](receiver As NamedTypeSymbol, name As String) As BoundExpression
' TODO: unroll loop and add diagnostics for failure
Dim propertySym = receiver.GetMembers(name).OfType(Of PropertySymbol)().[Single]()
Debug.Assert(propertySym.IsShared)
Return [Call](Nothing, propertySym.GetMethod())
End Function
Public Function SpecialType(st As SpecialType) As NamedTypeSymbol
Return Binder.GetSpecialType(Me.Compilation, st, _syntax, Me.Diagnostics)
End Function
Public Function NullableOf(type As TypeSymbol) As NamedTypeSymbol
' Get the Nullable type
Dim nullableType As NamedTypeSymbol = SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Nullable_T)
If nullableType.IsErrorType Then
Return nullableType
End If
Debug.Assert(nullableType.IsGenericType AndAlso nullableType.Arity = 1)
' Construct the Nullable(Of T).
Return nullableType.Construct(ImmutableArray.Create(type))
End Function
Public Function WellKnownType(wt As WellKnownType) As NamedTypeSymbol
Return Binder.GetWellKnownType(Me.Compilation, wt, _syntax, Me.Diagnostics)
End Function
Public Function WellKnownMember(Of T As Symbol)(wm As WellKnownMember, Optional isOptional As Boolean = False) As T
Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing
Dim member = DirectCast(Binder.GetWellKnownTypeMember(Me.Compilation, wm, useSiteInfo), T)
If useSiteInfo.DiagnosticInfo IsNot Nothing AndAlso isOptional Then
member = Nothing
Else
Me.Diagnostics.Add(useSiteInfo, _syntax)
End If
Return member
End Function
Public Function SpecialMember(sm As SpecialMember) As Symbol
Dim memberSymbol As Symbol = Me.Compilation.GetSpecialTypeMember(sm)
Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol)
If memberSymbol Is Nothing Then
Dim memberDescriptor As MemberDescriptor = SpecialMembers.GetDescriptor(sm)
useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(GetDiagnosticForMissingRuntimeHelper(memberDescriptor.DeclaringTypeMetadataName, memberDescriptor.Name, CompilationState.Compilation.Options.EmbedVbCoreRuntime))
Else
useSiteInfo = Binder.GetUseSiteInfoForMemberAndContainingType(memberSymbol)
End If
Me.Diagnostics.Add(useSiteInfo, _syntax)
Return memberSymbol
End Function
#If False Then
Public Function SpecialMember(sm As SpecialMember) As Symbol
Return Compilation.GetSpecialTypeMember(sm)
End Function
#End If
Public Function Assignment(left As BoundExpression, right As BoundExpression) As BoundExpressionStatement
Return ExpressionStatement(AssignmentExpression(left, right))
End Function
Public Function ExpressionStatement(expr As BoundExpression) As BoundExpressionStatement
Dim boundNode = New BoundExpressionStatement(_syntax, expr)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Assignment expressions in lowered form should always have suppressObjectClone = True
''' </summary>
Public Function AssignmentExpression(left As BoundExpression, right As BoundExpression) As BoundAssignmentOperator
Debug.Assert(left.Type.IsSameTypeIgnoringAll(right.Type) OrElse right.Type.IsErrorType() OrElse left.Type.IsErrorType())
Dim boundNode = New BoundAssignmentOperator(_syntax, left, right, True)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function ReferenceAssignment(byRefLocal As LocalSymbol, lValue As BoundExpression) As BoundReferenceAssignment
Debug.Assert(TypeSymbol.Equals(byRefLocal.Type, lValue.Type, TypeCompareKind.ConsiderEverything))
Debug.Assert(byRefLocal.IsByRef)
Dim boundNode = New BoundReferenceAssignment(_syntax, Local(byRefLocal, isLValue:=True), lValue, isLValue:=True, type:=lValue.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Block(statements As ImmutableArray(Of BoundStatement)) As BoundBlock
Return Block(ImmutableArray(Of LocalSymbol).Empty, statements)
End Function
Public Function Block(locals As ImmutableArray(Of LocalSymbol), statements As ImmutableArray(Of BoundStatement)) As BoundBlock
Dim boundNode = New BoundBlock(_syntax, Nothing, locals, statements)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Block() As BoundBlock
Return Block(ImmutableArray(Of BoundStatement).Empty)
End Function
Public Function Block(ParamArray statements As BoundStatement()) As BoundBlock
Return Block(ImmutableArray.Create(Of BoundStatement)(statements))
End Function
Public Function Block(locals As ImmutableArray(Of LocalSymbol), ParamArray statements As BoundStatement()) As BoundBlock
Return Block(locals, ImmutableArray.Create(Of BoundStatement)(statements))
End Function
Public Function StatementList() As BoundStatementList
Return StatementList(ImmutableArray(Of BoundStatement).Empty)
End Function
Public Function StatementList(statements As ImmutableArray(Of BoundStatement)) As BoundStatementList
Dim boundNode As New BoundStatementList(Syntax, statements)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function StatementList(first As BoundStatement, second As BoundStatement) As BoundStatementList
Dim boundNode As New BoundStatementList(Syntax, ImmutableArray.Create(first, second))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [Return](Optional expression As BoundExpression = Nothing) As BoundReturnStatement
If expression IsNot Nothing Then
' If necessary, add a conversion on the return expression.
Dim useSiteInfo As New CompoundUseSiteInfo(Of AssemblySymbol)(Diagnostics, Me.Compilation.Assembly)
Dim conversion = Conversions.ClassifyDirectCastConversion(expression.Type, Me.CurrentMethod.ReturnType, useSiteInfo)
Debug.Assert(Conversions.IsWideningConversion(conversion))
Diagnostics.Add(expression, useSiteInfo)
If Not Conversions.IsIdentityConversion(conversion) Then
expression = New BoundDirectCast(Me.Syntax, expression, conversion, Me.CurrentMethod.ReturnType)
End If
End If
Dim boundNode = New BoundReturnStatement(_syntax, expression, Nothing, Nothing)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#If False Then
Public Sub Generate(body As BoundStatement)
Debug.Assert(Me.CurrentMethod IsNot Nothing)
If body.Kind <> BoundKind.Block Then
body = Block(body)
End If
Me.compilationState.AddGeneratedMethod(Me.CurrentMethod, body)
Me.CurrentMethod = Nothing
End Sub
Public Function SynthesizedImplementation(type As NamedTypeSymbol, methodName As String, Optional debuggerHidden As Boolean = False) As SynthesizedImplementationMethod
' TODO: use WellKnownMembers instead of strings.
Dim methodToImplement = DirectCast(type.GetMembers(methodName).[Single](), MethodSymbol)
Dim result = New SynthesizedImplementationMethod(methodToImplement, CurrentClass, debuggerHidden:=debuggerHidden)
EmitModule.AddCompilerGeneratedDefinition(_currentClass, result)
Me.MethodImplementations.Add(New MethodImplementation(result, methodToImplement))
Me.CurrentMethod = result
Return result
End Function
Public Function SynthesizedPropertyImplementation(type As NamedTypeSymbol, propertyName As String, Optional debuggerHidden As Boolean = False) As SynthesizedImplementationMethod
' TODO: use WellKnownMembers instead of strings.
' TODO: share code with SynthesizedImplementation(...)
Dim methodToImplement = (DirectCast(type.GetMembers(propertyName).[Single](), PropertySymbol)).GetMethod
Dim result = New SynthesizedImplementationMethod(methodToImplement, CurrentClass, debuggerHidden:=debuggerHidden)
EmitModule.AddCompilerGeneratedDefinition(_currentClass, result)
Me.MethodImplementations.Add(New MethodImplementation(result, methodToImplement))
Me.CurrentMethod = result
Return result
End Function
#End If
Public Function SynthesizedLocal(type As TypeSymbol, Optional kind As SynthesizedLocalKind = SynthesizedLocalKind.LoweringTemp, Optional syntax As SyntaxNode = Nothing) As LocalSymbol
Return New SynthesizedLocal(Me.CurrentMethod, type, kind, syntax)
End Function
Public Function SynthesizedParameter(type As TypeSymbol, name As String, Optional container As MethodSymbol = Nothing, Optional ordinal As Integer = 0) As ParameterSymbol
Return New SynthesizedParameterSymbol(container, type, ordinal, False, name)
End Function
#If False Then
Public Function Binary(kind As BinaryOperatorKind, type As TypeSymbol, left As BoundExpression, right As BoundExpression, isChecked As Boolean) As BoundBinaryOperator
Dim boundNode = New BoundBinaryOperator(Me._syntax, kind, left, right, isChecked, type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function IntNotEqual(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Return Binary(BinaryOperatorKind.NotEquals, SpecialType(Roslyn.Compilers.SpecialType.System_Boolean), left, right, False)
End Function
#End If
Public Function LogicalAndAlso(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Return Binary(BinaryOperatorKind.AndAlso, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right)
End Function
Public Function LogicalOrElse(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Return Binary(BinaryOperatorKind.OrElse, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right)
End Function
Public Function IntEqual(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Return Binary(BinaryOperatorKind.Equals, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right)
End Function
Public Function IntLessThan(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Return Binary(BinaryOperatorKind.LessThan, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right)
End Function
Public Function Literal(value As Boolean) As BoundLiteral
Dim boundNode = New BoundLiteral(_syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Literal(value As Integer) As BoundLiteral
Dim boundNode = New BoundLiteral(_syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function BadExpression(ParamArray subExpressions As BoundExpression()) As BoundExpression
Dim boundNode = New BoundBadExpression(_syntax, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(subExpressions), ErrorTypeSymbol.UnknownResultType, hasErrors:=True)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [New](type As NamedTypeSymbol) As BoundObjectCreationExpression
' TODO: add diagnostics for when things fall apart
Dim ctor = type.InstanceConstructors.Single(Function(c) c.ParameterCount = 0)
Return [New](ctor)
End Function
Public Function [New](ctor As MethodSymbol, ParamArray args As BoundExpression()) As BoundObjectCreationExpression
Dim boundNode = New BoundObjectCreationExpression(_syntax, ctor, ImmutableArray.Create(args), Nothing, ctor.ContainingType)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [New](ctor As MethodSymbol) As BoundObjectCreationExpression
Dim boundNode = New BoundObjectCreationExpression(_syntax,
ctor,
ImmutableArray(Of BoundExpression).Empty,
Nothing,
ctor.ContainingType)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#If False Then
' These function do their own overload resolution. Probably will remove them or replace with helpers that use correct overload resolution.
Public Function StaticCall(receiver As TypeSymbol, name As String, ParamArray args As BoundExpression()) As BoundExpression
Return StaticCall(receiver, name, ImmutableArray(Of TypeSymbol).Empty, args)
End Function
Public Function StaticCall(receiver As TypeSymbol, name As String, typeArgs As ImmutableArray(Of TypeSymbol), ParamArray args As BoundExpression()) As BoundExpression
Dim m As MethodSymbol = FindMethod(receiver, name, typeArgs, args)
If m Is Nothing Then
Return New BoundBadExpression(_syntax, Nothing, ImmutableArray(Of Symbol).Empty, ImmutableArray(Of BoundNode).CreateFrom(Of BoundExpression)(args), receiver)
End If
Return [Call](Nothing, m, args)
End Function
Function FindMethod(receiver As TypeSymbol, name As String, typeArgs As ImmutableArray(Of TypeSymbol), args As BoundExpression()) As MethodSymbol
Dim found As MethodSymbol = Nothing
Dim ambiguous As Boolean = False
Dim candidates As ImmutableArray(Of Symbol) = receiver.GetMembers(name)
For Each m In candidates
Dim method = TryCast(m, MethodSymbol)
If method Is Nothing OrElse method.Arity <> typeArgs.Count OrElse method.ParameterCount <> args.Length Then
Continue For
End If
If method.Arity <> 0 Then
method = method.Construct(typeArgs)
End If
Dim parameters = method.Parameters
Dim exact As Boolean = True
For i = 0 To args.Length - 1
If parameters(i).IsByRef OrElse Not _compilation.ClassifyConversion(args(i).Type, parameters(i).Type).IsWidening Then
GoTo nextm
End If
exact = exact AndAlso args(i).Type = parameters(i).Type
Next
If exact Then
Return method
End If
If found IsNot Nothing Then
ambiguous = True
End If
found = method
nextm:
Next
' TODO: (EXPRTREE) These error codes are probably not correct. Fix them.
If ambiguous Then
ReportLibraryProblem(ERRID.ERR_MissingRuntimeHelper, receiver, name, typeArgs, args) ' C#: ERR_LibraryMethodNotUnique
ElseIf found Is Nothing Then
ReportLibraryProblem(ERRID.ERR_MissingRuntimeHelper, receiver, name, typeArgs, args) ' C#: ERR_LibraryMethodNotFound
End If
Return found
End Function
Function ReportLibraryProblem(code As ERRID, receiver As TypeSymbol, name As String, typeArgs As ImmutableArray(Of TypeSymbol), args As BoundExpression()) As MethodSymbol
Dim methodSig = New StringBuilder()
Dim wasFirst As Boolean
methodSig.Append(name)
If Not typeArgs.IsNullOrEmpty Then
methodSig.Append("(Of ")
wasFirst = True
For Each t In typeArgs
If Not wasFirst Then
methodSig.Append(", ")
End If
methodSig.Append(t.ToDisplayString())
wasFirst = False
Next
methodSig.Append(")")
End If
methodSig.Append("(")
wasFirst = True
For Each a In args
If Not wasFirst Then
methodSig.Append(", ")
End If
methodSig.Append(a.Type.ToDisplayString())
wasFirst = False
Next
methodSig.Append(")")
_diagnostics.Add(code, _syntax.GetLocation(), receiver, methodSig.ToString())
Return Nothing
End Function
#End If
Public Function [Call](receiver As BoundExpression, method As MethodSymbol) As BoundCall
Return [Call](receiver, method, ImmutableArray(Of BoundExpression).Empty)
End Function
Public Function [Call](receiver As BoundExpression, method As MethodSymbol, ParamArray args As BoundExpression()) As BoundCall
Return [Call](receiver, method, ImmutableArray.Create(Of BoundExpression)(args))
End Function
Public Function [Call](receiver As BoundExpression, method As MethodSymbol, args As ImmutableArray(Of BoundExpression)) As BoundCall
Debug.Assert(method.ParameterCount = args.Length)
Dim boundNode = New BoundCall(
Syntax,
method,
Nothing,
receiver,
args,
Nothing,
suppressObjectClone:=True,
type:=method.ReturnType)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [If](condition As BoundExpression, thenClause As BoundStatement, elseClause As BoundStatement) As BoundStatement
Debug.Assert(thenClause IsNot Nothing AndAlso elseClause IsNot Nothing)
Dim afterif = New GeneratedLabelSymbol("afterif")
Dim alt = New GeneratedLabelSymbol("alternative")
Dim boundCondGoto = New BoundConditionalGoto(_syntax, condition, False, alt)
boundCondGoto.SetWasCompilerGenerated()
Return Block(boundCondGoto, thenClause, [Goto](afterif), Label(alt), elseClause, Label(afterif))
End Function
Public Function TernaryConditionalExpression(condition As BoundExpression, ifTrue As BoundExpression, ifFalse As BoundExpression) As BoundTernaryConditionalExpression
Debug.Assert(ifTrue IsNot Nothing)
Debug.Assert(ifFalse IsNot Nothing)
Return New BoundTernaryConditionalExpression(Me.Syntax, condition, ifTrue, ifFalse, Nothing, ifTrue.Type).MakeCompilerGenerated()
End Function
Public Function [TryCast](expression As BoundExpression, type As TypeSymbol) As BoundTryCast
Debug.Assert(expression IsNot Nothing)
Debug.Assert(Not expression.IsNothingLiteral) ' Not supported yet
Debug.Assert(expression.Type.IsReferenceType) 'Others are not supported yet
Debug.Assert(type.IsReferenceType) 'Others are not supported yet
Debug.Assert(Not expression.Type.IsErrorType)
Debug.Assert(Not type.IsErrorType)
Return New BoundTryCast(Me.Syntax, expression, Conversions.ClassifyTryCastConversion(expression.Type, type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded), type)
End Function
Public Function [DirectCast](expression As BoundExpression, type As TypeSymbol) As BoundDirectCast
Debug.Assert(expression IsNot Nothing)
Debug.Assert(expression.IsNothingLiteral OrElse expression.Type.IsReferenceType OrElse expression.Type.IsTypeParameter()) 'Others are not supported yet
Debug.Assert(type.IsReferenceType OrElse (type.IsTypeParameter AndAlso expression.IsNothingLiteral)) 'Others are not supported yet
Debug.Assert(expression.Type Is Nothing OrElse Not expression.Type.IsErrorType)
Debug.Assert(Not type.IsErrorType)
Return New BoundDirectCast(Me.Syntax,
expression,
If(expression.IsNothingLiteral,
ConversionKind.WideningNothingLiteral,
Conversions.ClassifyDirectCastConversion(expression.Type, type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)),
type)
End Function
Public Function [If](condition As BoundExpression, thenClause As BoundStatement) As BoundStatement
Return [If](condition, thenClause, Block())
End Function
Public Function [Throw](Optional e As BoundExpression = Nothing) As BoundThrowStatement
Dim boundNode = New BoundThrowStatement(_syntax, e)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Local(localSym As LocalSymbol, isLValue As Boolean) As BoundLocal
Dim boundNode = New BoundLocal(_syntax, localSym, isLValue, localSym.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Sequence(temps As ImmutableArray(Of LocalSymbol), ParamArray parts As BoundExpression()) As BoundExpression
Debug.Assert(parts IsNot Nothing AndAlso parts.Length > 0)
Dim statements(parts.Length - 1 - 1) As BoundExpression
For i = 0 To parts.Length - 1 - 1
statements(i) = parts(i)
Next
Dim lastExpression = parts(parts.Length - 1)
Return Sequence(temps, statements.AsImmutableOrNull, lastExpression)
End Function
Public Function Sequence(temp As LocalSymbol, ParamArray parts As BoundExpression()) As BoundExpression
Return Sequence(ImmutableArray.Create(Of LocalSymbol)(temp), parts)
End Function
Public Function Sequence(ParamArray parts As BoundExpression()) As BoundExpression
Return Sequence(ImmutableArray(Of LocalSymbol).Empty, parts)
End Function
Public Function Sequence(locals As ImmutableArray(Of LocalSymbol), sideEffects As ImmutableArray(Of BoundExpression), result As BoundExpression) As BoundExpression
Dim boundNode = New BoundSequence(_syntax, locals, sideEffects, result, result.Type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [Select](ex As BoundExpression, sections As IEnumerable(Of BoundCaseBlock)) As BoundStatement
Dim sectionsArray = ImmutableArray.CreateRange(Of BoundCaseBlock)(sections)
If sectionsArray.Length = 0 Then
Return Me.ExpressionStatement(ex)
End If
Dim breakLabel As GeneratedLabelSymbol = New GeneratedLabelSymbol("break")
CheckSwitchSections(sectionsArray)
Dim boundNode = New BoundSelectStatement(_syntax, Me.ExpressionStatement(ex), Nothing, sectionsArray, True, breakLabel)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary> Check for (and assert that there are no) duplicate case labels in the switch. </summary>
<Conditional("DEBUG")>
Private Sub CheckSwitchSections(sections As ImmutableArray(Of BoundCaseBlock))
Dim labels = New HashSet(Of Integer)()
For Each s In sections
For Each l As BoundSimpleCaseClause In s.CaseStatement.CaseClauses
Dim v1 = l.ValueOpt.ConstantValueOpt.Int32Value
Debug.Assert(Not labels.Contains(v1))
labels.Add(v1)
Next
Next
End Sub
'Public Function SwitchSection(value As Integer, ParamArray statements As BoundStatement()) As BoundCaseBlock
' Dim boundCaseClause = New BoundSimpleCaseClause(_syntax, Literal(value), Nothing)
' boundCaseClause.SetWasCompilerGenerated()
' Dim boundCaseStatement = New BoundCaseStatement(_syntax, ImmutableArray(Of BoundCaseClause).CreateFrom(boundCaseClause), Nothing)
' boundCaseStatement.SetWasCompilerGenerated()
' Dim boundCaseBlock = New BoundCaseBlock(_syntax, boundCaseStatement, Block(statements))
' boundCaseBlock.SetWasCompilerGenerated()
' Return boundCaseBlock
'End Function
Public Function SwitchSection(values As List(Of Integer), ParamArray statements As BoundStatement()) As BoundCaseBlock
Dim builder = ArrayBuilder(Of BoundCaseClause).GetInstance()
For Each i In values
Dim boundCaseClause = New BoundSimpleCaseClause(_syntax, Literal(i), Nothing)
boundCaseClause.SetWasCompilerGenerated()
builder.Add(boundCaseClause)
Next
Dim boundCaseStatement = New BoundCaseStatement(_syntax, builder.ToImmutableAndFree(), Nothing)
boundCaseStatement.SetWasCompilerGenerated()
Dim boundCaseBlock = New BoundCaseBlock(_syntax, boundCaseStatement, Block(ImmutableArray.Create(Of BoundStatement)(statements)))
boundCaseBlock.SetWasCompilerGenerated()
Return boundCaseBlock
End Function
Public Function [Goto](label As LabelSymbol, Optional setWasCompilerGenerated As Boolean = True) As BoundGotoStatement
Dim boundNode = New BoundGotoStatement(_syntax, label, Nothing)
If setWasCompilerGenerated Then
boundNode.SetWasCompilerGenerated()
End If
Return boundNode
End Function
Public Function Label(labelSym As LabelSymbol) As BoundLabelStatement
Dim boundNode = New BoundLabelStatement(_syntax, labelSym)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Literal(value As String) As BoundLiteral
Dim boundNode = New BoundLiteral(_syntax, ConstantValue.Create(value), SpecialType(Microsoft.CodeAnalysis.SpecialType.System_String))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function StringLiteral(value As ConstantValue) As BoundLiteral
Debug.Assert(value.IsString OrElse value.IsNull)
Dim boundNode = New BoundLiteral(_syntax, value, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_String))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#If False Then
Public Function ArrayLength(array As BoundExpression) As BoundArrayLength
Debug.Assert(array.Type IsNot Nothing AndAlso array.Type.IsArrayType())
Return New BoundArrayLength(_syntax, array, SpecialType(Roslyn.Compilers.SpecialType.System_Int32))
End Function
Public Function ArrayAccessFirstElement(array As BoundExpression) As BoundArrayAccess
Debug.Assert(array.Type IsNot Nothing AndAlso array.Type.IsArrayType())
Dim rank As Integer = (DirectCast(array.Type, ArrayTypeSymbol)).Rank
Dim firstElementIndices As ImmutableArray(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance(rank, Literal(0)).ToReadOnlyAndFree()
Return ArrayAccess(array, firstElementIndices)
End Function
#End If
Public Function ArrayAccess(array As BoundExpression, isLValue As Boolean, ParamArray indices As BoundExpression()) As BoundArrayAccess
Return ArrayAccess(array, isLValue, indices.AsImmutableOrNull())
End Function
Public Function ArrayAccess(array As BoundExpression, isLValue As Boolean, indices As ImmutableArray(Of BoundExpression)) As BoundArrayAccess
Debug.Assert(array.Type IsNot Nothing AndAlso array.Type.IsArrayType())
Dim boundNode = New BoundArrayAccess(_syntax, array, indices, isLValue, (DirectCast(array.Type, ArrayTypeSymbol)).ElementType)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#If False Then
Public Function ThrowNull() As BoundStatement
Return [Throw](Null(_compilation.GetWellKnownType(Compilers.WellKnownType.System_Exception)))
End Function
#End If
Public Function BaseInitialization(ParamArray args As BoundExpression()) As BoundStatement
' TODO: add diagnostics for when things fall apart
Dim ctor = Me.CurrentMethod.MeParameter.Type.BaseTypeNoUseSiteDiagnostics.InstanceConstructors.Single(Function(c) c.ParameterCount = args.Length)
Dim boundNode = New BoundExpressionStatement(_syntax, [Call](Base(), ctor, args))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Shared Function HiddenSequencePoint(Optional statementOpt As BoundStatement = Nothing) As BoundStatement
Return New BoundSequencePoint(Nothing, statementOpt).MakeCompilerGenerated
End Function
Public Function Null() As BoundExpression
Dim nullLiteral As BoundExpression = New BoundLiteral(_syntax, ConstantValue.Null, Nothing)
nullLiteral.SetWasCompilerGenerated()
Return nullLiteral
End Function
Public Function Null(type As TypeSymbol) As BoundExpression
If Not type.IsTypeParameter() AndAlso type.IsReferenceType() Then
Dim nullLiteral As BoundExpression = New BoundLiteral(_syntax, ConstantValue.Null, type)
nullLiteral.SetWasCompilerGenerated()
Return nullLiteral
Else
Dim nullLiteral As BoundExpression = New BoundLiteral(_syntax, ConstantValue.Null, Nothing)
nullLiteral.SetWasCompilerGenerated()
Return Me.Convert(type, nullLiteral)
End If
End Function
Public Function Type(typeSym As TypeSymbol) As BoundTypeExpression
Dim boundNode = New BoundTypeExpression(_syntax, typeSym)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [Typeof](type As WellKnownType) As BoundExpression
Return [Typeof](WellKnownType(type))
End Function
Public Function [Typeof](typeSym As TypeSymbol) As BoundExpression
Dim boundNode = New BoundGetType(_syntax, Type(typeSym), WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Type))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function TypeArguments(typeArgs As ImmutableArray(Of TypeSymbol)) As BoundTypeArguments
Dim boundNode = New BoundTypeArguments(_syntax, typeArgs)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function MethodInfo(meth As WellKnownMember) As BoundExpression
Dim method = WellKnownMember(Of MethodSymbol)(meth)
If method Is Nothing Then
Return BadExpression()
Else
Return MethodInfo(method)
End If
End Function
Public Function MethodInfo(meth As SpecialMember) As BoundExpression
Dim method = DirectCast(SpecialMember(meth), MethodSymbol)
If method Is Nothing Then
Return BadExpression()
Else
Return MethodInfo(method)
End If
End Function
Public Function MethodInfo(method As MethodSymbol) As BoundExpression
Dim boundNode = New BoundMethodInfo(Syntax, method, WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_MethodInfo))
' Touch the method to be used to report use site diagnostics
WellKnownMember(Of MethodSymbol)(If(method.ContainingType.IsGenericType,
Microsoft.CodeAnalysis.WellKnownMember.System_Reflection_MethodBase__GetMethodFromHandle2,
Microsoft.CodeAnalysis.WellKnownMember.System_Reflection_MethodBase__GetMethodFromHandle))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function ConstructorInfo(meth As WellKnownMember) As BoundExpression
Dim method = WellKnownMember(Of MethodSymbol)(meth)
If method Is Nothing Then
Return BadExpression()
Else
Return ConstructorInfo(method)
End If
End Function
Public Function ConstructorInfo(meth As SpecialMember) As BoundExpression
Dim method = DirectCast(SpecialMember(meth), MethodSymbol)
If method Is Nothing Then
Return BadExpression()
Else
Return ConstructorInfo(method)
End If
End Function
Public Function ConstructorInfo(meth As MethodSymbol) As BoundExpression
Dim boundNode = New BoundMethodInfo(Syntax, meth, WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_ConstructorInfo))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#If False Then
Friend Function ConstructorInfo(ctor As MethodSymbol) As BoundExpression
Dim boundNode = New BoundMethodInfo(Syntax, ctor, WellKnownType(Compilers.WellKnownType.System_Reflection_ConstructorInfo))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
#End If
Public Function FieldInfo(field As FieldSymbol) As BoundExpression
Dim boundNode = New BoundFieldInfo(_syntax, field, WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Reflection_FieldInfo))
' Touch the method to be used to report use site diagnostics
WellKnownMember(Of MethodSymbol)(If(field.ContainingType.IsGenericType,
Microsoft.CodeAnalysis.WellKnownMember.System_Reflection_FieldInfo__GetFieldFromHandle2,
Microsoft.CodeAnalysis.WellKnownMember.System_Reflection_FieldInfo__GetFieldFromHandle))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to the index portion of a method's metadata token.
''' </summary>
Public Function MethodDefIndex(method As MethodSymbol) As BoundExpression
Dim boundNode As New BoundMethodDefIndex(Syntax, method, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to the maximum value of the index portions of all method definition metadata tokens in current module.
''' </summary>
Public Function MaximumMethodDefIndex() As BoundExpression
Dim boundNode As New BoundMaximumMethodDefIndex(Syntax, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to the current module's MVID.
''' </summary>
Public Function ModuleVersionId(isLValue As Boolean) As BoundExpression
Dim boundNode As New BoundModuleVersionId(Syntax, isLValue, WellKnownType(Microsoft.CodeAnalysis.WellKnownType.System_Guid))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to a text representation of the current module/s MVID.
''' </summary>
Public Function ModuleVersionIdString() As BoundExpression
Dim boundNode As New BoundModuleVersionIdString(Syntax, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_String))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to the root of the dynamic analysis payloads for a particular kind of dynamic analysis.
''' </summary>
''' <param name="analysisKind">Uniquely identifies the kind of dynamic analysis.</param>
''' <param name="payloadType">Type of an analysis payload cell for the particular analysis kind.</param>
Public Function InstrumentationPayloadRoot(analysisKind As Integer, payloadType As TypeSymbol, isLValue As Boolean) As BoundExpression
Dim boundNode As New BoundInstrumentationPayloadRoot(Syntax, analysisKind, isLValue, payloadType)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
''' <summary>
''' Synthesizes an expression that evaluates to the index of a source document in the table of debug source documents.
''' </summary>
Public Function SourceDocumentIndex(document As Cci.DebugSourceDocument) As BoundExpression
Dim boundNode As New BoundSourceDocumentIndex(Syntax, document, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Convert(type As TypeSymbol, arg As BoundExpression, Optional isChecked As Boolean = False) As BoundConversion
If arg.IsNothingLiteral() Then
Return Convert(type, arg, ConversionKind.WideningNothingLiteral, isChecked)
ElseIf type.IsErrorType() OrElse arg.Type.IsErrorType() Then
Return Convert(type, arg, ConversionKind.WideningReference, isChecked) ' will abort before code gen due to error, so doesn't matter if conversion kind is wrong.
Else
Return Convert(type, arg, Conversions.ClassifyConversion(arg.Type, type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key, isChecked)
End If
End Function
Public Function Convert(type As TypeSymbol, arg As BoundExpression, convKind As ConversionKind, Optional isChecked As Boolean = False) As BoundConversion
Debug.Assert((convKind And ConversionKind.UserDefined) = 0)
Dim boundNode = New BoundConversion(_syntax, arg, convKind, isChecked, True, ConstantValue.NotAvailable, type)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function Array(elementType As TypeSymbol, ParamArray elements As BoundExpression()) As BoundExpression
Return Array(elementType, elements.AsImmutableOrNull())
End Function
Public Function Array(elementType As TypeSymbol, elements As ImmutableArray(Of BoundExpression)) As BoundExpression
Dim arrayType = Me.Compilation.CreateArrayTypeSymbol(elementType)
Dim boundArrayInit = New BoundArrayInitialization(_syntax, elements, arrayType)
boundArrayInit.SetWasCompilerGenerated()
Return New BoundArrayCreation(_syntax, ImmutableArray.Create(Of BoundExpression)(Literal(elements.Length)), boundArrayInit, arrayType)
End Function
Public Function Array(elementType As TypeSymbol, bounds As ImmutableArray(Of BoundExpression), elements As ImmutableArray(Of BoundExpression)) As BoundExpression
Dim arrayType = Me.Compilation.CreateArrayTypeSymbol(elementType)
Dim arrayInitialization As BoundArrayInitialization = If(Not elements.IsDefaultOrEmpty, New BoundArrayInitialization(_syntax, elements, arrayType), Nothing)
arrayInitialization?.SetWasCompilerGenerated()
Dim arrayCreation As New BoundArrayCreation(_syntax, bounds, arrayInitialization, arrayType)
arrayCreation.SetWasCompilerGenerated()
Return arrayCreation
End Function
Public Function Conditional(condition As BoundExpression, consequence As BoundExpression, alternative As BoundExpression, type As TypeSymbol) As BoundTernaryConditionalExpression
Return New BoundTernaryConditionalExpression(Syntax, condition, consequence, alternative, Nothing, type)
End Function
Public Function BinaryConditional(left As BoundExpression, right As BoundExpression) As BoundBinaryConditionalExpression
Return New BoundBinaryConditionalExpression(Syntax, left, Nothing, Nothing, right, Nothing, left.Type)
End Function
Public Function Binary(kind As BinaryOperatorKind, type As TypeSymbol, left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Dim binOp = New BoundBinaryOperator(Syntax, kind, left, right, False, type)
binOp.SetWasCompilerGenerated()
Return binOp
End Function
Public Function ObjectReferenceEqual(left As BoundExpression, right As BoundExpression) As BoundBinaryOperator
Dim boundNode = Binary(BinaryOperatorKind.Is, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), left, right)
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function ReferenceIsNothing(operand As BoundExpression) As BoundBinaryOperator
Debug.Assert(operand.Type.IsReferenceType)
Dim boundNode = Binary(BinaryOperatorKind.Is, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), operand, Me.Null(operand.Type))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function ReferenceIsNotNothing(operand As BoundExpression) As BoundBinaryOperator
Debug.Assert(operand.Type.IsReferenceType)
Dim boundNode = Binary(BinaryOperatorKind.IsNot, SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Boolean), operand, Me.Null(operand.Type))
boundNode.SetWasCompilerGenerated()
Return boundNode
End Function
Public Function [Not](expression As BoundExpression) As BoundExpression
Return New BoundUnaryOperator(expression.Syntax, UnaryOperatorKind.Not, expression, False, expression.Type)
End Function
Public Function [Try](tryBlock As BoundBlock,
catchBlocks As ImmutableArray(Of BoundCatchBlock),
Optional finallyBlock As BoundBlock = Nothing,
Optional exitLabel As LabelSymbol = Nothing) As BoundStatement
Return New BoundTryStatement(Syntax, tryBlock, catchBlocks, finallyBlock, exitLabel)
End Function
Public Function CatchBlocks(ParamArray blocks() As BoundCatchBlock) As ImmutableArray(Of BoundCatchBlock)
Return blocks.AsImmutableOrNull()
End Function
Public Function [Catch](local As LocalSymbol, block As BoundBlock, Optional isSynthesizedAsyncCatchAll As Boolean = False) As BoundCatchBlock
Dim m1 = WellKnownMember(Of MethodSymbol)(Microsoft.CodeAnalysis.WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError)
Dim m2 = WellKnownMember(Of MethodSymbol)(Microsoft.CodeAnalysis.WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError)
Return New BoundCatchBlock(Syntax, local, Me.Local(local, False), Nothing, Nothing, block,
hasErrors:=m1 Is Nothing OrElse m2 Is Nothing,
isSynthesizedAsyncCatchAll:=isSynthesizedAsyncCatchAll)
End Function
Public Function SequencePoint(syntax As SyntaxNode, statement As BoundStatement) As BoundStatement
Return New BoundSequencePoint(syntax, statement)
End Function
Public Function SequencePoint(syntax As SyntaxNode) As BoundStatement
Return New BoundSequencePoint(syntax, Nothing).MakeCompilerGenerated
End Function
Public Function SequencePointWithSpan(syntax As SyntaxNode, textSpan As TextSpan, boundStatement As BoundStatement) As BoundStatement
Return New BoundSequencePointWithSpan(syntax, boundStatement, textSpan)
End Function
Public Function NoOp(Optional flavor As NoOpStatementFlavor = NoOpStatementFlavor.Default) As BoundStatement
Return New BoundNoOpStatement(Me.Syntax, flavor).MakeCompilerGenerated
End Function
Public Sub CloseMethod(body As BoundStatement)
Debug.Assert(Me.CurrentMethod IsNot Nothing)
If body.Kind <> BoundKind.Block Then
body = Me.Block(body)
End If
CompilationState.AddSynthesizedMethod(Me.CurrentMethod, body)
Me.CurrentMethod = Nothing
End Sub
Public Function SpillSequence(locals As ImmutableArray(Of LocalSymbol), fields As ImmutableArray(Of FieldSymbol), statements As ImmutableArray(Of BoundStatement), valueOpt As BoundExpression) As BoundSpillSequence
Return New BoundSpillSequence(Me.Syntax, locals, fields, statements, valueOpt,
If(valueOpt Is Nothing,
Me.SpecialType(Microsoft.CodeAnalysis.SpecialType.System_Void),
valueOpt.Type)).MakeCompilerGenerated()
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/xlf/CSharpCompilerExtensionsResources.pl.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="pl" original="../CSharpCompilerExtensionsResources.resx">
<body>
<trans-unit id="Code_block_preferences">
<source>Code-block preferences</source>
<target state="translated">Preferencje bloku kodu</target>
<note />
</trans-unit>
<trans-unit id="Expected_string_or_char_literal">
<source>Expected string or char literal</source>
<target state="translated">Oczekiwano ciągu lub literału znakowego</target>
<note />
</trans-unit>
<trans-unit id="Expression_bodied_members">
<source>Expression-bodied members</source>
<target state="translated">Składowe z wyrażeniem w treści</target>
<note />
</trans-unit>
<trans-unit id="Null_checking_preferences">
<source>Null-checking preferences</source>
<target state="translated">Preferencje sprawdzania wartości null</target>
<note />
</trans-unit>
<trans-unit id="Pattern_matching_preferences">
<source>Pattern matching preferences</source>
<target state="translated">Preferencje dopasowywania do wzorca</target>
<note />
</trans-unit>
<trans-unit id="_0_1_is_not_supported_in_this_version">
<source>'{0}.{1}' is not supported in this version</source>
<target state="translated">Element „{0}.{1}” nie jest obsługiwany w tej wersji</target>
<note>{0}: A type name
{1}: A member name</note>
</trans-unit>
<trans-unit id="using_directive_preferences">
<source>'using' directive preferences</source>
<target state="translated">Preferencje dyrektywy „using”</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="var_preferences">
<source>var preferences</source>
<target state="translated">Preferencje zmiennych</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="pl" original="../CSharpCompilerExtensionsResources.resx">
<body>
<trans-unit id="Code_block_preferences">
<source>Code-block preferences</source>
<target state="translated">Preferencje bloku kodu</target>
<note />
</trans-unit>
<trans-unit id="Expected_string_or_char_literal">
<source>Expected string or char literal</source>
<target state="translated">Oczekiwano ciągu lub literału znakowego</target>
<note />
</trans-unit>
<trans-unit id="Expression_bodied_members">
<source>Expression-bodied members</source>
<target state="translated">Składowe z wyrażeniem w treści</target>
<note />
</trans-unit>
<trans-unit id="Null_checking_preferences">
<source>Null-checking preferences</source>
<target state="translated">Preferencje sprawdzania wartości null</target>
<note />
</trans-unit>
<trans-unit id="Pattern_matching_preferences">
<source>Pattern matching preferences</source>
<target state="translated">Preferencje dopasowywania do wzorca</target>
<note />
</trans-unit>
<trans-unit id="_0_1_is_not_supported_in_this_version">
<source>'{0}.{1}' is not supported in this version</source>
<target state="translated">Element „{0}.{1}” nie jest obsługiwany w tej wersji</target>
<note>{0}: A type name
{1}: A member name</note>
</trans-unit>
<trans-unit id="using_directive_preferences">
<source>'using' directive preferences</source>
<target state="translated">Preferencje dyrektywy „using”</target>
<note>{Locked="using"} "using" is a C# keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="var_preferences">
<source>var preferences</source>
<target state="translated">Preferencje zmiennych</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/EditorFeatures/TestUtilities/Diagnostics/GenerateType/TestProjectManagementService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.ProjectManagement;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType
{
[ExportWorkspaceService(typeof(IProjectManagementService), ServiceLayer.Default), Shared]
internal class TestProjectManagementService : IProjectManagementService
{
private string _defaultNamespace;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestProjectManagementService()
{
}
public IList<string> GetFolders(ProjectId projectId, Workspace workspace)
=> null;
public string GetDefaultNamespace(Project project, Workspace workspace)
=> _defaultNamespace;
public void SetDefaultNamespace(string defaultNamespace)
=> _defaultNamespace = defaultNamespace;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Composition;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.ProjectManagement;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType
{
[ExportWorkspaceService(typeof(IProjectManagementService), ServiceLayer.Default), Shared]
internal class TestProjectManagementService : IProjectManagementService
{
private string _defaultNamespace;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestProjectManagementService()
{
}
public IList<string> GetFolders(ProjectId projectId, Workspace workspace)
=> null;
public string GetDefaultNamespace(Project project, Workspace workspace)
=> _defaultNamespace;
public void SetDefaultNamespace(string defaultNamespace)
=> _defaultNamespace = defaultNamespace;
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Workspaces/CSharp/Portable/CodeGeneration/EnumMemberGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class EnumMemberGenerator
{
internal static EnumDeclarationSyntax AddEnumMemberTo(EnumDeclarationSyntax destination, IFieldSymbol enumMember, CodeGenerationOptions options)
{
var members = new List<SyntaxNodeOrToken>();
members.AddRange(destination.Members.GetWithSeparators());
var member = GenerateEnumMemberDeclaration(enumMember, destination, options);
if (members.Count == 0)
{
members.Add(member);
}
else if (members.LastOrDefault().Kind() == SyntaxKind.CommaToken)
{
members.Add(member);
members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
}
else
{
var lastMember = members.Last();
var trailingTrivia = lastMember.GetTrailingTrivia();
members[members.Count - 1] = lastMember.WithTrailingTrivia();
members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(trailingTrivia));
members.Add(member);
}
return destination.EnsureOpenAndCloseBraceTokens()
.WithMembers(SyntaxFactory.SeparatedList<EnumMemberDeclarationSyntax>(members));
}
public static EnumMemberDeclarationSyntax GenerateEnumMemberDeclaration(
IFieldSymbol enumMember,
EnumDeclarationSyntax destinationOpt,
CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<EnumMemberDeclarationSyntax>(enumMember, options);
if (reusableSyntax != null)
{
return reusableSyntax;
}
var value = CreateEnumMemberValue(destinationOpt, enumMember);
var member = SyntaxFactory.EnumMemberDeclaration(enumMember.Name.ToIdentifierToken())
.WithEqualsValue(value == null ? null : SyntaxFactory.EqualsValueClause(value: value));
return AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(member, enumMember, options));
}
private static ExpressionSyntax CreateEnumMemberValue(EnumDeclarationSyntax destinationOpt, IFieldSymbol enumMember)
{
if (!enumMember.HasConstantValue)
{
return null;
}
if (!(enumMember.ConstantValue is byte) &&
!(enumMember.ConstantValue is sbyte) &&
!(enumMember.ConstantValue is ushort) &&
!(enumMember.ConstantValue is short) &&
!(enumMember.ConstantValue is int) &&
!(enumMember.ConstantValue is uint) &&
!(enumMember.ConstantValue is long) &&
!(enumMember.ConstantValue is ulong))
{
return null;
}
var value = IntegerUtilities.ToInt64(enumMember.ConstantValue);
if (destinationOpt != null)
{
if (destinationOpt.Members.Count == 0)
{
if (value == 0)
{
return null;
}
}
else
{
// Don't generate an initializer if no other members have them, and our value
// would be correctly inferred from our position.
if (destinationOpt.Members.Count == value &&
destinationOpt.Members.All(m => m.EqualsValue == null))
{
return null;
}
// Existing members, try to stay consistent with their style.
var lastMember = destinationOpt.Members.LastOrDefault(m => m.EqualsValue != null);
if (lastMember != null)
{
var lastExpression = lastMember.EqualsValue.Value;
if (lastExpression.Kind() == SyntaxKind.LeftShiftExpression &&
IntegerUtilities.HasOneBitSet(value))
{
var binaryExpression = (BinaryExpressionSyntax)lastExpression;
if (binaryExpression.Left.Kind() == SyntaxKind.NumericLiteralExpression)
{
var numericLiteral = (LiteralExpressionSyntax)binaryExpression.Left;
if (numericLiteral.Token.ValueText == "1")
{
// The user is left shifting ones, stick with that pattern
var shiftValue = IntegerUtilities.LogBase2(value);
// Re-use the numericLiteral text so type suffixes match too
return SyntaxFactory.BinaryExpression(
SyntaxKind.LeftShiftExpression,
SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(numericLiteral.Token.Text, 1)),
SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(shiftValue.ToString(), shiftValue)));
}
}
}
else if (lastExpression.IsKind(SyntaxKind.NumericLiteralExpression, out LiteralExpressionSyntax numericLiteral))
{
var numericToken = numericLiteral.Token;
var numericText = numericToken.ToString();
if (numericText.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
// Hex
return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression,
SyntaxFactory.Literal(numericText.Substring(0, 2) + value.ToString("X"), value));
}
else if (numericText.StartsWith("0b", StringComparison.OrdinalIgnoreCase))
{
return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression,
SyntaxFactory.Literal(numericText.Substring(0, 2) + Convert.ToString(value, 2), value));
}
}
}
}
}
var namedType = enumMember.Type as INamedTypeSymbol;
var underlyingType = namedType?.EnumUnderlyingType;
return ExpressionGenerator.GenerateNonEnumValueExpression(
underlyingType,
enumMember.ConstantValue,
canUseFieldReference: true);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class EnumMemberGenerator
{
internal static EnumDeclarationSyntax AddEnumMemberTo(EnumDeclarationSyntax destination, IFieldSymbol enumMember, CodeGenerationOptions options)
{
var members = new List<SyntaxNodeOrToken>();
members.AddRange(destination.Members.GetWithSeparators());
var member = GenerateEnumMemberDeclaration(enumMember, destination, options);
if (members.Count == 0)
{
members.Add(member);
}
else if (members.LastOrDefault().Kind() == SyntaxKind.CommaToken)
{
members.Add(member);
members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
}
else
{
var lastMember = members.Last();
var trailingTrivia = lastMember.GetTrailingTrivia();
members[members.Count - 1] = lastMember.WithTrailingTrivia();
members.Add(SyntaxFactory.Token(SyntaxKind.CommaToken).WithTrailingTrivia(trailingTrivia));
members.Add(member);
}
return destination.EnsureOpenAndCloseBraceTokens()
.WithMembers(SyntaxFactory.SeparatedList<EnumMemberDeclarationSyntax>(members));
}
public static EnumMemberDeclarationSyntax GenerateEnumMemberDeclaration(
IFieldSymbol enumMember,
EnumDeclarationSyntax destinationOpt,
CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<EnumMemberDeclarationSyntax>(enumMember, options);
if (reusableSyntax != null)
{
return reusableSyntax;
}
var value = CreateEnumMemberValue(destinationOpt, enumMember);
var member = SyntaxFactory.EnumMemberDeclaration(enumMember.Name.ToIdentifierToken())
.WithEqualsValue(value == null ? null : SyntaxFactory.EqualsValueClause(value: value));
return AddFormatterAndCodeGeneratorAnnotationsTo(
ConditionallyAddDocumentationCommentTo(member, enumMember, options));
}
private static ExpressionSyntax CreateEnumMemberValue(EnumDeclarationSyntax destinationOpt, IFieldSymbol enumMember)
{
if (!enumMember.HasConstantValue)
{
return null;
}
if (!(enumMember.ConstantValue is byte) &&
!(enumMember.ConstantValue is sbyte) &&
!(enumMember.ConstantValue is ushort) &&
!(enumMember.ConstantValue is short) &&
!(enumMember.ConstantValue is int) &&
!(enumMember.ConstantValue is uint) &&
!(enumMember.ConstantValue is long) &&
!(enumMember.ConstantValue is ulong))
{
return null;
}
var value = IntegerUtilities.ToInt64(enumMember.ConstantValue);
if (destinationOpt != null)
{
if (destinationOpt.Members.Count == 0)
{
if (value == 0)
{
return null;
}
}
else
{
// Don't generate an initializer if no other members have them, and our value
// would be correctly inferred from our position.
if (destinationOpt.Members.Count == value &&
destinationOpt.Members.All(m => m.EqualsValue == null))
{
return null;
}
// Existing members, try to stay consistent with their style.
var lastMember = destinationOpt.Members.LastOrDefault(m => m.EqualsValue != null);
if (lastMember != null)
{
var lastExpression = lastMember.EqualsValue.Value;
if (lastExpression.Kind() == SyntaxKind.LeftShiftExpression &&
IntegerUtilities.HasOneBitSet(value))
{
var binaryExpression = (BinaryExpressionSyntax)lastExpression;
if (binaryExpression.Left.Kind() == SyntaxKind.NumericLiteralExpression)
{
var numericLiteral = (LiteralExpressionSyntax)binaryExpression.Left;
if (numericLiteral.Token.ValueText == "1")
{
// The user is left shifting ones, stick with that pattern
var shiftValue = IntegerUtilities.LogBase2(value);
// Re-use the numericLiteral text so type suffixes match too
return SyntaxFactory.BinaryExpression(
SyntaxKind.LeftShiftExpression,
SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(numericLiteral.Token.Text, 1)),
SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(shiftValue.ToString(), shiftValue)));
}
}
}
else if (lastExpression.IsKind(SyntaxKind.NumericLiteralExpression, out LiteralExpressionSyntax numericLiteral))
{
var numericToken = numericLiteral.Token;
var numericText = numericToken.ToString();
if (numericText.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
// Hex
return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression,
SyntaxFactory.Literal(numericText.Substring(0, 2) + value.ToString("X"), value));
}
else if (numericText.StartsWith("0b", StringComparison.OrdinalIgnoreCase))
{
return SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression,
SyntaxFactory.Literal(numericText.Substring(0, 2) + Convert.ToString(value, 2), value));
}
}
}
}
}
var namedType = enumMember.Type as INamedTypeSymbol;
var underlyingType = namedType?.EnumUnderlyingType;
return ExpressionGenerator.GenerateNonEnumValueExpression(
underlyingType,
enumMember.ConstantValue,
canUseFieldReference: true);
}
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.VisualBasic.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.Syntax;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
public partial class CodeGenerationTests
{
[UseExportProvider]
public class VisualBasic
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNamespace()
{
var input = "Namespace [|N1|]\n End Namespace";
var expected = @"Namespace N1
Namespace N2
End Namespace
End Namespace";
await TestAddNamespaceAsync(input, expected,
name: "N2");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public F As Integer
End Class";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSharedField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Private Shared F As String
End Class";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(string)),
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddArrayField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public F As Integer()
End Class";
await TestAddFieldAsync(input, expected,
type: CreateArrayType(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructor()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub New()
End Sub
End Class";
await TestAddConstructorAsync(input, expected);
}
[WorkItem(530785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530785")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithXmlComment()
{
var input = @"
Public Class [|C|]
''' <summary>
''' Do Nothing
''' </summary>
Public Sub GetStates()
End Sub
End Class";
var expected = @"
Public Class C
Public Sub New()
End Sub
''' <summary>
''' Do Nothing
''' </summary>
Public Sub GetStates()
End Sub
End Class";
await TestAddConstructorAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithoutBody()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub New()
End Class";
await TestAddConstructorAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorResolveNamespaceImport()
{
var input = "Class [|C|]\n End Class";
var expected = @"Imports System.Text
Class C
Public Sub New(s As StringBuilder)
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
parameters: Parameters(Parameter(typeof(StringBuilder), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSharedConstructor()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Shared Sub New()
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddChainedConstructor()
{
var input = "Class [|C|]\n Public Sub New(i As Integer)\n End Sub\n End Class";
var expected = @"Class C
Public Sub New()
Me.New(42)
End Sub
Public Sub New(i As Integer)
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
thisArguments: ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExpression("42")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544476")]
public async Task AddClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassEscapeName()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class [Class]
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassUnicodeName()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class [Class]
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddNotInheritableClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public NotInheritable Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
modifiers: new DeclarationModifiers(isSealed: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddMustInheritClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Friend MustInherit Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
accessibility: Accessibility.Internal,
modifiers: new DeclarationModifiers(isAbstract: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStructure()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Friend Structure S
End Structure
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Internal,
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedStructure()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Structure S
End Structure
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isSealed: true),
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddInterface()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Interface I
End Interface
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "I",
typeKind: TypeKind.Interface);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544528")]
public async Task AddEnum()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Enum E
F1
End Enum
End Namespace";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", null)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544527")]
public async Task AddEnumWithValues()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Enum E
F1 = 1
F2 = 2
End Enum
End Namespace";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", 1), CreateEnumField("F2", 2)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEnumMember()
{
var input = "Public Enum [|E|]\n F1 = 1\n F2 = 2\n End Enum";
var expected = @"Public Enum E
F1 = 1
F2 = 2
F3
End Enum";
await TestAddFieldAsync(input, expected,
name: "F3");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEnumMemberWithValue()
{
var input = "Public Enum [|E|]\n F1 = 1\n F2\n End Enum";
var expected = @"Public Enum E
F1 = 1
F2
F3 = 3
End Enum";
await TestAddFieldAsync(input, expected,
name: "F3", hasConstantValue: true, constantValue: 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544529")]
public async Task AddDelegateType()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Delegate Function D(s As String) As Integer
End Class";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedDelegateType()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Delegate Function D(s As String) As Integer
End Class";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
modifiers: new DeclarationModifiers(isSealed: true),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEvent()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Event E As Action
End Class";
await TestAddEventAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddCustomEventToClassFromSourceSymbol()
{
var sourceGenerated = @"Public Class [|C2|]
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
Events.AddHandler(""ClickEvent"", value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Events.RemoveHandler(""ClickEvent"", value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
CType(Events(""ClickEvent""), EventHandler).Invoke(sender, e)
End RaiseEvent
End Event
End Class";
var input = "Class [|C1|]\nEnd Class";
var expected = @"Class C1
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
Events.AddHandler(""ClickEvent"", value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Events.RemoveHandler(""ClickEvent"", value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
CType(Events(""ClickEvent""), EventHandler).Invoke(sender, e)
End RaiseEvent
End Event
End Class";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessorAndImplementsClause()
{
var input = "Class [|C|] \n End Class";
var expected = @"Class C
Public Custom Event E As ComponentModel.PropertyChangedEventHandler Implements ComponentModel.INotifyPropertyChanged.PropertyChanged
AddHandler(value As ComponentModel.PropertyChangedEventHandler)
End AddHandler
RemoveHandler(value As ComponentModel.PropertyChangedEventHandler)
End RemoveHandler
RaiseEvent(sender As Object, e As ComponentModel.PropertyChangedEventArgs)
End RaiseEvent
End Event
End Class";
static ImmutableArray<IEventSymbol> GetExplicitInterfaceEvent(SemanticModel semanticModel)
{
var parameterSymbols = SpecializedCollections.EmptyList<AttributeData>();
return ImmutableArray.Create<IEventSymbol>(
new CodeGenerationEventSymbol(
GetTypeSymbol(typeof(System.ComponentModel.INotifyPropertyChanged))(semanticModel),
attributes: default,
Accessibility.Public,
modifiers: default,
GetTypeSymbol(typeof(System.ComponentModel.PropertyChangedEventHandler))(semanticModel),
explicitInterfaceImplementations: default,
nameof(System.ComponentModel.INotifyPropertyChanged.PropertyChanged), null, null, null));
}
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
getExplicitInterfaceImplementations: GetExplicitInterfaceEvent,
type: typeof(System.ComponentModel.PropertyChangedEventHandler),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAddAccessor()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Custom Event E As Action
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class";
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessors()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Custom Event E As Action
AddHandler(value As Action)
Console.WriteLine(0)
End AddHandler
RemoveHandler(value As Action)
Console.WriteLine(1)
End RemoveHandler
RaiseEvent()
Console.WriteLine(2)
End RaiseEvent
End Event
End Class";
var addStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(0)"));
var removeStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(1)"));
var raiseStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(2)"));
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, addStatements),
removeMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, removeStatements),
raiseMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, raiseStatements),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClass()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub M()
End Sub
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassFromSourceSymbol()
{
var sourceGenerated = @"Public Class [|C2|]
Public Function FInt() As Integer
Return 0
End Function
End Class";
var input = "Class [|C1|]\nEnd Class";
var expected = @"Class C1
Public Function FInt() As Integer
Return 0
End Function
End Class";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassEscapedName()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Protected Friend Sub [Sub]()
End Sub
End Class";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.ProtectedOrInternal,
name: "Sub",
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddSharedMethodToStructure()
{
var input = "Structure [|S|]\n End Structure";
var expected = @"Structure S
Public Shared Function M() As Integer
Return 0
End Function
End Structure";
await TestAddMethodAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNotOverridableOverridesMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public NotOverridable Overrides Function GetHashCode() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
name: "GetHashCode",
modifiers: new DeclarationModifiers(isOverride: true, isSealed: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMustOverrideMethod()
{
var input = "MustInherit Class [|C|]\n End Class";
var expected = "MustInherit Class C\n Public MustOverride Sub M()\nEnd Class";
await TestAddMethodAsync(input, expected,
modifiers: new DeclarationModifiers(isAbstract: true),
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodWithoutBody()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub M()
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(void),
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddGenericMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Function M(Of T)() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(int),
typeParameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T")),
statements: "Return new T().GetHashCode()");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddVirtualMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Protected Overridable Function M() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.Protected,
modifiers: new DeclarationModifiers(isVirtual: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddShadowsMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shadows Function ToString() As String
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
name: "ToString",
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isNew: true),
returnType: typeof(string),
statements: "Return String.Empty");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitImplementation()
{
var input = "Interface I\n Sub M(i As Integer)\n End Interface\n Class [|C|]\n Implements I\n End Class";
var expected = @"Interface I
Sub M(i As Integer)
End Interface
Class C
Implements I
Public Sub M(i As Integer) Implements I.M
End Sub
End Class";
await TestAddMethodAsync(input, expected,
name: "M",
returnType: typeof(void),
parameters: Parameters(Parameter(typeof(int), "i")),
getExplicitInterfaces: s => s.LookupSymbols(input.IndexOf('M'), null, "M").OfType<IMethodSymbol>().ToImmutableArray());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddTrueFalseOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator IsTrue(other As C) As Boolean
$$
End Operator
Public Shared Operator IsFalse(other As C) As Boolean
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[] { CodeGenerationOperatorKind.True, CodeGenerationOperatorKind.False },
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "Return False");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnaryOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator +(other As C) As Object
$$
End Operator
Public Shared Operator -(other As C) As Object
$$
End Operator
Public Shared Operator Not(other As C) As Object
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.UnaryPlus,
CodeGenerationOperatorKind.UnaryNegation,
CodeGenerationOperatorKind.LogicalNot
},
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(object),
statements: "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddBinaryOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator +(a As C, b As C) As Object
$$
End Operator
Public Shared Operator -(a As C, b As C) As Object
$$
End Operator
Public Shared Operator *(a As C, b As C) As Object
$$
End Operator
Public Shared Operator /(a As C, b As C) As Object
$$
End Operator
Public Shared Operator \(a As C, b As C) As Object
$$
End Operator
Public Shared Operator ^(a As C, b As C) As Object
$$
End Operator
Public Shared Operator &(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Like(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Mod(a As C, b As C) As Object
$$
End Operator
Public Shared Operator And(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Or(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Xor(a As C, b As C) As Object
$$
End Operator
Public Shared Operator <<(a As C, b As C) As Object
$$
End Operator
Public Shared Operator >>(a As C, b As C) As Object
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Addition,
CodeGenerationOperatorKind.Subtraction,
CodeGenerationOperatorKind.Multiplication,
CodeGenerationOperatorKind.Division,
CodeGenerationOperatorKind.IntegerDivision,
CodeGenerationOperatorKind.Exponent,
CodeGenerationOperatorKind.Concatenate,
CodeGenerationOperatorKind.Like,
CodeGenerationOperatorKind.Modulus,
CodeGenerationOperatorKind.BitwiseAnd,
CodeGenerationOperatorKind.BitwiseOr,
CodeGenerationOperatorKind.ExclusiveOr,
CodeGenerationOperatorKind.LeftShift,
CodeGenerationOperatorKind.RightShift
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(object),
statements: "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddComparisonOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator =(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <>(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator >(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator >=(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <=(a As C, b As C) As Boolean
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Equality,
CodeGenerationOperatorKind.Inequality,
CodeGenerationOperatorKind.GreaterThan,
CodeGenerationOperatorKind.LessThan,
CodeGenerationOperatorKind.GreaterThanOrEqual,
CodeGenerationOperatorKind.LessThanOrEqual
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(bool),
statements: "Return True");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsupportedOperator()
{
var input = "Class [|C|]\n End Class";
await TestAddUnsupportedOperatorAsync(input,
operatorKind: CodeGenerationOperatorKind.Increment,
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "Return True");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitConversion()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shared Narrowing Operator CType(other As C) As Integer
$$
End Operator
End Class";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddImplicitConversion()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shared Widening Operator CType(other As C) As Integer
$$
End Operator
End Class";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
isImplicit: true,
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToSub()
{
var input = "Class C\n [|Public Sub M\n Console.WriteLine(1)\n End Sub|]\n End Class";
var expected = @"Class C
Public Sub M
Console.WriteLine(1)
$$ End Sub
End Class";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(2)");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToOperator()
{
var input = "Class C\n [|Shared Operator +(arg As C) As C\n Return arg\n End Operator|]\n End Class";
var expected = @"Class C
Shared Operator +(arg As C) As C
Return arg
$$ End Operator
End Class";
await TestAddStatementsAsync(input, expected, "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToPropertySetter()
{
var input = "Imports System\n Class C\n WriteOnly Property P As String\n [|Set\n End Set|]\n End Property\n End Class";
var expected = @"Imports System
Class C
WriteOnly Property P As String
Set
$$ End Set
End Property
End Class";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(\"Setting the value\"");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToMethod()
{
var input = "Class C\n Public [|Sub M()\n End Sub|]\n End Class";
var expected = @"Class C
Public Sub M(numAs Integer, OptionaltextAs String = ""Hello!"",OptionalfloatingAs Single = 0.5)
End Sub
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num"), Parameter(typeof(string), "text", true, "Hello!"), Parameter(typeof(float), "floating", true, .5F)));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyBlock()
{
var input = "Class C\n [|Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property|]\n End Class";
var expected = @"Class C
Public Property P (numAs Integer) As String
Get
Return String.Empty
End Get
Set(value As String)
End Set
End Property
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyStatement()
{
var input = "Class C\n [|Public Property P As String|]\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
var expected = @"Class C
Public Property P (numAs Integer) As String
Get
Return String.Empty
End Get
Set(value As String)
End Set
End Property
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyGetter_ShouldNotSucceed()
{
var input = "Class C\n Public Property P As String\n [|Get\n Return String.Empty\n End Get|]\n Set(value As String)\n End Set\n End Property\n End Class";
var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertySetter_ShouldNotSucceed()
{
var input = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n [|Set(value As String)\n End Set|]\n End Property\n End Class";
var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToOperator()
{
var input = "Class C\n [|Shared Operator +(a As C) As C\n Return a\n End Operator|]\n End Class";
var expected = @"Class C
Shared Operator +(a As C,bAs C) As C
Return a
End Operator
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter("C", "b")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAutoProperty()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Property P As Integer
End Class";
await TestAddPropertyAsync(input, expected,
type: typeof(int));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddPropertyToClassFromSourceSymbol()
{
var sourceGenerated = @"Public Class [|C2|]
Public Property P As Integer
Get
Return 0
End Get
End Property
End Class";
var input = "Class [|C1|]\nEnd Class";
var expected = @"Class C1
Public Property P As Integer
Get
Return 0
End Get
End Property
End Class";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddPropertyWithoutAccessorBodies()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Property P As Integer
End Class";
await TestAddPropertyAsync(input, expected,
type: typeof(int),
getStatements: "Return 0",
setStatements: "Me.P = Value",
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddIndexer()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Default Public ReadOnly Property Item(i As Integer) As String
Get
$$
End Get
End Property
End Class";
await TestAddPropertyAsync(input, expected,
name: "Item",
type: typeof(string),
parameters: Parameters(Parameter(typeof(int), "i")),
getStatements: "Return String.Empty",
isIndexer: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToTypes()
{
var input = "Class [|C|]\n End Class";
var expected = @"<Serializable>
Class C
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromTypes()
{
var input = @"
<Serializable>
Class [|C|]
End Class";
var expected = @"
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToMethods()
{
var input = "Class C\n Public Sub [|M()|] \n End Sub \n End Class";
var expected = @"Class C
<Serializable>
Public Sub M()
End Sub
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromMethods()
{
var input = @"
Class C
<Serializable>
Public Sub [|M()|]
End Sub
End Class";
var expected = @"
Class C
Public Sub M()
End Sub
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToFields()
{
var input = "Class C\n [|Public F As Integer|]\n End Class";
var expected = @"Class C
<Serializable>
Public F As Integer
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromFields()
{
var input = @"
Class C
<Serializable>
Public [|F|] As Integer
End Class";
var expected = @"
Class C
Public F As Integer
End Class";
await TestRemoveAttributeAsync<FieldDeclarationSyntax>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToProperties()
{
var input = "Class C \n Public Property [|P|] As Integer \n End Class";
var expected = @"Class C
<Serializable>
Public Property P As Integer
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromProperties()
{
var input = @"
Class C
<Serializable>
Public Property [|P|] As Integer
End Class";
var expected = @"
Class C
Public Property P As Integer
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToPropertyAccessor()
{
var input = "Class C \n Public ReadOnly Property P As Integer \n [|Get|] \n Return 10 \n End Get \n End Property \n End Class";
var expected = @"Class C
Public ReadOnly Property P As Integer
<Serializable>
Get
Return 10
End Get
End Property
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromPropertyAccessor()
{
var input = @"
Class C
Public Property P As Integer
<Serializable>
[|Get|]
Return 10
End Get
End Class";
var expected = @"
Class C
Public Property P As Integer
Get
Return 10
End Get
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnums()
{
var input = "Module M \n [|Enum C|] \n One \n Two \n End Enum\n End Module";
var expected = @"Module M
<Serializable>
Enum C
One
Two
End Enum
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnums()
{
var input = @"
Module M
<Serializable>
Enum [|C|]
One
Two
End Enum
End Module";
var expected = @"
Module M
Enum C
One
Two
End Enum
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnumMembers()
{
var input = "Module M \n Enum C \n [|One|] \n Two \n End Enum\n End Module";
var expected = @"Module M
Enum C
<Serializable>
One
Two
End Enum
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnumMembers()
{
var input = @"
Module M
Enum C
<Serializable>
[|One|]
Two
End Enum
End Module";
var expected = @"
Module M
Enum C
One
Two
End Enum
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToModule()
{
var input = "Module [|M|] \n End Module";
var expected = @"<Serializable>
Module M
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromModule()
{
var input = @"
<Serializable>
Module [|M|]
End Module";
var expected = @"
Module M
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToOperator()
{
var input = "Class C \n Public Shared Operator [|+|] (x As C, y As C) As C \n Return New C() \n End Operator \n End Class";
var expected = @"Class C
<Serializable>
Public Shared Operator +(x As C, y As C) As C
Return New C()
End Operator
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromOperator()
{
var input = @"
Module M
Class C
<Serializable>
Public Shared Operator [|+|](x As C, y As C) As C
Return New C()
End Operator
End Class
End Module";
var expected = @"
Module M
Class C
Public Shared Operator +(x As C, y As C) As C
Return New C()
End Operator
End Class
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToDelegate()
{
var input = "Module M \n Delegate Sub [|D()|]\n End Module";
var expected = "Module M\n <Serializable>\n Delegate Sub D()\nEnd Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromDelegate()
{
var input = @"
Module M
<Serializable>
Delegate Sub [|D()|]
End Module";
var expected = @"
Module M
Delegate Sub D()
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToParam()
{
var input = "Class C \n Public Sub M([|x As Integer|]) \n End Sub \n End Class";
var expected = "Class C \n Public Sub M(<Serializable> x As Integer) \n End Sub \n End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromParam()
{
var input = @"
Class C
Public Sub M(<Serializable> [|x As Integer|])
End Sub
End Class";
var expected = @"
Class C
Public Sub M(x As Integer)
End Sub
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToCompilationUnit()
{
var input = "[|Class C \n End Class \n Class D \n End Class|]";
var expected = "<Assembly: Serializable>\nClass C\nEnd Class\nClass D\nEnd Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.AssemblyKeyword));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeWithWrongTarget()
{
var input = "[|Class C \n End Class \n Class D \n End Class|]";
var expected = "<Assembly: Serializable> Class C \n End Class \n Class D \n End Class";
await Assert.ThrowsAsync<AggregateException>(async () =>
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.ReturnKeyword)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia()
{
// With trivia.
var input = @"' Comment 1
<System.Serializable> ' Comment 2
Class [|C|]
End Class";
var expected = @"' Comment 1
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia_NewLine()
{
// With trivia, redundant newline at end of attribute removed.
var input = @"' Comment 1
<System.Serializable>
Class [|C|]
End Class";
var expected = @"' Comment 1
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributes()
{
// Multiple attributes.
var input = @"' Comment 1
< System.Serializable , System.Flags> ' Comment 2
Class [|C|]
End Class";
var expected = @"' Comment 1
<System.Flags> ' Comment 2
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributeLists()
{
// Multiple attribute lists.
var input = @"' Comment 1
< System.Serializable , System.Flags> ' Comment 2
<System.Obsolete> ' Comment 3
Class [|C|]
End Class";
var expected = @"' Comment 1
<System.Flags> ' Comment 2
<System.Obsolete> ' Comment 3
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateModifiers()
{
var input = @"Public Shared Class [|C|] ' Comment 1
' Comment 2
End Class";
var expected = @"Friend Partial NotInheritable Class C ' Comment 1
' Comment 2
End Class";
var eol = VB.SyntaxFactory.EndOfLine(@"");
var newModifiers = new[] { VB.SyntaxFactory.Token(VB.SyntaxKind.FriendKeyword).WithLeadingTrivia(eol) }.Concat(
CreateModifierTokens(new DeclarationModifiers(isSealed: true, isPartial: true), LanguageNames.VisualBasic));
await TestUpdateDeclarationAsync<ClassStatementSyntax>(input, expected, modifiers: newModifiers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateAccessibility()
{
var input = @"' Comment 0
Public Shared Class [|C|] ' Comment 1
' Comment 2
End Class";
var expected = @"' Comment 0
Protected Friend Shared Class C ' Comment 1
' Comment 2
End Class";
await TestUpdateDeclarationAsync<ClassStatementSyntax>(input, expected, accessibility: Accessibility.ProtectedOrFriend);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationType()
{
var input = @"
Public Shared Class C
' Comment 1
Public Shared Function [|F|]() As Char
Return 0
End Function
End Class";
var expected = @"
Public Shared Class C
' Comment 1
Public Shared Function F() As Integer
Return 0
End Function
End Class";
await TestUpdateDeclarationAsync<MethodStatementSyntax>(input, expected, getType: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationMembers()
{
var input = @"
Public Shared Class [|C|]
' Comment 0
Public Shared {|RetainedMember:f|} As Integer
' Comment 1
Public Shared Function F() As Char
Return 0
End Function
End Class";
var expected = @"
Public Shared Class C
' Comment 0
Public Shared f As Integer
Public Shared f2 As Integer
End Class";
var getField = CreateField(Accessibility.Public, new DeclarationModifiers(isStatic: true), typeof(int), "f2");
var getMembers = ImmutableArray.Create(getField);
await TestUpdateDeclarationAsync<ClassBlockSyntax>(input, expected, getNewMembers: getMembers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortModules()
{
var generationSource = "Public Class [|C|] \n End Class";
var initial = "Namespace [|N|] \n Module M \n End Module \n End Namespace";
var expected = @"Namespace N
Public Class C
End Class
Module M
End Module
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortOperators()
{
var generationSource = @"
Namespace N
Public Class [|C|]
' Unary operators
Public Shared Operator IsFalse(other As C) As Boolean
Return False
End Operator
Public Shared Operator IsTrue(other As C) As Boolean
Return True
End Operator
Public Shared Operator Not(other As C) As C
Return Nothing
End Operator
Public Shared Operator -(other As C) As C
Return Nothing
End Operator
Public Shared Operator + (other As C) As C
Return Nothing
End Operator
Public Shared Narrowing Operator CType(c As C) As Integer
Return 0
End Operator
' Binary operators
Public Shared Operator >= (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator <= (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator > (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator < (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator <> (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator = (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator >> (a As C, shift As Integer) As C
Return Nothing
End Operator
Public Shared Operator << (a As C, shift As Integer) As C
Return Nothing
End Operator
Public Shared Operator Xor(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Or(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator And(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Mod(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Like (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator & (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator ^ (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator \ (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator / (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator *(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator -(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator + (a As C, b As C) As C
Return Nothing
End Operator
End Class
End Namespace";
var initial = "Namespace [|N|] \n End Namespace";
var expected = @"Namespace N
Public Class C
Public Shared Operator +(other As C) As C
Public Shared Operator +(a As C, b As C) As C
Public Shared Operator -(other As C) As C
Public Shared Operator -(a As C, b As C) As C
Public Shared Operator *(a As C, b As C) As C
Public Shared Operator /(a As C, b As C) As C
Public Shared Operator \(a As C, b As C) As C
Public Shared Operator ^(a As C, b As C) As C
Public Shared Operator &(a As C, b As C) As C
Public Shared Operator Not(other As C) As C
Public Shared Operator Like(a As C, b As C) As C
Public Shared Operator Mod(a As C, b As C) As C
Public Shared Operator And(a As C, b As C) As C
Public Shared Operator Or(a As C, b As C) As C
Public Shared Operator Xor(a As C, b As C) As C
Public Shared Operator <<(a As C, shift As Integer) As C
Public Shared Operator >>(a As C, shift As Integer) As C
Public Shared Operator =(a As C, b As C) As Boolean
Public Shared Operator <>(a As C, b As C) As Boolean
Public Shared Operator >(a As C, b As C) As Boolean
Public Shared Operator <(a As C, b As C) As Boolean
Public Shared Operator >=(a As C, b As C) As Boolean
Public Shared Operator <=(a As C, b As C) As Boolean
Public Shared Operator IsTrue(other As C) As Boolean
Public Shared Operator IsFalse(other As C) As Boolean
Public Shared Narrowing Operator CType(c As C) As Integer
End Class
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
forceLanguage: LanguageNames.VisualBasic,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[WorkItem(848357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/848357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestConstraints()
{
var generationSource = @"
Namespace N
Public Class [|C|](Of T As Structure, U As Class)
Public Sub Goo(Of Q As New, R As IComparable)()
End Sub
Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2)
End Class
End Namespace
";
var initial = "Namespace [|N|] \n End Namespace";
var expected = @"Namespace N
Public Class C(Of T As Structure, U As Class)
Public Sub Goo(Of Q As New, R As IComparable)()
Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2)
End Class
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.VisualBasic.Syntax;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using VB = Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration
{
public partial class CodeGenerationTests
{
[UseExportProvider]
public class VisualBasic
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNamespace()
{
var input = "Namespace [|N1|]\n End Namespace";
var expected = @"Namespace N1
Namespace N2
End Namespace
End Namespace";
await TestAddNamespaceAsync(input, expected,
name: "N2");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public F As Integer
End Class";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSharedField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Private Shared F As String
End Class";
await TestAddFieldAsync(input, expected,
type: GetTypeSymbol(typeof(string)),
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddArrayField()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public F As Integer()
End Class";
await TestAddFieldAsync(input, expected,
type: CreateArrayType(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructor()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub New()
End Sub
End Class";
await TestAddConstructorAsync(input, expected);
}
[WorkItem(530785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530785")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithXmlComment()
{
var input = @"
Public Class [|C|]
''' <summary>
''' Do Nothing
''' </summary>
Public Sub GetStates()
End Sub
End Class";
var expected = @"
Public Class C
Public Sub New()
End Sub
''' <summary>
''' Do Nothing
''' </summary>
Public Sub GetStates()
End Sub
End Class";
await TestAddConstructorAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorWithoutBody()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub New()
End Class";
await TestAddConstructorAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddConstructorResolveNamespaceImport()
{
var input = "Class [|C|]\n End Class";
var expected = @"Imports System.Text
Class C
Public Sub New(s As StringBuilder)
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
parameters: Parameters(Parameter(typeof(StringBuilder), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddSharedConstructor()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Shared Sub New()
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddChainedConstructor()
{
var input = "Class [|C|]\n Public Sub New(i As Integer)\n End Sub\n End Class";
var expected = @"Class C
Public Sub New()
Me.New(42)
End Sub
Public Sub New(i As Integer)
End Sub
End Class";
await TestAddConstructorAsync(input, expected,
thisArguments: ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExpression("42")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544476")]
public async Task AddClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassEscapeName()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class [Class]
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddClassUnicodeName()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Class [Class]
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "Class");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddNotInheritableClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public NotInheritable Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
modifiers: new DeclarationModifiers(isSealed: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddMustInheritClass()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Friend MustInherit Class C
End Class
End Namespace";
await TestAddNamedTypeAsync(input, expected,
accessibility: Accessibility.Internal,
modifiers: new DeclarationModifiers(isAbstract: true));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStructure()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Friend Structure S
End Structure
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Internal,
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedStructure()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Structure S
End Structure
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "S",
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isSealed: true),
typeKind: TypeKind.Struct);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddInterface()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Interface I
End Interface
End Namespace";
await TestAddNamedTypeAsync(input, expected,
name: "I",
typeKind: TypeKind.Interface);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544528, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544528")]
public async Task AddEnum()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Enum E
F1
End Enum
End Namespace";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", null)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544527")]
public async Task AddEnumWithValues()
{
var input = "Namespace [|N|]\n End Namespace";
var expected = @"Namespace N
Public Enum E
F1 = 1
F2 = 2
End Enum
End Namespace";
await TestAddNamedTypeAsync(input, expected, "E",
typeKind: TypeKind.Enum,
members: Members(CreateEnumField("F1", 1), CreateEnumField("F2", 2)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEnumMember()
{
var input = "Public Enum [|E|]\n F1 = 1\n F2 = 2\n End Enum";
var expected = @"Public Enum E
F1 = 1
F2 = 2
F3
End Enum";
await TestAddFieldAsync(input, expected,
name: "F3");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEnumMemberWithValue()
{
var input = "Public Enum [|E|]\n F1 = 1\n F2\n End Enum";
var expected = @"Public Enum E
F1 = 1
F2
F3 = 3
End Enum";
await TestAddFieldAsync(input, expected,
name: "F3", hasConstantValue: true, constantValue: 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544529")]
public async Task AddDelegateType()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Delegate Function D(s As String) As Integer
End Class";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(546224, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546224")]
public async Task AddSealedDelegateType()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Delegate Function D(s As String) As Integer
End Class";
await TestAddDelegateTypeAsync(input, expected,
returnType: typeof(int),
modifiers: new DeclarationModifiers(isSealed: true),
parameters: Parameters(Parameter(typeof(string), "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEvent()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Event E As Action
End Class";
await TestAddEventAsync(input, expected,
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddCustomEventToClassFromSourceSymbol()
{
var sourceGenerated = @"Public Class [|C2|]
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
Events.AddHandler(""ClickEvent"", value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Events.RemoveHandler(""ClickEvent"", value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
CType(Events(""ClickEvent""), EventHandler).Invoke(sender, e)
End RaiseEvent
End Event
End Class";
var input = "Class [|C1|]\nEnd Class";
var expected = @"Class C1
Public Custom Event Click As EventHandler
AddHandler(ByVal value As EventHandler)
Events.AddHandler(""ClickEvent"", value)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
Events.RemoveHandler(""ClickEvent"", value)
End RemoveHandler
RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
CType(Events(""ClickEvent""), EventHandler).Invoke(sender, e)
End RaiseEvent
End Event
End Class";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessorAndImplementsClause()
{
var input = "Class [|C|] \n End Class";
var expected = @"Class C
Public Custom Event E As ComponentModel.PropertyChangedEventHandler Implements ComponentModel.INotifyPropertyChanged.PropertyChanged
AddHandler(value As ComponentModel.PropertyChangedEventHandler)
End AddHandler
RemoveHandler(value As ComponentModel.PropertyChangedEventHandler)
End RemoveHandler
RaiseEvent(sender As Object, e As ComponentModel.PropertyChangedEventArgs)
End RaiseEvent
End Event
End Class";
static ImmutableArray<IEventSymbol> GetExplicitInterfaceEvent(SemanticModel semanticModel)
{
var parameterSymbols = SpecializedCollections.EmptyList<AttributeData>();
return ImmutableArray.Create<IEventSymbol>(
new CodeGenerationEventSymbol(
GetTypeSymbol(typeof(System.ComponentModel.INotifyPropertyChanged))(semanticModel),
attributes: default,
Accessibility.Public,
modifiers: default,
GetTypeSymbol(typeof(System.ComponentModel.PropertyChangedEventHandler))(semanticModel),
explicitInterfaceImplementations: default,
nameof(System.ComponentModel.INotifyPropertyChanged.PropertyChanged), null, null, null));
}
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
getExplicitInterfaceImplementations: GetExplicitInterfaceEvent,
type: typeof(System.ComponentModel.PropertyChangedEventHandler),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAddAccessor()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Custom Event E As Action
AddHandler(value As Action)
End AddHandler
RemoveHandler(value As Action)
End RemoveHandler
RaiseEvent()
End RaiseEvent
End Event
End Class";
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, ImmutableArray<SyntaxNode>.Empty),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddEventWithAccessors()
{
var input = @"
Class [|C|]
End Class";
var expected = @"
Class C
Public Custom Event E As Action
AddHandler(value As Action)
Console.WriteLine(0)
End AddHandler
RemoveHandler(value As Action)
Console.WriteLine(1)
End RemoveHandler
RaiseEvent()
Console.WriteLine(2)
End RaiseEvent
End Event
End Class";
var addStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(0)"));
var removeStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(1)"));
var raiseStatements = ImmutableArray.Create<SyntaxNode>(VB.SyntaxFactory.ParseExecutableStatement("Console.WriteLine(2)"));
await TestAddEventAsync(input, expected,
addMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, addStatements),
removeMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, removeStatements),
raiseMethod: CodeGenerationSymbolFactory.CreateAccessorSymbol(
ImmutableArray<AttributeData>.Empty, Accessibility.NotApplicable, raiseStatements),
codeGenerationOptions: new CodeGenerationOptions(addImports: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClass()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub M()
End Sub
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassFromSourceSymbol()
{
var sourceGenerated = @"Public Class [|C2|]
Public Function FInt() As Integer
Return 0
End Function
End Class";
var input = "Class [|C1|]\nEnd Class";
var expected = @"Class C1
Public Function FInt() As Integer
Return 0
End Function
End Class";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodToClassEscapedName()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Protected Friend Sub [Sub]()
End Sub
End Class";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.ProtectedOrInternal,
name: "Sub",
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration), WorkItem(544477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544477")]
public async Task AddSharedMethodToStructure()
{
var input = "Structure [|S|]\n End Structure";
var expected = @"Structure S
Public Shared Function M() As Integer
Return 0
End Function
End Structure";
await TestAddMethodAsync(input, expected,
modifiers: new DeclarationModifiers(isStatic: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddNotOverridableOverridesMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public NotOverridable Overrides Function GetHashCode() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
name: "GetHashCode",
modifiers: new DeclarationModifiers(isOverride: true, isSealed: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMustOverrideMethod()
{
var input = "MustInherit Class [|C|]\n End Class";
var expected = "MustInherit Class C\n Public MustOverride Sub M()\nEnd Class";
await TestAddMethodAsync(input, expected,
modifiers: new DeclarationModifiers(isAbstract: true),
returnType: typeof(void));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddMethodWithoutBody()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Sub M()
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(void),
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddGenericMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Function M(Of T)() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
returnType: typeof(int),
typeParameters: ImmutableArray.Create(CodeGenerationSymbolFactory.CreateTypeParameterSymbol("T")),
statements: "Return new T().GetHashCode()");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddVirtualMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Protected Overridable Function M() As Integer
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
accessibility: Accessibility.Protected,
modifiers: new DeclarationModifiers(isVirtual: true),
returnType: typeof(int),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddShadowsMethod()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shadows Function ToString() As String
$$
End Function
End Class";
await TestAddMethodAsync(input, expected,
name: "ToString",
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(isNew: true),
returnType: typeof(string),
statements: "Return String.Empty");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitImplementation()
{
var input = "Interface I\n Sub M(i As Integer)\n End Interface\n Class [|C|]\n Implements I\n End Class";
var expected = @"Interface I
Sub M(i As Integer)
End Interface
Class C
Implements I
Public Sub M(i As Integer) Implements I.M
End Sub
End Class";
await TestAddMethodAsync(input, expected,
name: "M",
returnType: typeof(void),
parameters: Parameters(Parameter(typeof(int), "i")),
getExplicitInterfaces: s => s.LookupSymbols(input.IndexOf('M'), null, "M").OfType<IMethodSymbol>().ToImmutableArray());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddTrueFalseOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator IsTrue(other As C) As Boolean
$$
End Operator
Public Shared Operator IsFalse(other As C) As Boolean
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[] { CodeGenerationOperatorKind.True, CodeGenerationOperatorKind.False },
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "Return False");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnaryOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator +(other As C) As Object
$$
End Operator
Public Shared Operator -(other As C) As Object
$$
End Operator
Public Shared Operator Not(other As C) As Object
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.UnaryPlus,
CodeGenerationOperatorKind.UnaryNegation,
CodeGenerationOperatorKind.LogicalNot
},
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(object),
statements: "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddBinaryOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator +(a As C, b As C) As Object
$$
End Operator
Public Shared Operator -(a As C, b As C) As Object
$$
End Operator
Public Shared Operator *(a As C, b As C) As Object
$$
End Operator
Public Shared Operator /(a As C, b As C) As Object
$$
End Operator
Public Shared Operator \(a As C, b As C) As Object
$$
End Operator
Public Shared Operator ^(a As C, b As C) As Object
$$
End Operator
Public Shared Operator &(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Like(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Mod(a As C, b As C) As Object
$$
End Operator
Public Shared Operator And(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Or(a As C, b As C) As Object
$$
End Operator
Public Shared Operator Xor(a As C, b As C) As Object
$$
End Operator
Public Shared Operator <<(a As C, b As C) As Object
$$
End Operator
Public Shared Operator >>(a As C, b As C) As Object
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Addition,
CodeGenerationOperatorKind.Subtraction,
CodeGenerationOperatorKind.Multiplication,
CodeGenerationOperatorKind.Division,
CodeGenerationOperatorKind.IntegerDivision,
CodeGenerationOperatorKind.Exponent,
CodeGenerationOperatorKind.Concatenate,
CodeGenerationOperatorKind.Like,
CodeGenerationOperatorKind.Modulus,
CodeGenerationOperatorKind.BitwiseAnd,
CodeGenerationOperatorKind.BitwiseOr,
CodeGenerationOperatorKind.ExclusiveOr,
CodeGenerationOperatorKind.LeftShift,
CodeGenerationOperatorKind.RightShift
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(object),
statements: "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddComparisonOperators()
{
var input = @"
Class [|C|]
End Class
";
var expected = @"
Class C
Public Shared Operator =(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <>(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator >(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator >=(a As C, b As C) As Boolean
$$
End Operator
Public Shared Operator <=(a As C, b As C) As Boolean
$$
End Operator
End Class
";
await TestAddOperatorsAsync(input, expected,
new[]
{
CodeGenerationOperatorKind.Equality,
CodeGenerationOperatorKind.Inequality,
CodeGenerationOperatorKind.GreaterThan,
CodeGenerationOperatorKind.LessThan,
CodeGenerationOperatorKind.GreaterThanOrEqual,
CodeGenerationOperatorKind.LessThanOrEqual
},
parameters: Parameters(Parameter("C", "a"), Parameter("C", "b")),
returnType: typeof(bool),
statements: "Return True");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddUnsupportedOperator()
{
var input = "Class [|C|]\n End Class";
await TestAddUnsupportedOperatorAsync(input,
operatorKind: CodeGenerationOperatorKind.Increment,
parameters: Parameters(Parameter("C", "other")),
returnType: typeof(bool),
statements: "Return True");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddExplicitConversion()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shared Narrowing Operator CType(other As C) As Integer
$$
End Operator
End Class";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddImplicitConversion()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Shared Widening Operator CType(other As C) As Integer
$$
End Operator
End Class";
await TestAddConversionAsync(input, expected,
toType: typeof(int),
fromType: Parameter("C", "other"),
isImplicit: true,
statements: "Return 0");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToSub()
{
var input = "Class C\n [|Public Sub M\n Console.WriteLine(1)\n End Sub|]\n End Class";
var expected = @"Class C
Public Sub M
Console.WriteLine(1)
$$ End Sub
End Class";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(2)");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToOperator()
{
var input = "Class C\n [|Shared Operator +(arg As C) As C\n Return arg\n End Operator|]\n End Class";
var expected = @"Class C
Shared Operator +(arg As C) As C
Return arg
$$ End Operator
End Class";
await TestAddStatementsAsync(input, expected, "Return Nothing");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddStatementsToPropertySetter()
{
var input = "Imports System\n Class C\n WriteOnly Property P As String\n [|Set\n End Set|]\n End Property\n End Class";
var expected = @"Imports System
Class C
WriteOnly Property P As String
Set
$$ End Set
End Property
End Class";
await TestAddStatementsAsync(input, expected, "Console.WriteLine(\"Setting the value\"");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToMethod()
{
var input = "Class C\n Public [|Sub M()\n End Sub|]\n End Class";
var expected = @"Class C
Public Sub M(numAs Integer, OptionaltextAs String = ""Hello!"",OptionalfloatingAs Single = 0.5)
End Sub
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num"), Parameter(typeof(string), "text", true, "Hello!"), Parameter(typeof(float), "floating", true, .5F)));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyBlock()
{
var input = "Class C\n [|Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property|]\n End Class";
var expected = @"Class C
Public Property P (numAs Integer) As String
Get
Return String.Empty
End Get
Set(value As String)
End Set
End Property
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyStatement()
{
var input = "Class C\n [|Public Property P As String|]\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
var expected = @"Class C
Public Property P (numAs Integer) As String
Get
Return String.Empty
End Get
Set(value As String)
End Set
End Property
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertyGetter_ShouldNotSucceed()
{
var input = "Class C\n Public Property P As String\n [|Get\n Return String.Empty\n End Get|]\n Set(value As String)\n End Set\n End Property\n End Class";
var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[WorkItem(844460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844460")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToPropertySetter_ShouldNotSucceed()
{
var input = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n [|Set(value As String)\n End Set|]\n End Property\n End Class";
var expected = "Class C\n Public Property P As String\n Get\n Return String.Empty\n End Get\n Set(value As String)\n End Set\n End Property\n End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter(typeof(int), "num")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddParametersToOperator()
{
var input = "Class C\n [|Shared Operator +(a As C) As C\n Return a\n End Operator|]\n End Class";
var expected = @"Class C
Shared Operator +(a As C,bAs C) As C
Return a
End Operator
End Class";
await TestAddParametersAsync(input, expected,
Parameters(Parameter("C", "b")));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAutoProperty()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Property P As Integer
End Class";
await TestAddPropertyAsync(input, expected,
type: typeof(int));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddPropertyToClassFromSourceSymbol()
{
var sourceGenerated = @"Public Class [|C2|]
Public Property P As Integer
Get
Return 0
End Get
End Property
End Class";
var input = "Class [|C1|]\nEnd Class";
var expected = @"Class C1
Public Property P As Integer
Get
Return 0
End Get
End Property
End Class";
var options = new CodeGenerationOptions(reuseSyntax: true);
await TestGenerateFromSourceSymbolAsync(sourceGenerated, input, expected, onlyGenerateMembers: true, codeGenerationOptions: options);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddPropertyWithoutAccessorBodies()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Public Property P As Integer
End Class";
await TestAddPropertyAsync(input, expected,
type: typeof(int),
getStatements: "Return 0",
setStatements: "Me.P = Value",
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddIndexer()
{
var input = "Class [|C|]\n End Class";
var expected = @"Class C
Default Public ReadOnly Property Item(i As Integer) As String
Get
$$
End Get
End Property
End Class";
await TestAddPropertyAsync(input, expected,
name: "Item",
type: typeof(string),
parameters: Parameters(Parameter(typeof(int), "i")),
getStatements: "Return String.Empty",
isIndexer: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToTypes()
{
var input = "Class [|C|]\n End Class";
var expected = @"<Serializable>
Class C
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromTypes()
{
var input = @"
<Serializable>
Class [|C|]
End Class";
var expected = @"
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToMethods()
{
var input = "Class C\n Public Sub [|M()|] \n End Sub \n End Class";
var expected = @"Class C
<Serializable>
Public Sub M()
End Sub
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromMethods()
{
var input = @"
Class C
<Serializable>
Public Sub [|M()|]
End Sub
End Class";
var expected = @"
Class C
Public Sub M()
End Sub
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToFields()
{
var input = "Class C\n [|Public F As Integer|]\n End Class";
var expected = @"Class C
<Serializable>
Public F As Integer
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromFields()
{
var input = @"
Class C
<Serializable>
Public [|F|] As Integer
End Class";
var expected = @"
Class C
Public F As Integer
End Class";
await TestRemoveAttributeAsync<FieldDeclarationSyntax>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToProperties()
{
var input = "Class C \n Public Property [|P|] As Integer \n End Class";
var expected = @"Class C
<Serializable>
Public Property P As Integer
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromProperties()
{
var input = @"
Class C
<Serializable>
Public Property [|P|] As Integer
End Class";
var expected = @"
Class C
Public Property P As Integer
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToPropertyAccessor()
{
var input = "Class C \n Public ReadOnly Property P As Integer \n [|Get|] \n Return 10 \n End Get \n End Property \n End Class";
var expected = @"Class C
Public ReadOnly Property P As Integer
<Serializable>
Get
Return 10
End Get
End Property
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromPropertyAccessor()
{
var input = @"
Class C
Public Property P As Integer
<Serializable>
[|Get|]
Return 10
End Get
End Class";
var expected = @"
Class C
Public Property P As Integer
Get
Return 10
End Get
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnums()
{
var input = "Module M \n [|Enum C|] \n One \n Two \n End Enum\n End Module";
var expected = @"Module M
<Serializable>
Enum C
One
Two
End Enum
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnums()
{
var input = @"
Module M
<Serializable>
Enum [|C|]
One
Two
End Enum
End Module";
var expected = @"
Module M
Enum C
One
Two
End Enum
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToEnumMembers()
{
var input = "Module M \n Enum C \n [|One|] \n Two \n End Enum\n End Module";
var expected = @"Module M
Enum C
<Serializable>
One
Two
End Enum
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromEnumMembers()
{
var input = @"
Module M
Enum C
<Serializable>
[|One|]
Two
End Enum
End Module";
var expected = @"
Module M
Enum C
One
Two
End Enum
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToModule()
{
var input = "Module [|M|] \n End Module";
var expected = @"<Serializable>
Module M
End Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromModule()
{
var input = @"
<Serializable>
Module [|M|]
End Module";
var expected = @"
Module M
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToOperator()
{
var input = "Class C \n Public Shared Operator [|+|] (x As C, y As C) As C \n Return New C() \n End Operator \n End Class";
var expected = @"Class C
<Serializable>
Public Shared Operator +(x As C, y As C) As C
Return New C()
End Operator
End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromOperator()
{
var input = @"
Module M
Class C
<Serializable>
Public Shared Operator [|+|](x As C, y As C) As C
Return New C()
End Operator
End Class
End Module";
var expected = @"
Module M
Class C
Public Shared Operator +(x As C, y As C) As C
Return New C()
End Operator
End Class
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToDelegate()
{
var input = "Module M \n Delegate Sub [|D()|]\n End Module";
var expected = "Module M\n <Serializable>\n Delegate Sub D()\nEnd Module";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromDelegate()
{
var input = @"
Module M
<Serializable>
Delegate Sub [|D()|]
End Module";
var expected = @"
Module M
Delegate Sub D()
End Module";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToParam()
{
var input = "Class C \n Public Sub M([|x As Integer|]) \n End Sub \n End Class";
var expected = "Class C \n Public Sub M(<Serializable> x As Integer) \n End Sub \n End Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeFromParam()
{
var input = @"
Class C
Public Sub M(<Serializable> [|x As Integer|])
End Sub
End Class";
var expected = @"
Class C
Public Sub M(x As Integer)
End Sub
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeToCompilationUnit()
{
var input = "[|Class C \n End Class \n Class D \n End Class|]";
var expected = "<Assembly: Serializable>\nClass C\nEnd Class\nClass D\nEnd Class";
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.AssemblyKeyword));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task AddAttributeWithWrongTarget()
{
var input = "[|Class C \n End Class \n Class D \n End Class|]";
var expected = "<Assembly: Serializable> Class C \n End Class \n Class D \n End Class";
await Assert.ThrowsAsync<AggregateException>(async () =>
await TestAddAttributeAsync(input, expected, typeof(SerializableAttribute), VB.SyntaxFactory.Token(VB.SyntaxKind.ReturnKeyword)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia()
{
// With trivia.
var input = @"' Comment 1
<System.Serializable> ' Comment 2
Class [|C|]
End Class";
var expected = @"' Comment 1
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithTrivia_NewLine()
{
// With trivia, redundant newline at end of attribute removed.
var input = @"' Comment 1
<System.Serializable>
Class [|C|]
End Class";
var expected = @"' Comment 1
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributes()
{
// Multiple attributes.
var input = @"' Comment 1
< System.Serializable , System.Flags> ' Comment 2
Class [|C|]
End Class";
var expected = @"' Comment 1
<System.Flags> ' Comment 2
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task RemoveAttributeWithMultipleAttributeLists()
{
// Multiple attribute lists.
var input = @"' Comment 1
< System.Serializable , System.Flags> ' Comment 2
<System.Obsolete> ' Comment 3
Class [|C|]
End Class";
var expected = @"' Comment 1
<System.Flags> ' Comment 2
<System.Obsolete> ' Comment 3
Class C
End Class";
await TestRemoveAttributeAsync<SyntaxNode>(input, expected, typeof(SerializableAttribute));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateModifiers()
{
var input = @"Public Shared Class [|C|] ' Comment 1
' Comment 2
End Class";
var expected = @"Friend Partial NotInheritable Class C ' Comment 1
' Comment 2
End Class";
var eol = VB.SyntaxFactory.EndOfLine(@"");
var newModifiers = new[] { VB.SyntaxFactory.Token(VB.SyntaxKind.FriendKeyword).WithLeadingTrivia(eol) }.Concat(
CreateModifierTokens(new DeclarationModifiers(isSealed: true, isPartial: true), LanguageNames.VisualBasic));
await TestUpdateDeclarationAsync<ClassStatementSyntax>(input, expected, modifiers: newModifiers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateAccessibility()
{
var input = @"' Comment 0
Public Shared Class [|C|] ' Comment 1
' Comment 2
End Class";
var expected = @"' Comment 0
Protected Friend Shared Class C ' Comment 1
' Comment 2
End Class";
await TestUpdateDeclarationAsync<ClassStatementSyntax>(input, expected, accessibility: Accessibility.ProtectedOrFriend);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationType()
{
var input = @"
Public Shared Class C
' Comment 1
Public Shared Function [|F|]() As Char
Return 0
End Function
End Class";
var expected = @"
Public Shared Class C
' Comment 1
Public Shared Function F() As Integer
Return 0
End Function
End Class";
await TestUpdateDeclarationAsync<MethodStatementSyntax>(input, expected, getType: GetTypeSymbol(typeof(int)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestUpdateDeclarationMembers()
{
var input = @"
Public Shared Class [|C|]
' Comment 0
Public Shared {|RetainedMember:f|} As Integer
' Comment 1
Public Shared Function F() As Char
Return 0
End Function
End Class";
var expected = @"
Public Shared Class C
' Comment 0
Public Shared f As Integer
Public Shared f2 As Integer
End Class";
var getField = CreateField(Accessibility.Public, new DeclarationModifiers(isStatic: true), typeof(int), "f2");
var getMembers = ImmutableArray.Create(getField);
await TestUpdateDeclarationAsync<ClassBlockSyntax>(input, expected, getNewMembers: getMembers);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortModules()
{
var generationSource = "Public Class [|C|] \n End Class";
var initial = "Namespace [|N|] \n Module M \n End Module \n End Namespace";
var expected = @"Namespace N
Public Class C
End Class
Module M
End Module
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeGenerationSortDeclarations)]
public async Task SortOperators()
{
var generationSource = @"
Namespace N
Public Class [|C|]
' Unary operators
Public Shared Operator IsFalse(other As C) As Boolean
Return False
End Operator
Public Shared Operator IsTrue(other As C) As Boolean
Return True
End Operator
Public Shared Operator Not(other As C) As C
Return Nothing
End Operator
Public Shared Operator -(other As C) As C
Return Nothing
End Operator
Public Shared Operator + (other As C) As C
Return Nothing
End Operator
Public Shared Narrowing Operator CType(c As C) As Integer
Return 0
End Operator
' Binary operators
Public Shared Operator >= (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator <= (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator > (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator < (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator <> (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator = (a As C, b As C) As Boolean
Return True
End Operator
Public Shared Operator >> (a As C, shift As Integer) As C
Return Nothing
End Operator
Public Shared Operator << (a As C, shift As Integer) As C
Return Nothing
End Operator
Public Shared Operator Xor(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Or(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator And(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Mod(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator Like (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator & (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator ^ (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator \ (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator / (a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator *(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator -(a As C, b As C) As C
Return Nothing
End Operator
Public Shared Operator + (a As C, b As C) As C
Return Nothing
End Operator
End Class
End Namespace";
var initial = "Namespace [|N|] \n End Namespace";
var expected = @"Namespace N
Public Class C
Public Shared Operator +(other As C) As C
Public Shared Operator +(a As C, b As C) As C
Public Shared Operator -(other As C) As C
Public Shared Operator -(a As C, b As C) As C
Public Shared Operator *(a As C, b As C) As C
Public Shared Operator /(a As C, b As C) As C
Public Shared Operator \(a As C, b As C) As C
Public Shared Operator ^(a As C, b As C) As C
Public Shared Operator &(a As C, b As C) As C
Public Shared Operator Not(other As C) As C
Public Shared Operator Like(a As C, b As C) As C
Public Shared Operator Mod(a As C, b As C) As C
Public Shared Operator And(a As C, b As C) As C
Public Shared Operator Or(a As C, b As C) As C
Public Shared Operator Xor(a As C, b As C) As C
Public Shared Operator <<(a As C, shift As Integer) As C
Public Shared Operator >>(a As C, shift As Integer) As C
Public Shared Operator =(a As C, b As C) As Boolean
Public Shared Operator <>(a As C, b As C) As Boolean
Public Shared Operator >(a As C, b As C) As Boolean
Public Shared Operator <(a As C, b As C) As Boolean
Public Shared Operator >=(a As C, b As C) As Boolean
Public Shared Operator <=(a As C, b As C) As Boolean
Public Shared Operator IsTrue(other As C) As Boolean
Public Shared Operator IsFalse(other As C) As Boolean
Public Shared Narrowing Operator CType(c As C) As Integer
End Class
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
forceLanguage: LanguageNames.VisualBasic,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false));
}
[WorkItem(848357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/848357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public async Task TestConstraints()
{
var generationSource = @"
Namespace N
Public Class [|C|](Of T As Structure, U As Class)
Public Sub Goo(Of Q As New, R As IComparable)()
End Sub
Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2)
End Class
End Namespace
";
var initial = "Namespace [|N|] \n End Namespace";
var expected = @"Namespace N
Public Class C(Of T As Structure, U As Class)
Public Sub Goo(Of Q As New, R As IComparable)()
Public Delegate Sub D(Of T1 As Structure, T2 As Class)(t As T1, u As T2)
End Class
End Namespace";
await TestGenerateFromSourceSymbolAsync(generationSource, initial, expected,
codeGenerationOptions: new CodeGenerationOptions(generateMethodBodies: false),
onlyGenerateMembers: true);
}
}
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Features/Core/Portable/CodeFixes/CodeFixService.ProjectCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal partial class CodeFixService
{
private class ProjectCodeFixProvider
: AbstractProjectExtensionProvider<CodeFixProvider, ExportCodeFixProviderAttribute>
{
public ProjectCodeFixProvider(AnalyzerReference reference)
: base(reference)
{
}
protected override bool SupportsLanguage(ExportCodeFixProviderAttribute exportAttribute, string language)
{
return exportAttribute.Languages == null
|| exportAttribute.Languages.Length == 0
|| exportAttribute.Languages.Contains(language);
}
protected override bool TryGetExtensionsFromReference(AnalyzerReference reference, out ImmutableArray<CodeFixProvider> extensions)
{
// check whether the analyzer reference knows how to return fixers directly.
if (reference is ICodeFixProviderFactory codeFixProviderFactory)
{
extensions = codeFixProviderFactory.GetFixers();
return true;
}
extensions = default;
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal partial class CodeFixService
{
private class ProjectCodeFixProvider
: AbstractProjectExtensionProvider<CodeFixProvider, ExportCodeFixProviderAttribute>
{
public ProjectCodeFixProvider(AnalyzerReference reference)
: base(reference)
{
}
protected override bool SupportsLanguage(ExportCodeFixProviderAttribute exportAttribute, string language)
{
return exportAttribute.Languages == null
|| exportAttribute.Languages.Length == 0
|| exportAttribute.Languages.Contains(language);
}
protected override bool TryGetExtensionsFromReference(AnalyzerReference reference, out ImmutableArray<CodeFixProvider> extensions)
{
// check whether the analyzer reference knows how to return fixers directly.
if (reference is ICodeFixProviderFactory codeFixProviderFactory)
{
extensions = codeFixProviderFactory.GetFixers();
return true;
}
extensions = default;
return false;
}
}
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/EditorFeatures/Test/RenameTracking/RenameTrackingTestState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
internal sealed class RenameTrackingTestState : IDisposable
{
private readonly ITagger<RenameTrackingTag> _tagger;
public readonly TestWorkspace Workspace;
private readonly IWpfTextView _view;
private readonly ITextUndoHistoryRegistry _historyRegistry;
private string _notificationMessage = null;
private readonly TestHostDocument _hostDocument;
public TestHostDocument HostDocument { get { return _hostDocument; } }
private readonly IEditorOperations _editorOperations;
public IEditorOperations EditorOperations { get { return _editorOperations; } }
private readonly MockRefactorNotifyService _mockRefactorNotifyService;
public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } }
private readonly RenameTrackingCodeRefactoringProvider _codeRefactoringProvider;
private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler();
public static RenameTrackingTestState Create(
string markup,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
var workspace = CreateTestWorkspace(markup, languageName);
return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue);
}
public static RenameTrackingTestState CreateFromWorkspaceXml(
string workspaceXml,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
var workspace = CreateTestWorkspace(workspaceXml);
return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue);
}
public RenameTrackingTestState(
TestWorkspace workspace,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
this.Workspace = workspace;
_hostDocument = Workspace.Documents.First();
_view = _hostDocument.GetTextView();
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value));
_editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view);
_historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value;
_mockRefactorNotifyService = new MockRefactorNotifyService
{
OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue,
OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue
};
// Mock the action taken by the workspace INotificationService
var notificationService = (INotificationServiceCallback)Workspace.Services.GetRequiredService<INotificationService>();
var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message);
notificationService.NotificationCallback = callback;
var tracker = new RenameTrackingTaggerProvider(
Workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
Workspace.ExportProvider.GetExport<IInlineRenameService>().Value,
Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value,
Workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>());
_tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer());
if (languageName == LanguageNames.CSharp ||
languageName == LanguageNames.VisualBasic)
{
_codeRefactoringProvider = new RenameTrackingCodeRefactoringProvider(
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else
{
throw new ArgumentException("Invalid language name: " + languageName, nameof(languageName));
}
}
private static TestWorkspace CreateTestWorkspace(string code, string languageName)
{
return CreateTestWorkspace(string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document>{1}</Document>
</Project>
</Workspace>", languageName, code));
}
private static TestWorkspace CreateTestWorkspace(string xml)
{
return TestWorkspace.Create(xml, composition: EditorTestCompositions.EditorFeaturesWpf);
}
public void SendEscape()
=> _commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), TestCommandExecutionContext.Create());
public void MoveCaret(int delta)
{
var position = _view.Caret.Position.BufferPosition.Position;
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta));
}
public void Undo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Undo(count);
}
public void Redo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Redo(count);
}
public async Task AssertNoTag()
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
Assert.Equal(0, tags.Count());
}
/// <param name="textSpan">If <see langword="null"/> the current caret position will be used.</param>
public async Task<CodeAction> TryGetCodeActionAsync(TextSpan? textSpan = null)
{
var span = textSpan ?? new TextSpan(_view.Caret.Position.BufferPosition, 0);
var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var actions = new List<CodeAction>();
var context = new CodeRefactoringContext(
document, span, actions.Add, CancellationToken.None);
await _codeRefactoringProvider.ComputeRefactoringsAsync(context);
return actions.SingleOrDefault();
}
public async Task AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false)
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
// There should only ever be one tag
Assert.Equal(1, tags.Count());
var tag = tags.Single();
// There should only be one code action for the tag
var codeAction = await TryGetCodeActionAsync(tag.Span.Span.ToTextSpan());
Assert.NotNull(codeAction);
Assert.Equal(string.Format(EditorFeaturesResources.Rename_0_to_1, expectedFromName, expectedToName), codeAction.Title);
if (invokeAction)
{
var operations = (await codeAction.GetOperationsAsync(CancellationToken.None)).ToArray();
Assert.Equal(1, operations.Length);
operations[0].TryApply(this.Workspace, new ProgressTracker(), CancellationToken.None);
}
}
public void AssertNoNotificationMessage()
=> Assert.Null(_notificationMessage);
public void AssertNotificationMessage()
=> Assert.NotNull(_notificationMessage);
private async Task WaitForAsyncOperationsAsync()
{
var provider = Workspace.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>();
await provider.WaitAllDispatcherOperationAndTasksAsync(
Workspace,
FeatureAttribute.RenameTracking,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.Workspace,
FeatureAttribute.EventHookup);
}
public void Dispose()
=> Workspace.Dispose();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking
{
internal sealed class RenameTrackingTestState : IDisposable
{
private readonly ITagger<RenameTrackingTag> _tagger;
public readonly TestWorkspace Workspace;
private readonly IWpfTextView _view;
private readonly ITextUndoHistoryRegistry _historyRegistry;
private string _notificationMessage = null;
private readonly TestHostDocument _hostDocument;
public TestHostDocument HostDocument { get { return _hostDocument; } }
private readonly IEditorOperations _editorOperations;
public IEditorOperations EditorOperations { get { return _editorOperations; } }
private readonly MockRefactorNotifyService _mockRefactorNotifyService;
public MockRefactorNotifyService RefactorNotifyService { get { return _mockRefactorNotifyService; } }
private readonly RenameTrackingCodeRefactoringProvider _codeRefactoringProvider;
private readonly RenameTrackingCancellationCommandHandler _commandHandler = new RenameTrackingCancellationCommandHandler();
public static RenameTrackingTestState Create(
string markup,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
var workspace = CreateTestWorkspace(markup, languageName);
return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue);
}
public static RenameTrackingTestState CreateFromWorkspaceXml(
string workspaceXml,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
var workspace = CreateTestWorkspace(workspaceXml);
return new RenameTrackingTestState(workspace, languageName, onBeforeGlobalSymbolRenamedReturnValue, onAfterGlobalSymbolRenamedReturnValue);
}
public RenameTrackingTestState(
TestWorkspace workspace,
string languageName,
bool onBeforeGlobalSymbolRenamedReturnValue = true,
bool onAfterGlobalSymbolRenamedReturnValue = true)
{
this.Workspace = workspace;
_hostDocument = Workspace.Documents.First();
_view = _hostDocument.GetTextView();
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, _hostDocument.CursorPosition.Value));
_editorOperations = Workspace.GetService<IEditorOperationsFactoryService>().GetEditorOperations(_view);
_historyRegistry = Workspace.ExportProvider.GetExport<ITextUndoHistoryRegistry>().Value;
_mockRefactorNotifyService = new MockRefactorNotifyService
{
OnBeforeSymbolRenamedReturnValue = onBeforeGlobalSymbolRenamedReturnValue,
OnAfterSymbolRenamedReturnValue = onAfterGlobalSymbolRenamedReturnValue
};
// Mock the action taken by the workspace INotificationService
var notificationService = (INotificationServiceCallback)Workspace.Services.GetRequiredService<INotificationService>();
var callback = new Action<string, string, NotificationSeverity>((message, title, severity) => _notificationMessage = message);
notificationService.NotificationCallback = callback;
var tracker = new RenameTrackingTaggerProvider(
Workspace.ExportProvider.GetExportedValue<IThreadingContext>(),
Workspace.ExportProvider.GetExport<IInlineRenameService>().Value,
Workspace.ExportProvider.GetExport<IDiagnosticAnalyzerService>().Value,
Workspace.ExportProvider.GetExportedValue<IAsynchronousOperationListenerProvider>());
_tagger = tracker.CreateTagger<RenameTrackingTag>(_hostDocument.GetTextBuffer());
if (languageName == LanguageNames.CSharp ||
languageName == LanguageNames.VisualBasic)
{
_codeRefactoringProvider = new RenameTrackingCodeRefactoringProvider(
_historyRegistry,
SpecializedCollections.SingletonEnumerable(_mockRefactorNotifyService));
}
else
{
throw new ArgumentException("Invalid language name: " + languageName, nameof(languageName));
}
}
private static TestWorkspace CreateTestWorkspace(string code, string languageName)
{
return CreateTestWorkspace(string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document>{1}</Document>
</Project>
</Workspace>", languageName, code));
}
private static TestWorkspace CreateTestWorkspace(string xml)
{
return TestWorkspace.Create(xml, composition: EditorTestCompositions.EditorFeaturesWpf);
}
public void SendEscape()
=> _commandHandler.ExecuteCommand(new EscapeKeyCommandArgs(_view, _view.TextBuffer), TestCommandExecutionContext.Create());
public void MoveCaret(int delta)
{
var position = _view.Caret.Position.BufferPosition.Position;
_view.Caret.MoveTo(new SnapshotPoint(_view.TextSnapshot, position + delta));
}
public void Undo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Undo(count);
}
public void Redo(int count = 1)
{
var history = _historyRegistry.GetHistory(_view.TextBuffer);
history.Redo(count);
}
public async Task AssertNoTag()
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
Assert.Equal(0, tags.Count());
}
/// <param name="textSpan">If <see langword="null"/> the current caret position will be used.</param>
public async Task<CodeAction> TryGetCodeActionAsync(TextSpan? textSpan = null)
{
var span = textSpan ?? new TextSpan(_view.Caret.Position.BufferPosition, 0);
var document = this.Workspace.CurrentSolution.GetDocument(_hostDocument.Id);
var actions = new List<CodeAction>();
var context = new CodeRefactoringContext(
document, span, actions.Add, CancellationToken.None);
await _codeRefactoringProvider.ComputeRefactoringsAsync(context);
return actions.SingleOrDefault();
}
public async Task AssertTag(string expectedFromName, string expectedToName, bool invokeAction = false)
{
await WaitForAsyncOperationsAsync();
var tags = _tagger.GetTags(_view.TextBuffer.CurrentSnapshot.GetSnapshotSpanCollection());
// There should only ever be one tag
Assert.Equal(1, tags.Count());
var tag = tags.Single();
// There should only be one code action for the tag
var codeAction = await TryGetCodeActionAsync(tag.Span.Span.ToTextSpan());
Assert.NotNull(codeAction);
Assert.Equal(string.Format(EditorFeaturesResources.Rename_0_to_1, expectedFromName, expectedToName), codeAction.Title);
if (invokeAction)
{
var operations = (await codeAction.GetOperationsAsync(CancellationToken.None)).ToArray();
Assert.Equal(1, operations.Length);
operations[0].TryApply(this.Workspace, new ProgressTracker(), CancellationToken.None);
}
}
public void AssertNoNotificationMessage()
=> Assert.Null(_notificationMessage);
public void AssertNotificationMessage()
=> Assert.NotNull(_notificationMessage);
private async Task WaitForAsyncOperationsAsync()
{
var provider = Workspace.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>();
await provider.WaitAllDispatcherOperationAndTasksAsync(
Workspace,
FeatureAttribute.RenameTracking,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.Workspace,
FeatureAttribute.EventHookup);
}
public void Dispose()
=> Workspace.Dispose();
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Analyzers/CSharp/Tests/UseIndexOrRangeOperator/UseRangeOperatorTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Roslyn.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseRangeOperatorDiagnosticAnalyzer,
Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseRangeOperatorCodeFixProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseIndexOrRangeOperator
{
public class UseRangeOperatorTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNotInCSharp7()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring(1, s.Length - 1);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp7,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestWithMissingReference()
{
var source =
@"class {|#0:C|}
{
{|#1:void|} Goo({|#2:string|} s)
{
var v = s.Substring({|#3:1|}, s.Length - {|#4:1|});
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = new ReferenceAssemblies("custom"),
TestCode = source,
ExpectedDiagnostics =
{
// /0/Test0.cs(1,7): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithLocation(0).WithArguments("System.Object"),
// /0/Test0.cs(1,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments
DiagnosticResult.CompilerError("CS1729").WithLocation(0).WithArguments("object", "0"),
// /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Void' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithLocation(1).WithArguments("System.Void"),
// /0/Test0.cs(3,14): error CS0518: Predefined type 'System.String' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithLocation(2).WithArguments("System.String"),
// /0/Test0.cs(5,29): error CS0518: Predefined type 'System.Int32' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithLocation(3).WithArguments("System.Int32"),
// /0/Test0.cs(5,43): error CS0518: Predefined type 'System.Int32' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithLocation(4).WithArguments("System.Int32"),
},
FixedCode = source,
}.RunAsync();
}
[WorkItem(36909, "https://github.com/dotnet/roslyn/issues/36909")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNotWithoutSystemRange()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring(1, s.Length - 1);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp20,
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp7,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestSimple()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring([|1, s.Length - 1|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s)
{
var v = s[1..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)]
public async Task TestMultipleDefinitions()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring([|1, s.Length - 1|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s)
{
var v = s[1..];
}
}";
// Adding a dependency with internal definitions of Index and Range should not break the feature
var source1 = "namespace System { internal struct Index { } internal struct Range { } }";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestState =
{
Sources = { source },
AdditionalProjects =
{
["DependencyProject"] =
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20,
Sources = { source1 },
},
},
AdditionalProjectReferences = { "DependencyProject" },
},
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestComplexSubstraction()
{
var source =
@"
class C
{
void Goo(string s, int bar, int baz)
{
var v = s.Substring([|bar, s.Length - baz - bar|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, int bar, int baz)
{
var v = s[bar..^baz];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestSubstringOneArgument()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring([|1|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s)
{
var v = s[1..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestSliceOneArgument()
{
var source =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s.Slice([|1|]);
}
}";
var fixedSource =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s[1..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestExpressionOneArgument()
{
var source =
@"
class C
{
void Goo(string s, int bar)
{
var v = s.Substring([|bar|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, int bar)
{
var v = s[bar..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestConstantSubtraction1()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s)
{
var v = s[1..^1];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNotWithoutSubtraction()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring(1, 2);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp7,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNonStringType()
{
var source =
@"
struct S { public S Slice(int start, int length) => default; public int Length { get; } public S this[System.Range r] { get => default; } }
class C
{
void Goo(S s)
{
var v = s.Slice([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
struct S { public S Slice(int start, int length) => default; public int Length { get; } public S this[System.Range r] { get => default; } }
class C
{
void Goo(S s)
{
var v = s[1..^1];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNonStringTypeWithoutRangeIndexer()
{
var source =
@"
struct S { public S Slice(int start, int length) => default; public int Length { get; } }
class C
{
void Goo(S s)
{
var v = s.Slice([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
struct S { public S Slice(int start, int length) => default; public int Length { get; } }
class C
{
void Goo(S s)
{
var v = s[1..^1];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNonStringType_Assignment()
{
var source =
@"
struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public ref S this[System.Range r] { get => throw null; } }
class C
{
void Goo(S s)
{
s.Slice([|1, s.Length - 2|]) = default;
}
}";
var fixedSource =
@"
struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public ref S this[System.Range r] { get => throw null; } }
class C
{
void Goo(S s)
{
s[1..^1] = default;
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestMethodToMethod()
{
var source =
@"
struct S { public int Slice(int start, int length) => 0; public int Length { get; } public int Slice(System.Range r) => 0; }
class C
{
void Goo(S s)
{
var v = s.Slice([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
struct S { public int Slice(int start, int length) => 0; public int Length { get; } public int Slice(System.Range r) => 0; }
class C
{
void Goo(S s)
{
var v = s.Slice(1..^1);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestFixAllInvocationToElementAccess1()
{
// Note: once the IOp tree has support for range operators, this should
// simplify even further.
var source =
@"
class C
{
void Goo(string s, string t)
{
var v = t.Substring([|s.Substring([|1, s.Length - 2|])[0], t.Length - s.Substring([|1, s.Length - 2|])[0]|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, string t)
{
var v = t[s[1..^1][0]..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestFixAllInvocationToElementAccess2()
{
// Note: once the IOp tree has support for range operators, this should
// simplify even further.
var source =
@"
class C
{
void Goo(string s, string t)
{
var v = t.Substring([|s.Substring([|1|])[0]|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, string t)
{
var v = t[s[1..][0]..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestWithTypeWithActualSliceMethod1()
{
var source =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s.Slice([|1, s.Length - 1|]);
}
}";
var fixedSource =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s[1..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestWithTypeWithActualSliceMethod2()
{
var source =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s.Slice([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s[1..^1];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(43202, "https://github.com/dotnet/roslyn/issues/43202")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestWritableType()
{
var source =
@"
using System;
struct S {
public ref S Slice(int start, int length) => throw null;
public int Length { get; }
public S this[System.Range r] { get => default; }
}
class C
{
void Goo(S s)
{
s.Slice(1, s.Length - 2) = default;
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = source,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestReturnByRef()
{
var source =
@"
struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public S this[System.Range r] { get => throw null; } }
class C
{
void Goo(S s)
{
var x = s.Slice([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public S this[System.Range r] { get => throw null; } }
class C
{
void Goo(S s)
{
var x = s[1..^1];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(43202, "https://github.com/dotnet/roslyn/issues/43202")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestIntWritableType()
{
var source =
@"
using System;
struct S {
public ref S Slice(int start, int length) => throw null;
public int Length { get; }
public S this[int r] { get => default; }
}
class C
{
void Goo(S s)
{
s.Slice([|1, s.Length - 2|]) = default;
}
}";
var fixedSource =
@"
using System;
struct S {
public ref S Slice(int start, int length) => throw null;
public int Length { get; }
public S this[int r] { get => default; }
}
class C
{
void Goo(S s)
{
s[1..^1] = default;
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(43202, "https://github.com/dotnet/roslyn/issues/43202")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestReadWriteProperty()
{
var source =
@"
using System;
struct S {
public ref S Slice(int start, int length) => throw null;
public int Length { get; }
public S this[System.Range r] { get => default; set { } }
}
class C
{
void Goo(S s)
{
s.Slice([|1, s.Length - 2|]) = default;
}
}";
var fixedSource =
@"
using System;
struct S {
public ref S Slice(int start, int length) => throw null;
public int Length { get; }
public S this[System.Range r] { get => default; set { } }
}
class C
{
void Goo(S s)
{
s[1..^1] = default;
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestWithTypeWithActualSliceMethod3()
{
var source =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s.Slice([|1|]);
}
}";
var fixedSource =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s[1..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(36997, "https://github.com/dotnet/roslyn/issues/36997")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestExpressionWithAddOperatorArgument()
{
var source =
@"
class C
{
void Goo(string s, int bar)
{
var v = s.Substring([|bar + 1|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, int bar)
{
var v = s[(bar + 1)..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestExpressionWithElementAccessShouldNotAddParentheses()
{
var source =
@"
class C
{
void Goo(string s, int[] bar)
{
_ = s.Substring([|bar[0]|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, int[] bar)
{
_ = s[bar[0]..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(47183, "https://github.com/dotnet/roslyn/issues/47183")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestExpressionWithNullConditionalAccess()
{
var source =
@"
#nullable enable
public class Test
{
public string? M(string? arg)
=> arg?.Substring([|42|]);
}";
var fixedSource =
@"
#nullable enable
public class Test
{
public string? M(string? arg)
=> arg?[42..];
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(47183, "https://github.com/dotnet/roslyn/issues/47183")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestExpressionWithNullConditionalAccessWithPropertyAccess()
{
var source =
@"
public class Test
{
public int? M(string arg)
=> arg?.Substring([|42|]).Length;
}";
var fixedSource =
@"
public class Test
{
public int? M(string arg)
=> arg?[42..].Length;
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(47183, "https://github.com/dotnet/roslyn/issues/47183")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
[InlineData(
"c.Prop.Substring([|42|])",
"c.Prop[42..]")]
[InlineData(
"c.Prop.Substring([|1, c.Prop.Length - 2|])",
"c.Prop[1..^1]")]
[InlineData(
"c?.Prop.Substring([|42|])",
"c?.Prop[42..]")]
[InlineData(
"c.Prop?.Substring([|42|])",
"c.Prop?[42..]")]
[InlineData(
"c?.Prop?.Substring([|42|])",
"c?.Prop?[42..]")]
public async Task TestExpressionWithNullConditionalAccessVariations(string subStringCode, string rangeCode)
{
var source =
@$"
public class C
{{
public string Prop {{ get; set; }}
}}
public class Test
{{
public object M(C c)
=> { subStringCode };
}}";
var fixedSource =
@$"
public class C
{{
public string Prop {{ get; set; }}
}}
public class Test
{{
public object M(C c)
=> { rangeCode };
}}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(38055, "https://github.com/dotnet/roslyn/issues/38055")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestStringMethod()
{
var source =
@"
namespace System
{
public class Object {}
public class ValueType : Object {}
public struct Void {}
public struct Int32 {}
public struct Index
{
public int GetOffset(int length) => 0;
public static implicit operator Index(int value) => default;
}
public struct Range
{
public Range(Index start, Index end) {}
public Index Start => default;
public Index End => default;
}
public class String : Object
{
public int Length => 0;
public string Substring(int start, int length) => this;
string Foo(int x) => Substring([|1, x - 1|]);
}
}";
var fixedSource =
@"
namespace System
{
public class Object {}
public class ValueType : Object {}
public struct Void {}
public struct Int32 {}
public struct Index
{
public int GetOffset(int length) => 0;
public static implicit operator Index(int value) => default;
}
public struct Range
{
public Range(Index start, Index end) {}
public Index Start => default;
public Index End => default;
}
public class String : Object
{
public int Length => 0;
public string Substring(int start, int length) => this;
string Foo(int x) => this[1..x];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = new ReferenceAssemblies("nostdlib"),
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(38055, "https://github.com/dotnet/roslyn/issues/38055")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestSliceOnThis()
{
var source =
@"
class C
{
public int Length => 0;
public C Slice(int start, int length) => this;
public C Foo(int x) => Slice([|1, x - 1|]);
}";
var fixedSource =
@"
class C
{
public int Length => 0;
public C Slice(int start, int length) => this;
public C Foo(int x) => this[1..x];
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.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.CSharp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Roslyn.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseRangeOperatorDiagnosticAnalyzer,
Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator.CSharpUseRangeOperatorCodeFixProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseIndexOrRangeOperator
{
public class UseRangeOperatorTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNotInCSharp7()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring(1, s.Length - 1);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp7,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestWithMissingReference()
{
var source =
@"class {|#0:C|}
{
{|#1:void|} Goo({|#2:string|} s)
{
var v = s.Substring({|#3:1|}, s.Length - {|#4:1|});
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = new ReferenceAssemblies("custom"),
TestCode = source,
ExpectedDiagnostics =
{
// /0/Test0.cs(1,7): error CS0518: Predefined type 'System.Object' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithLocation(0).WithArguments("System.Object"),
// /0/Test0.cs(1,7): error CS1729: 'object' does not contain a constructor that takes 0 arguments
DiagnosticResult.CompilerError("CS1729").WithLocation(0).WithArguments("object", "0"),
// /0/Test0.cs(3,5): error CS0518: Predefined type 'System.Void' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithLocation(1).WithArguments("System.Void"),
// /0/Test0.cs(3,14): error CS0518: Predefined type 'System.String' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithLocation(2).WithArguments("System.String"),
// /0/Test0.cs(5,29): error CS0518: Predefined type 'System.Int32' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithLocation(3).WithArguments("System.Int32"),
// /0/Test0.cs(5,43): error CS0518: Predefined type 'System.Int32' is not defined or imported
DiagnosticResult.CompilerError("CS0518").WithLocation(4).WithArguments("System.Int32"),
},
FixedCode = source,
}.RunAsync();
}
[WorkItem(36909, "https://github.com/dotnet/roslyn/issues/36909")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNotWithoutSystemRange()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring(1, s.Length - 1);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp20,
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp7,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestSimple()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring([|1, s.Length - 1|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s)
{
var v = s[1..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseIndexOperator)]
public async Task TestMultipleDefinitions()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring([|1, s.Length - 1|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s)
{
var v = s[1..];
}
}";
// Adding a dependency with internal definitions of Index and Range should not break the feature
var source1 = "namespace System { internal struct Index { } internal struct Range { } }";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestState =
{
Sources = { source },
AdditionalProjects =
{
["DependencyProject"] =
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20,
Sources = { source1 },
},
},
AdditionalProjectReferences = { "DependencyProject" },
},
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestComplexSubstraction()
{
var source =
@"
class C
{
void Goo(string s, int bar, int baz)
{
var v = s.Substring([|bar, s.Length - baz - bar|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, int bar, int baz)
{
var v = s[bar..^baz];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestSubstringOneArgument()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring([|1|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s)
{
var v = s[1..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestSliceOneArgument()
{
var source =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s.Slice([|1|]);
}
}";
var fixedSource =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s[1..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestExpressionOneArgument()
{
var source =
@"
class C
{
void Goo(string s, int bar)
{
var v = s.Substring([|bar|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, int bar)
{
var v = s[bar..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestConstantSubtraction1()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s)
{
var v = s[1..^1];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNotWithoutSubtraction()
{
var source =
@"
class C
{
void Goo(string s)
{
var v = s.Substring(1, 2);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = source,
LanguageVersion = LanguageVersion.CSharp7,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNonStringType()
{
var source =
@"
struct S { public S Slice(int start, int length) => default; public int Length { get; } public S this[System.Range r] { get => default; } }
class C
{
void Goo(S s)
{
var v = s.Slice([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
struct S { public S Slice(int start, int length) => default; public int Length { get; } public S this[System.Range r] { get => default; } }
class C
{
void Goo(S s)
{
var v = s[1..^1];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNonStringTypeWithoutRangeIndexer()
{
var source =
@"
struct S { public S Slice(int start, int length) => default; public int Length { get; } }
class C
{
void Goo(S s)
{
var v = s.Slice([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
struct S { public S Slice(int start, int length) => default; public int Length { get; } }
class C
{
void Goo(S s)
{
var v = s[1..^1];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestNonStringType_Assignment()
{
var source =
@"
struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public ref S this[System.Range r] { get => throw null; } }
class C
{
void Goo(S s)
{
s.Slice([|1, s.Length - 2|]) = default;
}
}";
var fixedSource =
@"
struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public ref S this[System.Range r] { get => throw null; } }
class C
{
void Goo(S s)
{
s[1..^1] = default;
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestMethodToMethod()
{
var source =
@"
struct S { public int Slice(int start, int length) => 0; public int Length { get; } public int Slice(System.Range r) => 0; }
class C
{
void Goo(S s)
{
var v = s.Slice([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
struct S { public int Slice(int start, int length) => 0; public int Length { get; } public int Slice(System.Range r) => 0; }
class C
{
void Goo(S s)
{
var v = s.Slice(1..^1);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestFixAllInvocationToElementAccess1()
{
// Note: once the IOp tree has support for range operators, this should
// simplify even further.
var source =
@"
class C
{
void Goo(string s, string t)
{
var v = t.Substring([|s.Substring([|1, s.Length - 2|])[0], t.Length - s.Substring([|1, s.Length - 2|])[0]|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, string t)
{
var v = t[s[1..^1][0]..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestFixAllInvocationToElementAccess2()
{
// Note: once the IOp tree has support for range operators, this should
// simplify even further.
var source =
@"
class C
{
void Goo(string s, string t)
{
var v = t.Substring([|s.Substring([|1|])[0]|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, string t)
{
var v = t[s[1..][0]..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestWithTypeWithActualSliceMethod1()
{
var source =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s.Slice([|1, s.Length - 1|]);
}
}";
var fixedSource =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s[1..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestWithTypeWithActualSliceMethod2()
{
var source =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s.Slice([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s[1..^1];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(43202, "https://github.com/dotnet/roslyn/issues/43202")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestWritableType()
{
var source =
@"
using System;
struct S {
public ref S Slice(int start, int length) => throw null;
public int Length { get; }
public S this[System.Range r] { get => default; }
}
class C
{
void Goo(S s)
{
s.Slice(1, s.Length - 2) = default;
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = source,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestReturnByRef()
{
var source =
@"
struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public S this[System.Range r] { get => throw null; } }
class C
{
void Goo(S s)
{
var x = s.Slice([|1, s.Length - 2|]);
}
}";
var fixedSource =
@"
struct S { public ref S Slice(int start, int length) => throw null; public int Length { get; } public S this[System.Range r] { get => throw null; } }
class C
{
void Goo(S s)
{
var x = s[1..^1];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(43202, "https://github.com/dotnet/roslyn/issues/43202")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestIntWritableType()
{
var source =
@"
using System;
struct S {
public ref S Slice(int start, int length) => throw null;
public int Length { get; }
public S this[int r] { get => default; }
}
class C
{
void Goo(S s)
{
s.Slice([|1, s.Length - 2|]) = default;
}
}";
var fixedSource =
@"
using System;
struct S {
public ref S Slice(int start, int length) => throw null;
public int Length { get; }
public S this[int r] { get => default; }
}
class C
{
void Goo(S s)
{
s[1..^1] = default;
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(43202, "https://github.com/dotnet/roslyn/issues/43202")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestReadWriteProperty()
{
var source =
@"
using System;
struct S {
public ref S Slice(int start, int length) => throw null;
public int Length { get; }
public S this[System.Range r] { get => default; set { } }
}
class C
{
void Goo(S s)
{
s.Slice([|1, s.Length - 2|]) = default;
}
}";
var fixedSource =
@"
using System;
struct S {
public ref S Slice(int start, int length) => throw null;
public int Length { get; }
public S this[System.Range r] { get => default; set { } }
}
class C
{
void Goo(S s)
{
s[1..^1] = default;
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestWithTypeWithActualSliceMethod3()
{
var source =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s.Slice([|1|]);
}
}";
var fixedSource =
@"
using System;
class C
{
void Goo(Span<int> s)
{
var v = s[1..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(36997, "https://github.com/dotnet/roslyn/issues/36997")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestExpressionWithAddOperatorArgument()
{
var source =
@"
class C
{
void Goo(string s, int bar)
{
var v = s.Substring([|bar + 1|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, int bar)
{
var v = s[(bar + 1)..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestExpressionWithElementAccessShouldNotAddParentheses()
{
var source =
@"
class C
{
void Goo(string s, int[] bar)
{
_ = s.Substring([|bar[0]|]);
}
}";
var fixedSource =
@"
class C
{
void Goo(string s, int[] bar)
{
_ = s[bar[0]..];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(47183, "https://github.com/dotnet/roslyn/issues/47183")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestExpressionWithNullConditionalAccess()
{
var source =
@"
#nullable enable
public class Test
{
public string? M(string? arg)
=> arg?.Substring([|42|]);
}";
var fixedSource =
@"
#nullable enable
public class Test
{
public string? M(string? arg)
=> arg?[42..];
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(47183, "https://github.com/dotnet/roslyn/issues/47183")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestExpressionWithNullConditionalAccessWithPropertyAccess()
{
var source =
@"
public class Test
{
public int? M(string arg)
=> arg?.Substring([|42|]).Length;
}";
var fixedSource =
@"
public class Test
{
public int? M(string arg)
=> arg?[42..].Length;
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(47183, "https://github.com/dotnet/roslyn/issues/47183")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
[InlineData(
"c.Prop.Substring([|42|])",
"c.Prop[42..]")]
[InlineData(
"c.Prop.Substring([|1, c.Prop.Length - 2|])",
"c.Prop[1..^1]")]
[InlineData(
"c?.Prop.Substring([|42|])",
"c?.Prop[42..]")]
[InlineData(
"c.Prop?.Substring([|42|])",
"c.Prop?[42..]")]
[InlineData(
"c?.Prop?.Substring([|42|])",
"c?.Prop?[42..]")]
public async Task TestExpressionWithNullConditionalAccessVariations(string subStringCode, string rangeCode)
{
var source =
@$"
public class C
{{
public string Prop {{ get; set; }}
}}
public class Test
{{
public object M(C c)
=> { subStringCode };
}}";
var fixedSource =
@$"
public class C
{{
public string Prop {{ get; set; }}
}}
public class Test
{{
public object M(C c)
=> { rangeCode };
}}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(38055, "https://github.com/dotnet/roslyn/issues/38055")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestStringMethod()
{
var source =
@"
namespace System
{
public class Object {}
public class ValueType : Object {}
public struct Void {}
public struct Int32 {}
public struct Index
{
public int GetOffset(int length) => 0;
public static implicit operator Index(int value) => default;
}
public struct Range
{
public Range(Index start, Index end) {}
public Index Start => default;
public Index End => default;
}
public class String : Object
{
public int Length => 0;
public string Substring(int start, int length) => this;
string Foo(int x) => Substring([|1, x - 1|]);
}
}";
var fixedSource =
@"
namespace System
{
public class Object {}
public class ValueType : Object {}
public struct Void {}
public struct Int32 {}
public struct Index
{
public int GetOffset(int length) => 0;
public static implicit operator Index(int value) => default;
}
public struct Range
{
public Range(Index start, Index end) {}
public Index Start => default;
public Index End => default;
}
public class String : Object
{
public int Length => 0;
public string Substring(int start, int length) => this;
string Foo(int x) => this[1..x];
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = new ReferenceAssemblies("nostdlib"),
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
[WorkItem(38055, "https://github.com/dotnet/roslyn/issues/38055")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseRangeOperator)]
public async Task TestSliceOnThis()
{
var source =
@"
class C
{
public int Length => 0;
public C Slice(int start, int length) => this;
public C Foo(int x) => Slice([|1, x - 1|]);
}";
var fixedSource =
@"
class C
{
public int Length => 0;
public C Slice(int start, int length) => this;
public C Foo(int x) => this[1..x];
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31,
TestCode = source,
FixedCode = fixedSource,
}.RunAsync();
}
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Compilers/Core/Portable/MetadataReader/LocalSlotConstraints.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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
{
[Flags]
internal enum LocalSlotConstraints : byte
{
None = 0,
ByRef = 1,
Pinned = 2,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis
{
[Flags]
internal enum LocalSlotConstraints : byte
{
None = 0,
ByRef = 1,
Pinned = 2,
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Features/Core/Portable/PullMemberUp/MemberAnalysisResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.PullMemberUp
{
internal readonly struct MemberAnalysisResult
{
/// <summary>
/// The member needs to be pulled up.
/// </summary>
public readonly ISymbol Member;
/// <summary>
/// Indicate whether this member needs to be changed to public so it won't cause error after it is pulled up to destination.
/// </summary>
public readonly bool ChangeOriginalToPublic;
/// <summary>
/// Indicate whether this member needs to be changed to non-static so it won't cause error after it is pulled up to destination.
/// </summary>
public readonly bool ChangeOriginalToNonStatic;
/// <summary>
/// Indicate whether this member's declaration in destination needs to be made to abstract. It is only used by the dialog UI.
/// If this property is true, then pull a member up to a class will only generate a abstract declaration in the destination.
/// It will always be false if the refactoring is triggered from Quick Action.
/// </summary>
public readonly bool MakeMemberDeclarationAbstract;
/// <summary>
/// Indicate whether pulling this member up would change the destination to abstract. It will be true if:
/// 1. Pull an abstract member to a non-abstract class
/// 2. The 'Make abstract' check box of a member is checked, and the destination is a non-abstract class
/// </summary>
public readonly bool ChangeDestinationTypeToAbstract;
/// <summary>
/// Indicate whether it would cause error if we directly pull Member into destination.
/// </summary>
public bool PullMemberUpNeedsToDoExtraChanges => ChangeOriginalToPublic || ChangeOriginalToNonStatic || ChangeDestinationTypeToAbstract;
public MemberAnalysisResult(
ISymbol member,
bool changeOriginalToPublic,
bool changeOriginalToNonStatic,
bool makeMemberDeclarationAbstract,
bool changeDestinationTypeToAbstract)
{
Member = member;
ChangeOriginalToPublic = changeOriginalToPublic;
ChangeOriginalToNonStatic = changeOriginalToNonStatic;
MakeMemberDeclarationAbstract = makeMemberDeclarationAbstract;
ChangeDestinationTypeToAbstract = changeDestinationTypeToAbstract;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.PullMemberUp
{
internal readonly struct MemberAnalysisResult
{
/// <summary>
/// The member needs to be pulled up.
/// </summary>
public readonly ISymbol Member;
/// <summary>
/// Indicate whether this member needs to be changed to public so it won't cause error after it is pulled up to destination.
/// </summary>
public readonly bool ChangeOriginalToPublic;
/// <summary>
/// Indicate whether this member needs to be changed to non-static so it won't cause error after it is pulled up to destination.
/// </summary>
public readonly bool ChangeOriginalToNonStatic;
/// <summary>
/// Indicate whether this member's declaration in destination needs to be made to abstract. It is only used by the dialog UI.
/// If this property is true, then pull a member up to a class will only generate a abstract declaration in the destination.
/// It will always be false if the refactoring is triggered from Quick Action.
/// </summary>
public readonly bool MakeMemberDeclarationAbstract;
/// <summary>
/// Indicate whether pulling this member up would change the destination to abstract. It will be true if:
/// 1. Pull an abstract member to a non-abstract class
/// 2. The 'Make abstract' check box of a member is checked, and the destination is a non-abstract class
/// </summary>
public readonly bool ChangeDestinationTypeToAbstract;
/// <summary>
/// Indicate whether it would cause error if we directly pull Member into destination.
/// </summary>
public bool PullMemberUpNeedsToDoExtraChanges => ChangeOriginalToPublic || ChangeOriginalToNonStatic || ChangeDestinationTypeToAbstract;
public MemberAnalysisResult(
ISymbol member,
bool changeOriginalToPublic,
bool changeOriginalToNonStatic,
bool makeMemberDeclarationAbstract,
bool changeDestinationTypeToAbstract)
{
Member = member;
ChangeOriginalToPublic = changeOriginalToPublic;
ChangeOriginalToNonStatic = changeOriginalToNonStatic;
MakeMemberDeclarationAbstract = makeMemberDeclarationAbstract;
ChangeDestinationTypeToAbstract = changeDestinationTypeToAbstract;
}
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Workspaces/MSBuildTest/Resources/NetCoreMultiTFM_ProjectReference/Library.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
</PropertyGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
</PropertyGroup>
</Project>
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Workspaces/Remote/ServiceHub/Services/BrokeredServiceBase.ServiceConstructionArguments.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.ServiceHub.Framework;
namespace Microsoft.CodeAnalysis.Remote
{
internal abstract partial class BrokeredServiceBase
{
internal readonly struct ServiceConstructionArguments
{
public readonly IServiceProvider ServiceProvider;
public readonly IServiceBroker ServiceBroker;
public ServiceConstructionArguments(IServiceProvider serviceProvider, IServiceBroker serviceBroker)
{
ServiceProvider = serviceProvider;
ServiceBroker = serviceBroker;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.ServiceHub.Framework;
namespace Microsoft.CodeAnalysis.Remote
{
internal abstract partial class BrokeredServiceBase
{
internal readonly struct ServiceConstructionArguments
{
public readonly IServiceProvider ServiceProvider;
public readonly IServiceBroker ServiceBroker;
public ServiceConstructionArguments(IServiceProvider serviceProvider, IServiceBroker serviceBroker)
{
ServiceProvider = serviceProvider;
ServiceBroker = serviceBroker;
}
}
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/EditorFeatures/Core.Wpf/QuickInfo/ContentControlService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.QuickInfo
{
[ExportWorkspaceService(typeof(IContentControlService), layer: ServiceLayer.Editor), Shared]
internal partial class ContentControlService : IContentControlService
{
private readonly IThreadingContext _threadingContext;
private readonly ITextEditorFactoryService _textEditorFactoryService;
private readonly IContentTypeRegistryService _contentTypeRegistryService;
private readonly IProjectionBufferFactoryService _projectionBufferFactoryService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ContentControlService(
IThreadingContext threadingContext,
ITextEditorFactoryService textEditorFactoryService,
IContentTypeRegistryService contentTypeRegistryService,
IProjectionBufferFactoryService projectionBufferFactoryService,
IEditorOptionsFactoryService editorOptionsFactoryService)
{
_threadingContext = threadingContext;
_textEditorFactoryService = textEditorFactoryService;
_contentTypeRegistryService = contentTypeRegistryService;
_projectionBufferFactoryService = projectionBufferFactoryService;
_editorOptionsFactoryService = editorOptionsFactoryService;
}
public void AttachToolTipToControl(FrameworkElement element, Func<DisposableToolTip> createToolTip)
=> LazyToolTip.AttachTo(element, _threadingContext, createToolTip);
public DisposableToolTip CreateDisposableToolTip(Document document, ITextBuffer textBuffer, Span contentSpan, object backgroundResourceKey)
{
var control = CreateViewHostingControl(textBuffer, contentSpan);
// Create the actual tooltip around the region of that text buffer we want to show.
var toolTip = new ToolTip
{
Content = control,
Background = (Brush)Application.Current.Resources[backgroundResourceKey]
};
// Create a preview workspace for this text buffer and open it's corresponding
// document.
//
// our underlying preview tagger and mechanism to attach tagger to associated buffer of
// opened document will light up automatically
var workspace = new PreviewWorkspace(document.Project.Solution);
workspace.OpenDocument(document.Id, textBuffer.AsTextContainer());
return new DisposableToolTip(toolTip, workspace);
}
public DisposableToolTip CreateDisposableToolTip(ITextBuffer textBuffer, object backgroundResourceKey)
{
var control = CreateViewHostingControl(textBuffer, textBuffer.CurrentSnapshot.GetFullSpan().Span);
// Create the actual tooltip around the region of that text buffer we want to show.
var toolTip = new ToolTip
{
Content = control,
Background = (Brush)Application.Current.Resources[backgroundResourceKey]
};
// we have stand alone view that is not associated with roslyn solution
return new DisposableToolTip(toolTip, workspaceOpt: null);
}
public ViewHostingControl CreateViewHostingControl(ITextBuffer textBuffer, Span contentSpan)
{
var snapshotSpan = textBuffer.CurrentSnapshot.GetSpan(contentSpan);
var contentType = _contentTypeRegistryService.GetContentType(
IProjectionBufferFactoryServiceExtensions.RoslynPreviewContentType);
var roleSet = _textEditorFactoryService.CreateTextViewRoleSet(
TextViewRoles.PreviewRole,
PredefinedTextViewRoles.Analyzable,
PredefinedTextViewRoles.Document,
PredefinedTextViewRoles.Editable);
var contentControl = ProjectionBufferContent.Create(
_threadingContext,
ImmutableArray.Create(snapshotSpan),
_projectionBufferFactoryService,
_editorOptionsFactoryService,
_textEditorFactoryService,
contentType,
roleSet);
return contentControl;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.QuickInfo
{
[ExportWorkspaceService(typeof(IContentControlService), layer: ServiceLayer.Editor), Shared]
internal partial class ContentControlService : IContentControlService
{
private readonly IThreadingContext _threadingContext;
private readonly ITextEditorFactoryService _textEditorFactoryService;
private readonly IContentTypeRegistryService _contentTypeRegistryService;
private readonly IProjectionBufferFactoryService _projectionBufferFactoryService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ContentControlService(
IThreadingContext threadingContext,
ITextEditorFactoryService textEditorFactoryService,
IContentTypeRegistryService contentTypeRegistryService,
IProjectionBufferFactoryService projectionBufferFactoryService,
IEditorOptionsFactoryService editorOptionsFactoryService)
{
_threadingContext = threadingContext;
_textEditorFactoryService = textEditorFactoryService;
_contentTypeRegistryService = contentTypeRegistryService;
_projectionBufferFactoryService = projectionBufferFactoryService;
_editorOptionsFactoryService = editorOptionsFactoryService;
}
public void AttachToolTipToControl(FrameworkElement element, Func<DisposableToolTip> createToolTip)
=> LazyToolTip.AttachTo(element, _threadingContext, createToolTip);
public DisposableToolTip CreateDisposableToolTip(Document document, ITextBuffer textBuffer, Span contentSpan, object backgroundResourceKey)
{
var control = CreateViewHostingControl(textBuffer, contentSpan);
// Create the actual tooltip around the region of that text buffer we want to show.
var toolTip = new ToolTip
{
Content = control,
Background = (Brush)Application.Current.Resources[backgroundResourceKey]
};
// Create a preview workspace for this text buffer and open it's corresponding
// document.
//
// our underlying preview tagger and mechanism to attach tagger to associated buffer of
// opened document will light up automatically
var workspace = new PreviewWorkspace(document.Project.Solution);
workspace.OpenDocument(document.Id, textBuffer.AsTextContainer());
return new DisposableToolTip(toolTip, workspace);
}
public DisposableToolTip CreateDisposableToolTip(ITextBuffer textBuffer, object backgroundResourceKey)
{
var control = CreateViewHostingControl(textBuffer, textBuffer.CurrentSnapshot.GetFullSpan().Span);
// Create the actual tooltip around the region of that text buffer we want to show.
var toolTip = new ToolTip
{
Content = control,
Background = (Brush)Application.Current.Resources[backgroundResourceKey]
};
// we have stand alone view that is not associated with roslyn solution
return new DisposableToolTip(toolTip, workspaceOpt: null);
}
public ViewHostingControl CreateViewHostingControl(ITextBuffer textBuffer, Span contentSpan)
{
var snapshotSpan = textBuffer.CurrentSnapshot.GetSpan(contentSpan);
var contentType = _contentTypeRegistryService.GetContentType(
IProjectionBufferFactoryServiceExtensions.RoslynPreviewContentType);
var roleSet = _textEditorFactoryService.CreateTextViewRoleSet(
TextViewRoles.PreviewRole,
PredefinedTextViewRoles.Analyzable,
PredefinedTextViewRoles.Document,
PredefinedTextViewRoles.Editable);
var contentControl = ProjectionBufferContent.Create(
_threadingContext,
ImmutableArray.Create(snapshotSpan),
_projectionBufferFactoryService,
_editorOptionsFactoryService,
_textEditorFactoryService,
contentType,
roleSet);
return contentControl;
}
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/VisualStudio/VisualStudioDiagnosticsToolWindow/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>
<trans-unit id="110">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn-Diagnose</target>
<note />
</trans-unit>
<trans-unit id="112">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn-Diagnose</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../VSPackage.resx">
<body>
<trans-unit id="110">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn-Diagnose</target>
<note />
</trans-unit>
<trans-unit id="112">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn-Diagnose</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/GotoKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class GotoKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public GotoKeywordRecommender()
: base(SyntaxKind.GotoKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsStatementContext ||
context.IsGlobalStatementContext;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class GotoKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public GotoKeywordRecommender()
: base(SyntaxKind.GotoKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsStatementContext ||
context.IsGlobalStatementContext;
}
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundNoOpStatement.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundNoOpStatement
Public Sub New(syntax As SyntaxNode)
MyClass.New(syntax, NoOpStatementFlavor.Default)
End Sub
Public Sub New(syntax As SyntaxNode, hasErrors As Boolean)
MyClass.New(syntax, NoOpStatementFlavor.Default, hasErrors)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundNoOpStatement
Public Sub New(syntax As SyntaxNode)
MyClass.New(syntax, NoOpStatementFlavor.Default)
End Sub
Public Sub New(syntax As SyntaxNode, hasErrors As Boolean)
MyClass.New(syntax, NoOpStatementFlavor.Default, hasErrors)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Compilers/CSharp/Portable/Emitter/Model/NamespaceSymbolAdapter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class
#if DEBUG
NamespaceSymbolAdapter : SymbolAdapter,
#else
NamespaceSymbol :
#endif
Cci.INamespace
{
Cci.INamespace Cci.INamespace.ContainingNamespace => AdaptedNamespaceSymbol.ContainingNamespace?.GetCciAdapter();
string Cci.INamedEntity.Name => AdaptedNamespaceSymbol.MetadataName;
CodeAnalysis.Symbols.INamespaceSymbolInternal Cci.INamespace.GetInternalSymbol() => AdaptedNamespaceSymbol;
}
internal partial class NamespaceSymbol
{
#if DEBUG
private NamespaceSymbolAdapter _lazyAdapter;
protected sealed override SymbolAdapter GetCciAdapterImpl() => GetCciAdapter();
internal new NamespaceSymbolAdapter GetCciAdapter()
{
if (_lazyAdapter is null)
{
return InterlockedOperations.Initialize(ref _lazyAdapter, new NamespaceSymbolAdapter(this));
}
return _lazyAdapter;
}
#else
internal NamespaceSymbol AdaptedNamespaceSymbol => this;
internal new NamespaceSymbol GetCciAdapter()
{
return this;
}
#endif
}
#if DEBUG
internal partial class NamespaceSymbolAdapter
{
internal NamespaceSymbolAdapter(NamespaceSymbol underlyingNamespaceSymbol)
{
AdaptedNamespaceSymbol = underlyingNamespaceSymbol;
}
internal sealed override Symbol AdaptedSymbol => AdaptedNamespaceSymbol;
internal NamespaceSymbol AdaptedNamespaceSymbol { get; }
}
#endif
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class
#if DEBUG
NamespaceSymbolAdapter : SymbolAdapter,
#else
NamespaceSymbol :
#endif
Cci.INamespace
{
Cci.INamespace Cci.INamespace.ContainingNamespace => AdaptedNamespaceSymbol.ContainingNamespace?.GetCciAdapter();
string Cci.INamedEntity.Name => AdaptedNamespaceSymbol.MetadataName;
CodeAnalysis.Symbols.INamespaceSymbolInternal Cci.INamespace.GetInternalSymbol() => AdaptedNamespaceSymbol;
}
internal partial class NamespaceSymbol
{
#if DEBUG
private NamespaceSymbolAdapter _lazyAdapter;
protected sealed override SymbolAdapter GetCciAdapterImpl() => GetCciAdapter();
internal new NamespaceSymbolAdapter GetCciAdapter()
{
if (_lazyAdapter is null)
{
return InterlockedOperations.Initialize(ref _lazyAdapter, new NamespaceSymbolAdapter(this));
}
return _lazyAdapter;
}
#else
internal NamespaceSymbol AdaptedNamespaceSymbol => this;
internal new NamespaceSymbol GetCciAdapter()
{
return this;
}
#endif
}
#if DEBUG
internal partial class NamespaceSymbolAdapter
{
internal NamespaceSymbolAdapter(NamespaceSymbol underlyingNamespaceSymbol)
{
AdaptedNamespaceSymbol = underlyingNamespaceSymbol;
}
internal sealed override Symbol AdaptedSymbol => AdaptedNamespaceSymbol;
internal NamespaceSymbol AdaptedNamespaceSymbol { get; }
}
#endif
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Compilers/CSharp/Portable/Symbols/SubstitutedParameterSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SubstitutedParameterSymbol : WrappedParameterSymbol
{
// initially set to map which is only used to get the type, which is once computed is stored here.
private object _mapOrType;
private readonly Symbol _containingSymbol;
internal SubstitutedParameterSymbol(MethodSymbol containingSymbol, TypeMap map, ParameterSymbol originalParameter) :
this((Symbol)containingSymbol, map, originalParameter)
{
}
internal SubstitutedParameterSymbol(PropertySymbol containingSymbol, TypeMap map, ParameterSymbol originalParameter) :
this((Symbol)containingSymbol, map, originalParameter)
{
}
private SubstitutedParameterSymbol(Symbol containingSymbol, TypeMap map, ParameterSymbol originalParameter) :
base(originalParameter)
{
Debug.Assert(originalParameter.IsDefinition);
_containingSymbol = containingSymbol;
_mapOrType = map;
}
public override ParameterSymbol OriginalDefinition
{
get { return _underlyingParameter.OriginalDefinition; }
}
public override Symbol ContainingSymbol
{
get { return _containingSymbol; }
}
public override TypeWithAnnotations TypeWithAnnotations
{
get
{
var mapOrType = _mapOrType;
if (mapOrType is TypeWithAnnotations type)
{
return type;
}
TypeWithAnnotations substituted = ((TypeMap)mapOrType).SubstituteType(this._underlyingParameter.TypeWithAnnotations);
if (substituted.CustomModifiers.IsEmpty &&
this._underlyingParameter.TypeWithAnnotations.CustomModifiers.IsEmpty &&
this._underlyingParameter.RefCustomModifiers.IsEmpty)
{
_mapOrType = substituted;
}
return substituted;
}
}
internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => _underlyingParameter.InterpolatedStringHandlerArgumentIndexes;
internal override bool HasInterpolatedStringHandlerArgumentError => _underlyingParameter.HasInterpolatedStringHandlerArgumentError;
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get
{
var map = _mapOrType as TypeMap;
return map != null ? map.SubstituteCustomModifiers(this._underlyingParameter.RefCustomModifiers) : this._underlyingParameter.RefCustomModifiers;
}
}
internal override bool IsCallerLineNumber
{
get { return _underlyingParameter.IsCallerLineNumber; }
}
internal override bool IsCallerFilePath
{
get { return _underlyingParameter.IsCallerFilePath; }
}
internal override bool IsCallerMemberName
{
get { return _underlyingParameter.IsCallerMemberName; }
}
internal override int CallerArgumentExpressionParameterIndex
{
get { return _underlyingParameter.CallerArgumentExpressionParameterIndex; }
}
public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if ((object)this == obj)
{
return true;
}
// Equality of ordinal and containing symbol is a correct
// implementation for all ParameterSymbols, but we don't
// define it on the base type because most can simply use
// ReferenceEquals.
var other = obj as SubstitutedParameterSymbol;
return (object)other != null &&
this.Ordinal == other.Ordinal &&
this.ContainingSymbol.Equals(other.ContainingSymbol, compareKind);
}
public sealed override int GetHashCode()
{
return Roslyn.Utilities.Hash.Combine(ContainingSymbol, _underlyingParameter.Ordinal);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SubstitutedParameterSymbol : WrappedParameterSymbol
{
// initially set to map which is only used to get the type, which is once computed is stored here.
private object _mapOrType;
private readonly Symbol _containingSymbol;
internal SubstitutedParameterSymbol(MethodSymbol containingSymbol, TypeMap map, ParameterSymbol originalParameter) :
this((Symbol)containingSymbol, map, originalParameter)
{
}
internal SubstitutedParameterSymbol(PropertySymbol containingSymbol, TypeMap map, ParameterSymbol originalParameter) :
this((Symbol)containingSymbol, map, originalParameter)
{
}
private SubstitutedParameterSymbol(Symbol containingSymbol, TypeMap map, ParameterSymbol originalParameter) :
base(originalParameter)
{
Debug.Assert(originalParameter.IsDefinition);
_containingSymbol = containingSymbol;
_mapOrType = map;
}
public override ParameterSymbol OriginalDefinition
{
get { return _underlyingParameter.OriginalDefinition; }
}
public override Symbol ContainingSymbol
{
get { return _containingSymbol; }
}
public override TypeWithAnnotations TypeWithAnnotations
{
get
{
var mapOrType = _mapOrType;
if (mapOrType is TypeWithAnnotations type)
{
return type;
}
TypeWithAnnotations substituted = ((TypeMap)mapOrType).SubstituteType(this._underlyingParameter.TypeWithAnnotations);
if (substituted.CustomModifiers.IsEmpty &&
this._underlyingParameter.TypeWithAnnotations.CustomModifiers.IsEmpty &&
this._underlyingParameter.RefCustomModifiers.IsEmpty)
{
_mapOrType = substituted;
}
return substituted;
}
}
internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => _underlyingParameter.InterpolatedStringHandlerArgumentIndexes;
internal override bool HasInterpolatedStringHandlerArgumentError => _underlyingParameter.HasInterpolatedStringHandlerArgumentError;
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get
{
var map = _mapOrType as TypeMap;
return map != null ? map.SubstituteCustomModifiers(this._underlyingParameter.RefCustomModifiers) : this._underlyingParameter.RefCustomModifiers;
}
}
internal override bool IsCallerLineNumber
{
get { return _underlyingParameter.IsCallerLineNumber; }
}
internal override bool IsCallerFilePath
{
get { return _underlyingParameter.IsCallerFilePath; }
}
internal override bool IsCallerMemberName
{
get { return _underlyingParameter.IsCallerMemberName; }
}
internal override int CallerArgumentExpressionParameterIndex
{
get { return _underlyingParameter.CallerArgumentExpressionParameterIndex; }
}
public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if ((object)this == obj)
{
return true;
}
// Equality of ordinal and containing symbol is a correct
// implementation for all ParameterSymbols, but we don't
// define it on the base type because most can simply use
// ReferenceEquals.
var other = obj as SubstitutedParameterSymbol;
return (object)other != null &&
this.Ordinal == other.Ordinal &&
this.ContainingSymbol.Equals(other.ContainingSymbol, compareKind);
}
public sealed override int GetHashCode()
{
return Roslyn.Utilities.Hash.Combine(ContainingSymbol, _underlyingParameter.Ordinal);
}
}
}
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateEndConstruct/GenerateEndConstructTests.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.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEndConstruct
Imports Microsoft.CodeAnalysis.Diagnostics
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateEndConstruct
Public Class GenerateEndConstructTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New GenerateEndConstructCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestIf() As Task
Dim text = <MethodBody>
If True Then[||]
</MethodBody>
Dim expected = <MethodBody>
If True Then
End If</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestUsing() As Task
Dim text = <MethodBody>
Using (goo)[||]
</MethodBody>
Dim expected = <MethodBody>
Using (goo)
End Using</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestStructure() As Task
Dim text = <File>
Structure Goo[||]</File>
Dim expected = StringFromLines("", "Structure Goo", "End Structure", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestModule() As Task
Dim text = <File>
Module Goo[||]
</File>
Dim expected = StringFromLines("", "Module Goo", "", "End Module", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestNamespace() As Task
Dim text = <File>
Namespace Goo[||]
</File>
Dim expected = StringFromLines("", "Namespace Goo", "", "End Namespace", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestClass() As Task
Dim text = <File>
Class Goo[||]
</File>
Dim expected = StringFromLines("", "Class Goo", "", "End Class", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestInterface() As Task
Dim text = <File>
Interface Goo[||]
</File>
Dim expected = StringFromLines("", "Interface Goo", "", "End Interface", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestEnum() As Task
Dim text = <File>
Enum Goo[||]
</File>
Dim expected = StringFromLines("", "Enum Goo", "", "End Enum", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestWhile() As Task
Dim text = <MethodBody>
While True[||]</MethodBody>
Dim expected = <MethodBody>
While True
End While</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestWith() As Task
Dim text = <MethodBody>
With True[||]</MethodBody>
Dim expected = <MethodBody>
With True
End With</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestSyncLock() As Task
Dim text = <MethodBody>
SyncLock Me[||]</MethodBody>
Dim expected = <MethodBody>
SyncLock Me
End SyncLock</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestDoLoop() As Task
Dim text = <MethodBody>
Do While True[||]</MethodBody>
Dim expected = <MethodBody>
Do While True
Loop</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestForNext() As Task
Dim text = <MethodBody>
For x = 1 to 3[||]</MethodBody>
Dim expected = <MethodBody>
For x = 1 to 3
Next</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestForEachNext() As Task
Dim text = <MethodBody>
For Each x in {}[||]</MethodBody>
Dim expected = <MethodBody>
For Each x in {}
Next</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestEndTry() As Task
Dim text = <MethodBody>
Try[||]</MethodBody>
Dim expected = <MethodBody>
Try
End Try</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestEndTryCatch() As Task
Dim text = <MethodBody>
Try[||]
Catch</MethodBody>
Dim expected = <MethodBody>
Try
Catch
End Try</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestEndTryCatchFinally() As Task
Dim text = <MethodBody>
Try[||]
Catch
Finally</MethodBody>
Dim expected = <MethodBody>
Try
Catch
Finally
End Try</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestProperty() As Task
Dim text = <File>
Class C
Property P As Integer[||]
Get
End Class</File>
Dim expected = <File>
Class C
Property P As Integer
Get
End Get
Set(value As Integer)
End Set
End Property
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestReadOnlyProperty() As Task
Dim text = <File>
Class C
ReadOnly Property P As Integer[||]
Get
End Class</File>
Dim expected = <File>
Class C
ReadOnly Property P As Integer
Get
End Get
End Property
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestWriteOnlyProperty() As Task
Dim text = <File>
Class C
WriteOnly Property P As Integer[||]
Set
End Class</File>
Dim expected = <File>
Class C
WriteOnly Property P As Integer
Set
End Set
End Property
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestWriteOnlyPropertyFromSet() As Task
Dim text = <File>
Class C
WriteOnly Property P As Integer
Set[||]
End Class</File>
Dim expected = <File>
Class C
WriteOnly Property P As Integer
Set
End Set
End Property
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestInvInsideEndsEnum() As Task
Dim text = <File>
Public Enum e[||]
e1
Class Goo
End Class</File>
Dim expected = <File>
Public Enum e
e1
End Enum
Class Goo
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestMissingEndSub() As Task
Dim text = <File>
Class C
Sub Bar()[||]
End Class</File>
Dim expected = <File>
Class C
Sub Bar()
End Sub
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestMissingEndFunction() As Task
Dim text = <File>
Class C
Function Bar() as Integer[||]
End Class</File>
Dim expected = <File>
Class C
Function Bar() as Integer
End Function
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(576176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestFormatWrappedBlock() As Task
Dim text = <File>
Class C
Sub Main(args As String())
While True[||]
Dim x = 1
Dim y = 2
Dim z = 3
End Sub
End Class</File>
Dim expected = <File>
Class C
Sub Main(args As String())
While True
End While
Dim x = 1
Dim y = 2
Dim z = 3
End Sub
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(578253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578253")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestDoNotWrapCLass() As Task
Dim text = <File>
Class C[||]
Function f1() As Integer
Return 1
End Function
Module Program
Sub Main(args As String())
End Sub
End Module</File>
Dim expected = <File>
Class C
End Class
Function f1() As Integer
Return 1
End Function
Module Program
Sub Main(args As String())
End Sub
End Module</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(578260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578260")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestNotOnLambda() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
End Sub
Function goo()
Dim op = Sub[||](c)
Dim kl = Sub(g)
End Sub
End Function
End Module")
End Function
<WorkItem(578271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578271")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestNamespaceThatEndsAtFile() As Task
Dim text = <File>
Namespace N[||]
Interface I
Module Program
Sub Main(args As String())
End Sub
End Module
End Interface</File>
Dim expected = <File>
Namespace N
End Namespace
Interface I
Module Program
Sub Main(args As String())
End Sub
End Module
End Interface</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
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.CodeFixes
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateEndConstruct
Imports Microsoft.CodeAnalysis.Diagnostics
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateEndConstruct
Public Class GenerateEndConstructTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing, New GenerateEndConstructCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestIf() As Task
Dim text = <MethodBody>
If True Then[||]
</MethodBody>
Dim expected = <MethodBody>
If True Then
End If</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestUsing() As Task
Dim text = <MethodBody>
Using (goo)[||]
</MethodBody>
Dim expected = <MethodBody>
Using (goo)
End Using</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestStructure() As Task
Dim text = <File>
Structure Goo[||]</File>
Dim expected = StringFromLines("", "Structure Goo", "End Structure", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestModule() As Task
Dim text = <File>
Module Goo[||]
</File>
Dim expected = StringFromLines("", "Module Goo", "", "End Module", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestNamespace() As Task
Dim text = <File>
Namespace Goo[||]
</File>
Dim expected = StringFromLines("", "Namespace Goo", "", "End Namespace", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestClass() As Task
Dim text = <File>
Class Goo[||]
</File>
Dim expected = StringFromLines("", "Class Goo", "", "End Class", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestInterface() As Task
Dim text = <File>
Interface Goo[||]
</File>
Dim expected = StringFromLines("", "Interface Goo", "", "End Interface", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestEnum() As Task
Dim text = <File>
Enum Goo[||]
</File>
Dim expected = StringFromLines("", "Enum Goo", "", "End Enum", "")
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestWhile() As Task
Dim text = <MethodBody>
While True[||]</MethodBody>
Dim expected = <MethodBody>
While True
End While</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestWith() As Task
Dim text = <MethodBody>
With True[||]</MethodBody>
Dim expected = <MethodBody>
With True
End With</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestSyncLock() As Task
Dim text = <MethodBody>
SyncLock Me[||]</MethodBody>
Dim expected = <MethodBody>
SyncLock Me
End SyncLock</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestDoLoop() As Task
Dim text = <MethodBody>
Do While True[||]</MethodBody>
Dim expected = <MethodBody>
Do While True
Loop</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestForNext() As Task
Dim text = <MethodBody>
For x = 1 to 3[||]</MethodBody>
Dim expected = <MethodBody>
For x = 1 to 3
Next</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestForEachNext() As Task
Dim text = <MethodBody>
For Each x in {}[||]</MethodBody>
Dim expected = <MethodBody>
For Each x in {}
Next</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestEndTry() As Task
Dim text = <MethodBody>
Try[||]</MethodBody>
Dim expected = <MethodBody>
Try
End Try</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestEndTryCatch() As Task
Dim text = <MethodBody>
Try[||]
Catch</MethodBody>
Dim expected = <MethodBody>
Try
Catch
End Try</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestEndTryCatchFinally() As Task
Dim text = <MethodBody>
Try[||]
Catch
Finally</MethodBody>
Dim expected = <MethodBody>
Try
Catch
Finally
End Try</MethodBody>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestProperty() As Task
Dim text = <File>
Class C
Property P As Integer[||]
Get
End Class</File>
Dim expected = <File>
Class C
Property P As Integer
Get
End Get
Set(value As Integer)
End Set
End Property
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestReadOnlyProperty() As Task
Dim text = <File>
Class C
ReadOnly Property P As Integer[||]
Get
End Class</File>
Dim expected = <File>
Class C
ReadOnly Property P As Integer
Get
End Get
End Property
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestWriteOnlyProperty() As Task
Dim text = <File>
Class C
WriteOnly Property P As Integer[||]
Set
End Class</File>
Dim expected = <File>
Class C
WriteOnly Property P As Integer
Set
End Set
End Property
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestWriteOnlyPropertyFromSet() As Task
Dim text = <File>
Class C
WriteOnly Property P As Integer
Set[||]
End Class</File>
Dim expected = <File>
Class C
WriteOnly Property P As Integer
Set
End Set
End Property
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestInvInsideEndsEnum() As Task
Dim text = <File>
Public Enum e[||]
e1
Class Goo
End Class</File>
Dim expected = <File>
Public Enum e
e1
End Enum
Class Goo
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestMissingEndSub() As Task
Dim text = <File>
Class C
Sub Bar()[||]
End Class</File>
Dim expected = <File>
Class C
Sub Bar()
End Sub
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestMissingEndFunction() As Task
Dim text = <File>
Class C
Function Bar() as Integer[||]
End Class</File>
Dim expected = <File>
Class C
Function Bar() as Integer
End Function
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(576176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576176")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestFormatWrappedBlock() As Task
Dim text = <File>
Class C
Sub Main(args As String())
While True[||]
Dim x = 1
Dim y = 2
Dim z = 3
End Sub
End Class</File>
Dim expected = <File>
Class C
Sub Main(args As String())
While True
End While
Dim x = 1
Dim y = 2
Dim z = 3
End Sub
End Class</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(578253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578253")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestDoNotWrapCLass() As Task
Dim text = <File>
Class C[||]
Function f1() As Integer
Return 1
End Function
Module Program
Sub Main(args As String())
End Sub
End Module</File>
Dim expected = <File>
Class C
End Class
Function f1() As Integer
Return 1
End Function
Module Program
Sub Main(args As String())
End Sub
End Module</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
<WorkItem(578260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578260")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestNotOnLambda() As Task
Await TestMissingInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
End Sub
Function goo()
Dim op = Sub[||](c)
Dim kl = Sub(g)
End Sub
End Function
End Module")
End Function
<WorkItem(578271, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578271")>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateEndConstruct)>
Public Async Function TestNamespaceThatEndsAtFile() As Task
Dim text = <File>
Namespace N[||]
Interface I
Module Program
Sub Main(args As String())
End Sub
End Module
End Interface</File>
Dim expected = <File>
Namespace N
End Namespace
Interface I
Module Program
Sub Main(args As String())
End Sub
End Module
End Interface</File>
Await TestInRegularAndScriptAsync(text.ConvertTestSourceTag(), expected.ConvertTestSourceTag())
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,873 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures | Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | cston | 2021-08-24T23:46:09Z | 2021-08-27T22:54:45Z | a7ec315972df7b075b0d5b0c6206ee30a9ffb701 | 6aa4ddbe1b4423a70ff538f2b4bcdf2000bb5bf4 | Ensure synthesized attribute definitions are emitted for lambda and local function signatures. Ensure synthesized attribute type definitions are emitted for nested functions, even in cases where there are no uses of the attributes in the public API for the compilation.
See #55254. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/OperatorKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class OperatorKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public OperatorKeywordRecommender()
: base(SyntaxKind.OperatorKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
// cases:
// public static implicit |
// public static explicit |
var token = context.TargetToken;
return
token.Kind() == SyntaxKind.ImplicitKeyword ||
token.Kind() == SyntaxKind.ExplicitKeyword;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class OperatorKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public OperatorKeywordRecommender()
: base(SyntaxKind.OperatorKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
// cases:
// public static implicit |
// public static explicit |
var token = context.TargetToken;
return
token.Kind() == SyntaxKind.ImplicitKeyword ||
token.Kind() == SyntaxKind.ExplicitKeyword;
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Portable/SourceGeneration/CSharpGeneratorDriver.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Linq;
using System.ComponentModel;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A <see cref="GeneratorDriver"/> implementation for the CSharp language.
/// </summary>
public sealed class CSharpGeneratorDriver : GeneratorDriver
{
/// <summary>
/// Creates a new instance of <see cref="CSharpGeneratorDriver"/>
/// </summary>
/// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files.</param>
/// <param name="generators">The generators that will run as part of this driver.</param>
/// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver.</param>
/// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver.</param>
internal CSharpGeneratorDriver(CSharpParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions)
: base(parseOptions, generators, optionsProvider, additionalTexts, enableIncremental: parseOptions.LanguageVersion == LanguageVersion.Preview, driverOptions)
{
}
private CSharpGeneratorDriver(GeneratorDriverState state)
: base(state)
{
}
/// <summary>
/// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and default options
/// </summary>
/// <param name="generators">The generators to create this driver with</param>
/// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns>
public static CSharpGeneratorDriver Create(params ISourceGenerator[] generators)
=> Create(generators, additionalTexts: null);
/// <summary>
/// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="IIncrementalGenerator"/>s and default options
/// </summary>
/// <param name="incrementalGenerators">The incremental generators to create this driver with</param>
/// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns>
public static CSharpGeneratorDriver Create(params IIncrementalGenerator[] incrementalGenerators)
=> Create(incrementalGenerators.Select(GeneratorExtensions.AsSourceGenerator), additionalTexts: null);
/// <summary>
/// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and the provided options or default.
/// </summary>
/// <param name="generators">The generators to create this driver with</param>
/// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver, or <c>null</c> if there are none.</param>
/// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files, or <c>null</c> to use <see cref="CSharpParseOptions.Default"/></param>
/// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver, or <c>null</c> if there are none.</param>
/// <param name="driverOptions">A <see cref="GeneratorDriverOptions"/> that controls the behavior of the created driver.</param>
/// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns>
public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts = null, CSharpParseOptions? parseOptions = null, AnalyzerConfigOptionsProvider? optionsProvider = null, GeneratorDriverOptions driverOptions = default)
=> new CSharpGeneratorDriver(parseOptions ?? CSharpParseOptions.Default, generators.ToImmutableArray(), optionsProvider ?? CompilerAnalyzerConfigOptionsProvider.Empty, additionalTexts.AsImmutableOrEmpty(), driverOptions);
// 3.11 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts, CSharpParseOptions? parseOptions, AnalyzerConfigOptionsProvider? optionsProvider)
=> Create(generators, additionalTexts, parseOptions, optionsProvider, driverOptions: default);
internal override SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken)
=> CSharpSyntaxTree.ParseTextLazy(input.Text, (CSharpParseOptions)_state.ParseOptions, fileName);
internal override GeneratorDriver FromState(GeneratorDriverState state) => new CSharpGeneratorDriver(state);
internal override CommonMessageProvider MessageProvider => CSharp.MessageProvider.Instance;
internal override AdditionalSourcesCollection CreateSourcesCollection() => new AdditionalSourcesCollection(".cs");
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Linq;
using System.ComponentModel;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A <see cref="GeneratorDriver"/> implementation for the CSharp language.
/// </summary>
public sealed class CSharpGeneratorDriver : GeneratorDriver
{
/// <summary>
/// Creates a new instance of <see cref="CSharpGeneratorDriver"/>
/// </summary>
/// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files.</param>
/// <param name="generators">The generators that will run as part of this driver.</param>
/// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver.</param>
/// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver.</param>
internal CSharpGeneratorDriver(CSharpParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions)
: base(parseOptions, generators, optionsProvider, additionalTexts, driverOptions)
{
}
private CSharpGeneratorDriver(GeneratorDriverState state)
: base(state)
{
}
/// <summary>
/// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and default options
/// </summary>
/// <param name="generators">The generators to create this driver with</param>
/// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns>
public static CSharpGeneratorDriver Create(params ISourceGenerator[] generators)
=> Create(generators, additionalTexts: null);
/// <summary>
/// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="IIncrementalGenerator"/>s and default options
/// </summary>
/// <param name="incrementalGenerators">The incremental generators to create this driver with</param>
/// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns>
public static CSharpGeneratorDriver Create(params IIncrementalGenerator[] incrementalGenerators)
=> Create(incrementalGenerators.Select(GeneratorExtensions.AsSourceGenerator), additionalTexts: null);
/// <summary>
/// Creates a new instance of <see cref="CSharpGeneratorDriver"/> with the specified <see cref="ISourceGenerator"/>s and the provided options or default.
/// </summary>
/// <param name="generators">The generators to create this driver with</param>
/// <param name="additionalTexts">A list of <see cref="AdditionalText"/>s available to generators in this driver, or <c>null</c> if there are none.</param>
/// <param name="parseOptions">The <see cref="CSharpParseOptions"/> that should be used when parsing generated files, or <c>null</c> to use <see cref="CSharpParseOptions.Default"/></param>
/// <param name="optionsProvider">An <see cref="AnalyzerConfigOptionsProvider"/> that can be used to retrieve analyzer config values by the generators in this driver, or <c>null</c> if there are none.</param>
/// <param name="driverOptions">A <see cref="GeneratorDriverOptions"/> that controls the behavior of the created driver.</param>
/// <returns>A new <see cref="CSharpGeneratorDriver"/> instance.</returns>
public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts = null, CSharpParseOptions? parseOptions = null, AnalyzerConfigOptionsProvider? optionsProvider = null, GeneratorDriverOptions driverOptions = default)
=> new CSharpGeneratorDriver(parseOptions ?? CSharpParseOptions.Default, generators.ToImmutableArray(), optionsProvider ?? CompilerAnalyzerConfigOptionsProvider.Empty, additionalTexts.AsImmutableOrEmpty(), driverOptions);
// 3.11 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
[EditorBrowsable(EditorBrowsableState.Never)]
public static CSharpGeneratorDriver Create(IEnumerable<ISourceGenerator> generators, IEnumerable<AdditionalText>? additionalTexts, CSharpParseOptions? parseOptions, AnalyzerConfigOptionsProvider? optionsProvider)
=> Create(generators, additionalTexts, parseOptions, optionsProvider, driverOptions: default);
internal override SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken)
=> CSharpSyntaxTree.ParseTextLazy(input.Text, (CSharpParseOptions)_state.ParseOptions, fileName);
internal override GeneratorDriver FromState(GeneratorDriverState state) => new CSharpGeneratorDriver(state);
internal override CommonMessageProvider MessageProvider => CSharp.MessageProvider.Instance;
internal override AdditionalSourcesCollection CreateSourcesCollection() => new AdditionalSourcesCollection(".cs");
}
}
| 1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Test/Semantic/SourceGeneration/GeneratorDriverTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration
{
public class GeneratorDriverTests
: CSharpTestBase
{
[Fact]
public void Running_With_No_Changes_Is_NoOp()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Empty(diagnostics);
Assert.Single(outputCompilation.SyntaxTrees);
Assert.Equal(compilation, outputCompilation);
}
[Fact]
public void Generator_Is_Initialized_Before_Running()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Equal(1, initCount);
Assert.Equal(1, executeCount);
}
[Fact]
public void Generator_Is_Not_Initialized_If_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
Assert.Equal(0, initCount);
Assert.Equal(0, executeCount);
}
[Fact]
public void Generator_Is_Only_Initialized_Once()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _);
driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _);
Assert.Equal(1, initCount);
Assert.Equal(3, executeCount);
}
[Fact]
public void Single_File_Is_Added()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
Assert.NotEqual(compilation, outputCompilation);
var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single();
Assert.True(generatedClass.Locations.Single().IsInSource);
}
[Fact]
public void Analyzer_Is_Run()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
var analyzer = new Analyzer_Is_Run_Analyzer();
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(0, analyzer.GeneratedClassCount);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.GeneratedClassCount);
}
private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer
{
public int GeneratedClassCount;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(Handle, SymbolKind.NamedType);
}
private void Handle(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "GeneratedClass":
Interlocked.Increment(ref GeneratedClassCount);
break;
case "C":
case "System.Runtime.CompilerServices.IsExternalInit":
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _);
Assert.Equal(2, outputCompilation1.SyntaxTrees.Count());
Assert.Equal(2, outputCompilation2.SyntaxTrees.Count());
Assert.Equal(2, outputCompilation3.SyntaxTrees.Count());
Assert.NotEqual(compilation, outputCompilation1);
Assert.NotEqual(compilation, outputCompilation2);
Assert.NotEqual(compilation, outputCompilation3);
}
[Fact]
public void User_Source_Can_Depend_On_Generated_Source()
{
var source = @"
#pragma warning disable CS0649
class C
{
public D d;
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
}
[Fact]
public void Error_During_Initialization_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("init error");
var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Initialization_Generator_Does_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("init error");
var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
Assert.Single(outputCompilation.SyntaxTrees);
}
[Fact]
public void Error_During_Generation_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_Does_Not_Affect_Other_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_With_Dependent_Source()
{
var source = @"
#pragma warning disable CS0649
class C
{
public D d;
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_Has_Exception_In_Description()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
// Since translated description strings can have punctuation that differs based on locale, simply ensure the
// exception message is contains in the diagnostic description.
Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString());
}
[Fact]
public void Generator_Can_Report_Diagnostics()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
Diagnostic("TG001").WithLocation(1, 1)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/54185: the addition happens later so the exceptions don't occur directly at add-time. we should decide if this subtle behavior change is acceptable")]
public void Generator_HintName_MustBe_Unique()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) =>
{
sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
// the assert should swallow the exception, so we'll actually successfully generate
Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)));
// also throws for <name> vs <name>.cs
Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8)));
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
}
[Fact]
public void Generator_HintName_Is_Appended_With_GeneratorName()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D {}", "source.cs");
var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
Assert.Equal(3, outputCompilation.SyntaxTrees.Count());
var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray();
Assert.Equal(new[] {
Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"),
Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs")
}, filePaths);
}
[Fact]
public void RunResults_Are_Empty_Before_Generation()
{
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular);
var results = driver.GetRunResult();
Assert.Empty(results.GeneratedTrees);
Assert.Empty(results.Diagnostics);
Assert.Empty(results.Results);
}
[Fact]
public void RunResults_Are_Available_After_Generation()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Single(results.GeneratedTrees);
Assert.Single(results.Results);
Assert.Empty(results.Diagnostics);
var result = results.Results.Single();
Assert.Null(result.Exception);
Assert.Empty(result.Diagnostics);
Assert.Single(result.GeneratedSources);
Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree);
}
[Fact]
public void RunResults_Combine_SyntaxTrees()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); });
var generator2 = new SingleFileTestGenerator("public class F{}");
var generator3 = new SingleFileTestGenerator2("public class G{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(4, results.GeneratedTrees.Length);
Assert.Equal(3, results.Results.Length);
Assert.Empty(results.Diagnostics);
var result1 = results.Results[0];
var result2 = results.Results[1];
var result3 = results.Results[2];
Assert.Null(result1.Exception);
Assert.Empty(result1.Diagnostics);
Assert.Equal(2, result1.GeneratedSources.Length);
Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree);
Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree);
Assert.Null(result2.Exception);
Assert.Empty(result2.Diagnostics);
Assert.Single(result2.GeneratedSources);
Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree);
Assert.Null(result3.Exception);
Assert.Empty(result3.Diagnostics);
Assert.Single(result3.GeneratedSources);
Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree);
}
[Fact]
public void RunResults_Combine_Diagnostics()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None);
var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None);
var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(2, results.Results.Length);
Assert.Equal(3, results.Diagnostics.Length);
Assert.Empty(results.GeneratedTrees);
var result1 = results.Results[0];
var result2 = results.Results[1];
Assert.Null(result1.Exception);
Assert.Equal(2, result1.Diagnostics.Length);
Assert.Empty(result1.GeneratedSources);
Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]);
Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]);
Assert.Null(result2.Exception);
Assert.Single(result2.Diagnostics);
Assert.Empty(result2.GeneratedSources);
Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]);
}
[Fact]
public void FullGeneration_Diagnostics_AreSame_As_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None);
var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None);
var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics);
var results = driver.GetRunResult();
Assert.Equal(3, results.Diagnostics.Length);
Assert.Equal(3, fullDiagnostics.Length);
AssertEx.Equal(results.Diagnostics, fullDiagnostics);
}
[Fact]
public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CancellationTokenSource cts = new CancellationTokenSource();
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => { cts.Cancel(); }
);
// test generator cancels the token. Check that the call to this generator doesn't make it look like it errored.
var testGenerator2 = new CallbackGenerator2(
onInit: (i) => { },
onExecute: (e) =>
{
e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8));
e.CancellationToken.ThrowIfCancellationRequested();
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions);
var oldDriver = driver;
Assert.Throws<OperationCanceledException>(() =>
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token)
);
Assert.Same(oldDriver, driver);
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")]
public void Adding_A_Source_Text_Without_Encoding_Fails_Generation()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics);
Assert.Single(outputDiagnostics);
outputDiagnostics.Verify(
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1)
);
}
[Fact]
public void ParseOptions_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
ParseOptions? passedOptions = null;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => { passedOptions = e.ParseOptions; }
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.Same(parseOptions, passedOptions);
}
[Fact]
public void AdditionalFiles_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def"));
ImmutableArray<AdditionalText> passedIn = default;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => passedIn = e.AdditionalFiles
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.Equal(2, passedIn.Length);
Assert.Equal<AdditionalText>(texts, passedIn);
}
[Fact]
public void AnalyzerConfigOptions_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def")));
AnalyzerConfigOptionsProvider? passedIn = null;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => passedIn = e.AnalyzerConfigOptions
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.NotNull(passedIn);
Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1));
Assert.Equal("abc", item1);
Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2));
Assert.Equal("def", item2);
}
[Fact]
public void Generator_Can_Provide_Source_In_PostInit()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
}
[Fact]
public void PostInit_Source_Is_Available_During_Execute()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
INamedTypeSymbol? dSymbol = null;
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.NotNull(dSymbol);
}
[Fact]
public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
INamedTypeSymbol? dSymbol = null;
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.NotNull(dSymbol);
}
[Fact]
public void PostInit_Is_Only_Called_Once()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int postInitCount = 0;
int executeCount = 0;
void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
postInitCount++;
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.Equal(1, postInitCount);
Assert.Equal(3, executeCount);
}
[Fact]
public void Error_During_PostInit_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
throw new InvalidOperationException("post init error");
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Initialization_PostInit_Does_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void init(GeneratorInitializationContext context)
{
context.RegisterForPostInitialization(postInit);
throw new InvalidOperationException("init error");
}
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
Assert.True(false, "Should not execute");
}
var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1)
);
}
[Fact]
public void PostInit_SyntaxTrees_Are_Available_In_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Single(results.Results);
Assert.Empty(results.Diagnostics);
var result = results.Results[0];
Assert.Null(result.Exception);
Assert.Empty(result.Diagnostics);
Assert.Equal(2, result.GeneratedSources.Length);
}
[Fact]
public void PostInit_SyntaxTrees_Are_Combined_In_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}");
var generator2 = new SingleFileTestGenerator("public class F{}");
var generator3 = new SingleFileTestGenerator2("public class G{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(4, results.GeneratedTrees.Length);
Assert.Equal(3, results.Results.Length);
Assert.Empty(results.Diagnostics);
var result1 = results.Results[0];
var result2 = results.Results[1];
var result3 = results.Results[2];
Assert.Null(result1.Exception);
Assert.Empty(result1.Diagnostics);
Assert.Equal(2, result1.GeneratedSources.Length);
Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree);
Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree);
Assert.Null(result2.Exception);
Assert.Empty(result2.Diagnostics);
Assert.Single(result2.GeneratedSources);
Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree);
Assert.Null(result3.Exception);
Assert.Empty(result3.Diagnostics);
Assert.Single(result3.GeneratedSources);
Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree);
}
[Fact]
public void SyntaxTrees_Are_Lazy()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D {}", "source.cs");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
var tree = Assert.Single(results.GeneratedTrees);
Assert.False(tree.TryGetRoot(out _));
var rootFromGetRoot = tree.GetRoot();
Assert.NotNull(rootFromGetRoot);
Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot));
Assert.Same(rootFromGetRoot, rootFromTryGetRoot);
}
[Fact]
public void Diagnostics_Respect_Suppression()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) =>
{
c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2));
c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3));
});
var options = ((CSharpCompilationOptions)compilation.Options);
// generator driver diagnostics are reported separately from the compilation
verifyDiagnosticsWithOptions(options,
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1));
// warnings can be individually suppressed
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress),
Diagnostic("GEN002").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress),
Diagnostic("GEN001").WithLocation(1, 1));
// warning level is respected
verifyDiagnosticsWithOptions(options.WithWarningLevel(0));
verifyDiagnosticsWithOptions(options.WithWarningLevel(2),
Diagnostic("GEN001").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithWarningLevel(3),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1));
// warnings can be upgraded to errors
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error),
Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true),
Diagnostic("GEN002").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true));
void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected)
{
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions);
var updatedCompilation = compilation.WithOptions(options);
driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
diagnostics.Verify(expected);
}
}
[Fact]
public void Diagnostics_Respect_Pragma_Suppression()
{
var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2);
// reported diagnostics can have a location in source
verifyDiagnosticsWithSource("//comment",
new[] { (gen001, TextSpan.FromBounds(2, 5)) },
Diagnostic("GEN001", "com").WithLocation(1, 3));
// diagnostics are suppressed via #pragma
verifyDiagnosticsWithSource(
@"#pragma warning disable
//comment",
new[] { (gen001, TextSpan.FromBounds(27, 30)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3));
// but not when they don't have a source location
verifyDiagnosticsWithSource(
@"#pragma warning disable
//comment",
new[] { (gen001, new TextSpan(0, 0)) },
Diagnostic("GEN001").WithLocation(1, 1));
// can be suppressed explicitly
verifyDiagnosticsWithSource(
@"#pragma warning disable GEN001
//comment",
new[] { (gen001, TextSpan.FromBounds(34, 37)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3));
// suppress + restore
verifyDiagnosticsWithSource(
@"#pragma warning disable GEN001
//comment
#pragma warning restore GEN001
//another",
new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3),
Diagnostic("GEN001", "ano").WithLocation(4, 3));
void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected)
{
var parseOptions = TestOptions.Regular;
source = source.Replace(Environment.NewLine, "\r\n");
Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) =>
{
foreach ((var d, var l) in reportDiagnostics)
{
if (l.IsEmpty)
{
c.ReportDiagnostic(d);
}
else
{
c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l)));
}
}
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
diagnostics.Verify(expected);
}
}
[Theory]
[InlineData(LanguageVersion.CSharp9)]
[InlineData(LanguageVersion.CSharp10)]
[InlineData(LanguageVersion.Preview)]
public void GeneratorDriver_Prefers_Incremental_Generators(LanguageVersion langVer)
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular.WithLanguageVersion(langVer);
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
int incrementalInitCount = 0;
var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++));
int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0;
var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver.RunGenerators(compilation);
// ran generator 1 always
Assert.Equal(1, initCount);
Assert.Equal(1, executeCount);
// ran the incremental generator if in preview
Assert.Equal(langVer == LanguageVersion.Preview ? 1 : 0, incrementalInitCount);
// ran the combined generator only as an IIncrementalGenerator if in preview, or as an ISourceGenerator when not
Assert.Equal(langVer == LanguageVersion.Preview ? 0 : 1, dualInitCount);
Assert.Equal(langVer == LanguageVersion.Preview ? 0 : 1, dualExecuteCount);
Assert.Equal(langVer == LanguageVersion.Preview ? 1 : 0, dualIncrementalInitCount);
}
[Theory]
[InlineData(LanguageVersion.CSharp9)]
[InlineData(LanguageVersion.CSharp10)]
[InlineData(LanguageVersion.Preview)]
public void GeneratorDriver_Initializes_Incremental_Generators(LanguageVersion langVer)
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular.WithLanguageVersion(langVer);
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int incrementalInitCount = 0;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver.RunGenerators(compilation);
// ran the incremental generator
Assert.Equal((langVer == LanguageVersion.Preview) ? 1 : 0, incrementalInitCount);
}
[Fact]
public void Incremental_Generators_Exception_During_Initialization()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e)));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", ""));
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e);
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e);
}));
var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", ""));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Equal(2, runResults.Results.Length);
Assert.Single(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { }));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Empty(diagnostics);
}
[Fact]
public void IncrementalGenerator_Can_Add_PostInit_Source()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}"))));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
Assert.Empty(diagnostics);
}
[Fact]
public void User_WrappedFunc_Throw_Exceptions()
{
Func<int, CancellationToken, int> func = (input, _) => input;
Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception");
Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; };
Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException();
var userFunc = func.WrapUserFunction();
var userThrowsFunc = throwsFunc.WrapUserFunction();
var userTimeoutFunc = timeoutFunc.WrapUserFunction();
var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction();
// user functions return same values when wrapped
var result = userFunc(10, CancellationToken.None);
var userResult = userFunc(10, CancellationToken.None);
Assert.Equal(10, result);
Assert.Equal(result, userResult);
// exceptions thrown in user code are wrapped
Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None));
Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None));
try
{
userThrowsFunc(20, CancellationToken.None);
}
catch (UserFunctionException e)
{
Assert.IsType<InvalidOperationException>(e.InnerException);
}
// cancellation is not wrapped, and is bubbled up
Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true)));
Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true)));
// unless it wasn't *our* cancellation token, in which case it still gets wrapped
Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None));
Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None));
}
[Fact]
public void IncrementalGenerator_Doesnt_Run_For_Same_Input()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath);
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); });
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
// run the same compilation through again, and confirm the output wasn't called
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_Runs_Only_For_Changed_Inputs()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var text1 = new InMemoryAdditionalText("Text1", "content1");
var text2 = new InMemoryAdditionalText("Text2", "content2");
List<Compilation> compilationsCalledFor = new List<Compilation>();
List<AdditionalText> textsCalledFor = new List<AdditionalText>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); });
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); });
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
Assert.Equal(1, textsCalledFor.Count);
Assert.Equal(text1, textsCalledFor[0]);
// clear the results, add an additional text, but keep the compilation the same
compilationsCalledFor.Clear();
textsCalledFor.Clear();
driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2));
driver = driver.RunGenerators(compilation);
Assert.Equal(0, compilationsCalledFor.Count);
Assert.Equal(1, textsCalledFor.Count);
Assert.Equal(text2, textsCalledFor[0]);
// now edit the compilation
compilationsCalledFor.Clear();
textsCalledFor.Clear();
var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(newCompilation, compilationsCalledFor[0]);
Assert.Equal(0, textsCalledFor.Count);
// re run without changing anything
compilationsCalledFor.Clear();
textsCalledFor.Clear();
driver = driver.RunGenerators(newCompilation);
Assert.Equal(0, compilationsCalledFor.Count);
Assert.Equal(0, textsCalledFor.Count);
}
[Fact]
public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0));
ctx.RegisterSourceOutput(compilationSource, (spc, c) =>
{
compilationsCalledFor.Add(c);
});
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
// now edit the compilation, run the generator, and confirm that the output was not called again this time
Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") };
List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect())
// comparer that ignores the LHS (additional texts)
.WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0));
ctx.RegisterSourceOutput(compilationSource, (spc, c) =>
{
calledFor.Add(c);
});
}));
// run the generator once, and check it was passed the compilation + additional texts
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, calledFor.Count);
Assert.Equal(compilation, calledFor[0].Item1);
Assert.Equal(texts[0], calledFor[0].Item2.Single());
// edit the additional texts, and verify that the output was *not* called again on the next run
driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray());
driver = driver.RunGenerators(compilation);
Assert.Equal(1, calledFor.Count);
// now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts
Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(2, calledFor.Count);
Assert.Equal(newCompilation, calledFor[1].Item1);
Assert.Empty(calledFor[1].Item2);
}
[Fact]
public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var source = ctx.CompilationProvider;
var source2 = ctx.CompilationProvider.Combine(source);
var source3 = ctx.CompilationProvider.Combine(source2);
var source4 = ctx.CompilationProvider.Combine(source3);
var source5 = ctx.CompilationProvider.Combine(source4);
ctx.RegisterSourceOutput(source5, (spc, c) =>
{
compilationsCalledFor.Add(c.Item1);
});
}));
// run the generator and check that we didn't multiple register the generate source node through the combine
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_PostInit_Source_Is_Cached()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}"));
ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(2, classes.Count);
Assert.Equal("C", classes[0].Identifier.ValueText);
Assert.Equal("D", classes[1].Identifier.ValueText);
// clear classes, re-run
classes.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(classes);
// modify the original tree, see that the post init is still cached
var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions));
classes.Clear();
driver = driver.RunGenerators(c2);
Assert.Single(classes);
Assert.Equal("E", classes[0].Identifier.ValueText);
}
[Fact]
public void Incremental_Generators_Can_Be_Cancelled()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CancellationTokenSource cts = new CancellationTokenSource();
bool generatorCancelled = false;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; });
var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; });
ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", ""));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token));
Assert.True(generatorCancelled);
}
[Fact]
public void ParseOptions_Can_Be_Updated()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); });
}));
// run the generator once, and check it was passed the parse options
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, parseOptionsCalledFor.Count);
Assert.Equal(parseOptions, parseOptionsCalledFor[0]);
// clear the results, and re-run
parseOptionsCalledFor.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(parseOptionsCalledFor);
// now update the parse options
parseOptionsCalledFor.Clear();
var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose);
driver = driver.WithUpdatedParseOptions(newParseOptions);
// check we ran
driver = driver.RunGenerators(compilation);
Assert.Equal(1, parseOptionsCalledFor.Count);
Assert.Equal(newParseOptions, parseOptionsCalledFor[0]);
// clear the results, and re-run
parseOptionsCalledFor.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(parseOptionsCalledFor);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!));
}
[Fact]
public void AnalyzerConfig_Can_Be_Updated()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string? analyzerOptionsValue = string.Empty;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue));
}));
var builder = ImmutableDictionary<string, string>.Empty.ToBuilder();
builder.Add("test", "value1");
var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable()));
// run the generator once, and check it was passed the configs
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider);
driver = driver.RunGenerators(compilation);
Assert.Equal("value1", analyzerOptionsValue);
// clear the results, and re-run
analyzerOptionsValue = null;
driver = driver.RunGenerators(compilation);
Assert.Null(analyzerOptionsValue);
// now update the config
analyzerOptionsValue = null;
builder.Clear();
builder.Add("test", "value2");
var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable()));
driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider);
// check we ran
driver = driver.RunGenerators(compilation);
Assert.Equal("value2", analyzerOptionsValue);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!));
}
[Fact]
public void AdditionalText_Can_Be_Replaced()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", "");
InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", "");
InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", "");
List<string?> additionalTextPaths = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); });
}));
// run the generator once and check we saw the additional file
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 });
driver = driver.RunGenerators(compilation);
Assert.Equal(3, additionalTextPaths.Count);
Assert.Equal("path1.txt", additionalTextPaths[0]);
Assert.Equal("path2.txt", additionalTextPaths[1]);
Assert.Equal("path3.txt", additionalTextPaths[2]);
// re-run and check nothing else got added
additionalTextPaths.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(additionalTextPaths);
// now, update the additional text, but keep the path the same
additionalTextPaths.Clear();
driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", ""));
// run, and check that only the replaced file was invoked
driver = driver.RunGenerators(compilation);
Assert.Single(additionalTextPaths);
Assert.Equal("path4.txt", additionalTextPaths[0]);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!));
}
[Fact]
public void Replaced_Input_Is_Treated_As_Modified()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc");
List<string?> additionalTextPaths = new List<string?>();
List<string?> additionalTextsContents = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var texts = ctx.AdditionalTextsProvider;
var paths = texts.Select((t, _) => t?.Path);
var contents = texts.Select((t, _) => t?.GetText()?.ToString());
ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); });
ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); });
}));
// run the generator once and check we saw the additional file
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText });
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal("path.txt", additionalTextPaths[0]);
Assert.Equal(1, additionalTextsContents.Count);
Assert.Equal("abc", additionalTextsContents[0]);
// re-run and check nothing else got added
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal(1, additionalTextsContents.Count);
// now, update the additional text, but keep the path the same
additionalTextPaths.Clear();
additionalTextsContents.Clear();
var secondText = new InMemoryAdditionalText("path.txt", "def");
driver = driver.ReplaceAdditionalText(additionalText, secondText);
// run, and check that only the contents got re-run
driver = driver.RunGenerators(compilation);
Assert.Empty(additionalTextPaths);
Assert.Equal(1, additionalTextsContents.Count);
Assert.Equal("def", additionalTextsContents[0]);
// now replace the text with a different path, but the same text
additionalTextPaths.Clear();
additionalTextsContents.Clear();
var thirdText = new InMemoryAdditionalText("path2.txt", "def");
driver = driver.ReplaceAdditionalText(secondText, thirdText);
// run, and check that only the paths got re-run
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal("path2.txt", additionalTextPaths[0]);
Assert.Empty(additionalTextsContents);
}
[Theory]
[CombinatorialData]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)]
[InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)]
public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput)
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", ""));
ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", ""));
ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", ""));
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var result = driver.GetRunResult();
Assert.Single(result.Results);
Assert.Empty(result.Results[0].Diagnostics);
// verify the expected outputs were generated
// NOTE: adding new output types will cause this test to fail. Update above as needed.
foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind)))
{
if (kind == IncrementalGeneratorOutputKind.None)
continue;
if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind))
{
Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind);
}
else
{
Assert.Contains(result.Results[0].GeneratedSources, isTextForKind);
}
bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs";
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration
{
public class GeneratorDriverTests
: CSharpTestBase
{
[Fact]
public void Running_With_No_Changes_Is_NoOp()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Empty(diagnostics);
Assert.Single(outputCompilation.SyntaxTrees);
Assert.Equal(compilation, outputCompilation);
}
[Fact]
public void Generator_Is_Initialized_Before_Running()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Equal(1, initCount);
Assert.Equal(1, executeCount);
}
[Fact]
public void Generator_Is_Not_Initialized_If_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
Assert.Equal(0, initCount);
Assert.Equal(0, executeCount);
}
[Fact]
public void Generator_Is_Only_Initialized_Once()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++, source: "public class C { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _);
driver.RunGeneratorsAndUpdateCompilation(outputCompilation, out outputCompilation, out _);
Assert.Equal(1, initCount);
Assert.Equal(3, executeCount);
}
[Fact]
public void Single_File_Is_Added()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
Assert.NotEqual(compilation, outputCompilation);
var generatedClass = outputCompilation.GlobalNamespace.GetTypeMembers("GeneratedClass").Single();
Assert.True(generatedClass.Locations.Single().IsInSource);
}
[Fact]
public void Analyzer_Is_Run()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
var analyzer = new Analyzer_Is_Run_Analyzer();
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
compilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(0, analyzer.GeneratedClassCount);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify();
Assert.Equal(1, analyzer.GeneratedClassCount);
}
private class Analyzer_Is_Run_Analyzer : DiagnosticAnalyzer
{
public int GeneratedClassCount;
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
=> ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.RegisterSymbolAction(Handle, SymbolKind.NamedType);
}
private void Handle(SymbolAnalysisContext context)
{
switch (context.Symbol.ToTestDisplayString())
{
case "GeneratedClass":
Interlocked.Increment(ref GeneratedClassCount);
break;
case "C":
case "System.Runtime.CompilerServices.IsExternalInit":
break;
default:
Assert.True(false);
break;
}
}
}
[Fact]
public void Single_File_Is_Added_OnlyOnce_For_Multiple_Calls()
{
var source = @"
class C { }
";
var generatorSource = @"
class GeneratedClass { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
SingleFileTestGenerator testGenerator = new SingleFileTestGenerator(generatorSource);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation1, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation2, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation3, out _);
Assert.Equal(2, outputCompilation1.SyntaxTrees.Count());
Assert.Equal(2, outputCompilation2.SyntaxTrees.Count());
Assert.Equal(2, outputCompilation3.SyntaxTrees.Count());
Assert.NotEqual(compilation, outputCompilation1);
Assert.NotEqual(compilation, outputCompilation2);
Assert.NotEqual(compilation, outputCompilation3);
}
[Fact]
public void User_Source_Can_Depend_On_Generated_Source()
{
var source = @"
#pragma warning disable CS0649
class C
{
public D d;
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
}
[Fact]
public void Error_During_Initialization_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("init error");
var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Initialization_Generator_Does_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("init error");
var generator = new CallbackGenerator((ic) => throw exception, (sgc) => { }, source: "class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
Assert.Single(outputCompilation.SyntaxTrees);
}
[Fact]
public void Error_During_Generation_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_Does_Not_Affect_Other_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { }, source: "public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_With_Dependent_Source()
{
var source = @"
#pragma warning disable CS0649
class C
{
public D d;
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception, source: "public class D { }");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics(
// (5,12): error CS0246: The type or namespace name 'D' could not be found (are you missing a using directive or an assembly reference?)
// public D d;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "D").WithArguments("D").WithLocation(5, 12)
);
generatorDiagnostics.Verify(
// warning CS8785: Generator 'CallbackGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'generate error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "InvalidOperationException", "generate error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Generation_Has_Exception_In_Description()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var exception = new InvalidOperationException("generate error");
var generator = new CallbackGenerator((ic) => { }, (sgc) => throw exception);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
// Since translated description strings can have punctuation that differs based on locale, simply ensure the
// exception message is contains in the diagnostic description.
Assert.Contains(exception.ToString(), generatorDiagnostics.Single().Descriptor.Description.ToString());
}
[Fact]
public void Generator_Can_Report_Diagnostics()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => sgc.ReportDiagnostic(diagnostic));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify(
Diagnostic("TG001").WithLocation(1, 1)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/54185: the addition happens later so the exceptions don't occur directly at add-time. we should decide if this subtle behavior change is acceptable")]
public void Generator_HintName_MustBe_Unique()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) =>
{
sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8));
// the assert should swallow the exception, so we'll actually successfully generate
Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test", SourceText.From("public class D{}", Encoding.UTF8)));
// also throws for <name> vs <name>.cs
Assert.Throws<ArgumentException>("hintName", () => sgc.AddSource("test.cs", SourceText.From("public class D{}", Encoding.UTF8)));
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
}
[Fact]
public void Generator_HintName_Is_Appended_With_GeneratorName()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D {}", "source.cs");
var generator2 = new SingleFileTestGenerator2("public class E {}", "source.cs");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
generatorDiagnostics.Verify();
Assert.Equal(3, outputCompilation.SyntaxTrees.Count());
var filePaths = outputCompilation.SyntaxTrees.Skip(1).Select(t => t.FilePath).ToArray();
Assert.Equal(new[] {
Path.Combine(generator.GetType().Assembly.GetName().Name!, generator.GetType().FullName!, "source.cs"),
Path.Combine(generator2.GetType().Assembly.GetName().Name!, generator2.GetType().FullName!, "source.cs")
}, filePaths);
}
[Fact]
public void RunResults_Are_Empty_Before_Generation()
{
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray<ISourceGenerator>.Empty, parseOptions: TestOptions.Regular);
var results = driver.GetRunResult();
Assert.Empty(results.GeneratedTrees);
Assert.Empty(results.Diagnostics);
Assert.Empty(results.Results);
}
[Fact]
public void RunResults_Are_Available_After_Generation()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Single(results.GeneratedTrees);
Assert.Single(results.Results);
Assert.Empty(results.Diagnostics);
var result = results.Results.Single();
Assert.Null(result.Exception);
Assert.Empty(result.Diagnostics);
Assert.Single(result.GeneratedSources);
Assert.Equal(results.GeneratedTrees.Single(), result.GeneratedSources.Single().SyntaxTree);
}
[Fact]
public void RunResults_Combine_SyntaxTrees()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("test", SourceText.From("public class D {}", Encoding.UTF8)); sgc.AddSource("test2", SourceText.From("public class E {}", Encoding.UTF8)); });
var generator2 = new SingleFileTestGenerator("public class F{}");
var generator3 = new SingleFileTestGenerator2("public class G{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(4, results.GeneratedTrees.Length);
Assert.Equal(3, results.Results.Length);
Assert.Empty(results.Diagnostics);
var result1 = results.Results[0];
var result2 = results.Results[1];
var result3 = results.Results[2];
Assert.Null(result1.Exception);
Assert.Empty(result1.Diagnostics);
Assert.Equal(2, result1.GeneratedSources.Length);
Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree);
Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree);
Assert.Null(result2.Exception);
Assert.Empty(result2.Diagnostics);
Assert.Single(result2.GeneratedSources);
Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree);
Assert.Null(result3.Exception);
Assert.Empty(result3.Diagnostics);
Assert.Single(result3.GeneratedSources);
Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree);
}
[Fact]
public void RunResults_Combine_Diagnostics()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None);
var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None);
var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(2, results.Results.Length);
Assert.Equal(3, results.Diagnostics.Length);
Assert.Empty(results.GeneratedTrees);
var result1 = results.Results[0];
var result2 = results.Results[1];
Assert.Null(result1.Exception);
Assert.Equal(2, result1.Diagnostics.Length);
Assert.Empty(result1.GeneratedSources);
Assert.Equal(results.Diagnostics[0], result1.Diagnostics[0]);
Assert.Equal(results.Diagnostics[1], result1.Diagnostics[1]);
Assert.Null(result2.Exception);
Assert.Single(result2.Diagnostics);
Assert.Empty(result2.GeneratedSources);
Assert.Equal(results.Diagnostics[2], result2.Diagnostics[0]);
}
[Fact]
public void FullGeneration_Diagnostics_AreSame_As_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string description = "This is a test diagnostic";
DiagnosticDescriptor generatorDiagnostic1 = new DiagnosticDescriptor("TG001", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic2 = new DiagnosticDescriptor("TG002", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
DiagnosticDescriptor generatorDiagnostic3 = new DiagnosticDescriptor("TG003", "Test Diagnostic", description, "Generators", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description);
var diagnostic1 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic1, Location.None);
var diagnostic2 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic2, Location.None);
var diagnostic3 = Microsoft.CodeAnalysis.Diagnostic.Create(generatorDiagnostic3, Location.None);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic1); sgc.ReportDiagnostic(diagnostic2); });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { sgc.ReportDiagnostic(diagnostic3); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var fullDiagnostics);
var results = driver.GetRunResult();
Assert.Equal(3, results.Diagnostics.Length);
Assert.Equal(3, fullDiagnostics.Length);
AssertEx.Equal(results.Diagnostics, fullDiagnostics);
}
[Fact]
public void Cancellation_During_Execution_Doesnt_Report_As_Generator_Error()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CancellationTokenSource cts = new CancellationTokenSource();
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => { cts.Cancel(); }
);
// test generator cancels the token. Check that the call to this generator doesn't make it look like it errored.
var testGenerator2 = new CallbackGenerator2(
onInit: (i) => { },
onExecute: (e) =>
{
e.AddSource("a", SourceText.From("public class E {}", Encoding.UTF8));
e.CancellationToken.ThrowIfCancellationRequested();
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator, testGenerator2 }, parseOptions: parseOptions);
var oldDriver = driver;
Assert.Throws<OperationCanceledException>(() =>
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var outputDiagnostics, cts.Token)
);
Assert.Same(oldDriver, driver);
}
[ConditionalFact(typeof(MonoOrCoreClrOnly), Reason = "Desktop CLR displays argument exceptions differently")]
public void Adding_A_Source_Text_Without_Encoding_Fails_Generation()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => { }, (sgc) => { sgc.AddSource("a", SourceText.From("")); });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out var outputDiagnostics);
Assert.Single(outputDiagnostics);
outputDiagnostics.Verify(
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringGeneration).WithArguments("CallbackGenerator", "ArgumentException", "The SourceText with hintName 'a.cs' must have an explicit encoding set. (Parameter 'source')").WithLocation(1, 1)
);
}
[Fact]
public void ParseOptions_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
ParseOptions? passedOptions = null;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => { passedOptions = e.ParseOptions; }
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.Same(parseOptions, passedOptions);
}
[Fact]
public void AdditionalFiles_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var texts = ImmutableArray.Create<AdditionalText>(new InMemoryAdditionalText("a", "abc"), new InMemoryAdditionalText("b", "def"));
ImmutableArray<AdditionalText> passedIn = default;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => passedIn = e.AdditionalFiles
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, additionalTexts: texts);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.Equal(2, passedIn.Length);
Assert.Equal<AdditionalText>(texts, passedIn);
}
[Fact]
public void AnalyzerConfigOptions_Are_Passed_To_Generator()
{
var source = @"
class C
{
}
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var options = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("a", "abc").Add("b", "def")));
AnalyzerConfigOptionsProvider? passedIn = null;
var testGenerator = new CallbackGenerator(
onInit: (i) => { },
onExecute: (e) => passedIn = e.AnalyzerConfigOptions
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { testGenerator }, parseOptions: parseOptions, optionsProvider: options);
driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
Assert.NotNull(passedIn);
Assert.True(passedIn!.GlobalOptions.TryGetValue("a", out var item1));
Assert.Equal("abc", item1);
Assert.True(passedIn!.GlobalOptions.TryGetValue("b", out var item2));
Assert.Equal("def", item2);
}
[Fact]
public void Generator_Can_Provide_Source_In_PostInit()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { });
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
}
[Fact]
public void PostInit_Source_Is_Available_During_Execute()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
INamedTypeSymbol? dSymbol = null;
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.NotNull(dSymbol);
}
[Fact]
public void PostInit_Source_Is_Available_To_Other_Generators_During_Execute()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
}
INamedTypeSymbol? dSymbol = null;
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => { });
var generator2 = new CallbackGenerator2((ic) => { }, (sgc) => { dSymbol = sgc.Compilation.GetTypeByMetadataName("D"); }, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.NotNull(dSymbol);
}
[Fact]
public void PostInit_Is_Only_Called_Once()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int postInitCount = 0;
int executeCount = 0;
void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
postInitCount++;
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => executeCount++, source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out _, out _);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out _);
outputCompilation.VerifyDiagnostics();
Assert.Equal(1, postInitCount);
Assert.Equal(3, executeCount);
}
[Fact]
public void Error_During_PostInit_Is_Reported()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
throw new InvalidOperationException("post init error");
}
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(postInit), (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'post init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "post init error").WithLocation(1, 1)
);
}
[Fact]
public void Error_During_Initialization_PostInit_Does_Not_Run()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
static void init(GeneratorInitializationContext context)
{
context.RegisterForPostInitialization(postInit);
throw new InvalidOperationException("init error");
}
static void postInit(GeneratorPostInitializationContext context)
{
context.AddSource("postInit", "public class D {} ");
Assert.True(false, "Should not execute");
}
var generator = new CallbackGenerator(init, (sgc) => Assert.True(false, "Should not execute"), source = "public class E : D {}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
generatorDiagnostics.Verify(
// warning CS8784: Generator 'CallbackGenerator' failed to initialize. It will not contribute to the output and compilation errors may occur as a result. Exception was 'InvalidOperationException' with message 'init error'
Diagnostic("CS" + (int)ErrorCode.WRN_GeneratorFailedDuringInitialization).WithArguments("CallbackGenerator", "InvalidOperationException", "init error").WithLocation(1, 1)
);
}
[Fact]
public void PostInit_SyntaxTrees_Are_Available_In_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Single(results.Results);
Assert.Empty(results.Diagnostics);
var result = results.Results[0];
Assert.Null(result.Exception);
Assert.Empty(result.Diagnostics);
Assert.Equal(2, result.GeneratedSources.Length);
}
[Fact]
public void PostInit_SyntaxTrees_Are_Combined_In_RunResults()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new CallbackGenerator((ic) => ic.RegisterForPostInitialization(pic => pic.AddSource("postInit", "public class D{}")), (sgc) => { }, "public class E{}");
var generator2 = new SingleFileTestGenerator("public class F{}");
var generator3 = new SingleFileTestGenerator2("public class G{}");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
Assert.Equal(4, results.GeneratedTrees.Length);
Assert.Equal(3, results.Results.Length);
Assert.Empty(results.Diagnostics);
var result1 = results.Results[0];
var result2 = results.Results[1];
var result3 = results.Results[2];
Assert.Null(result1.Exception);
Assert.Empty(result1.Diagnostics);
Assert.Equal(2, result1.GeneratedSources.Length);
Assert.Equal(results.GeneratedTrees[0], result1.GeneratedSources[0].SyntaxTree);
Assert.Equal(results.GeneratedTrees[1], result1.GeneratedSources[1].SyntaxTree);
Assert.Null(result2.Exception);
Assert.Empty(result2.Diagnostics);
Assert.Single(result2.GeneratedSources);
Assert.Equal(results.GeneratedTrees[2], result2.GeneratedSources[0].SyntaxTree);
Assert.Null(result3.Exception);
Assert.Empty(result3.Diagnostics);
Assert.Single(result3.GeneratedSources);
Assert.Equal(results.GeneratedTrees[3], result3.GeneratedSources[0].SyntaxTree);
}
[Fact]
public void SyntaxTrees_Are_Lazy()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new SingleFileTestGenerator("public class D {}", "source.cs");
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var results = driver.GetRunResult();
var tree = Assert.Single(results.GeneratedTrees);
Assert.False(tree.TryGetRoot(out _));
var rootFromGetRoot = tree.GetRoot();
Assert.NotNull(rootFromGetRoot);
Assert.True(tree.TryGetRoot(out var rootFromTryGetRoot));
Assert.Same(rootFromGetRoot, rootFromTryGetRoot);
}
[Fact]
public void Diagnostics_Respect_Suppression()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) =>
{
c.ReportDiagnostic(CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2));
c.ReportDiagnostic(CSDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 3));
});
var options = ((CSharpCompilationOptions)compilation.Options);
// generator driver diagnostics are reported separately from the compilation
verifyDiagnosticsWithOptions(options,
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1));
// warnings can be individually suppressed
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Suppress),
Diagnostic("GEN002").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Suppress),
Diagnostic("GEN001").WithLocation(1, 1));
// warning level is respected
verifyDiagnosticsWithOptions(options.WithWarningLevel(0));
verifyDiagnosticsWithOptions(options.WithWarningLevel(2),
Diagnostic("GEN001").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithWarningLevel(3),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1));
// warnings can be upgraded to errors
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN001", ReportDiagnostic.Error),
Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(true),
Diagnostic("GEN002").WithLocation(1, 1));
verifyDiagnosticsWithOptions(options.WithSpecificDiagnosticOptions("GEN002", ReportDiagnostic.Error),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(true));
void verifyDiagnosticsWithOptions(CompilationOptions options, params DiagnosticDescription[] expected)
{
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions);
var updatedCompilation = compilation.WithOptions(options);
driver.RunGeneratorsAndUpdateCompilation(updatedCompilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
diagnostics.Verify(expected);
}
}
[Fact]
public void Diagnostics_Respect_Pragma_Suppression()
{
var gen001 = CSDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, true, 2);
// reported diagnostics can have a location in source
verifyDiagnosticsWithSource("//comment",
new[] { (gen001, TextSpan.FromBounds(2, 5)) },
Diagnostic("GEN001", "com").WithLocation(1, 3));
// diagnostics are suppressed via #pragma
verifyDiagnosticsWithSource(
@"#pragma warning disable
//comment",
new[] { (gen001, TextSpan.FromBounds(27, 30)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3));
// but not when they don't have a source location
verifyDiagnosticsWithSource(
@"#pragma warning disable
//comment",
new[] { (gen001, new TextSpan(0, 0)) },
Diagnostic("GEN001").WithLocation(1, 1));
// can be suppressed explicitly
verifyDiagnosticsWithSource(
@"#pragma warning disable GEN001
//comment",
new[] { (gen001, TextSpan.FromBounds(34, 37)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3));
// suppress + restore
verifyDiagnosticsWithSource(
@"#pragma warning disable GEN001
//comment
#pragma warning restore GEN001
//another",
new[] { (gen001, TextSpan.FromBounds(34, 37)), (gen001, TextSpan.FromBounds(77, 80)) },
Diagnostic("GEN001", "com", isSuppressed: true).WithLocation(2, 3),
Diagnostic("GEN001", "ano").WithLocation(4, 3));
void verifyDiagnosticsWithSource(string source, (Diagnostic, TextSpan)[] reportDiagnostics, params DiagnosticDescription[] expected)
{
var parseOptions = TestOptions.Regular;
source = source.Replace(Environment.NewLine, "\r\n");
Compilation compilation = CreateCompilation(source, sourceFileName: "sourcefile.cs", options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CallbackGenerator gen = new CallbackGenerator((c) => { }, (c) =>
{
foreach ((var d, var l) in reportDiagnostics)
{
if (l.IsEmpty)
{
c.ReportDiagnostic(d);
}
else
{
c.ReportDiagnostic(d.WithLocation(Location.Create(c.Compilation.SyntaxTrees.First(), l)));
}
}
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions: parseOptions);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
diagnostics.Verify(expected);
}
}
[Fact]
public void GeneratorDriver_Prefers_Incremental_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int initCount = 0, executeCount = 0;
var generator = new CallbackGenerator((ic) => initCount++, (sgc) => executeCount++);
int incrementalInitCount = 0;
var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++));
int dualInitCount = 0, dualExecuteCount = 0, dualIncrementalInitCount = 0;
var generator3 = new IncrementalAndSourceCallbackGenerator((ic) => dualInitCount++, (sgc) => dualExecuteCount++, (ic) => dualIncrementalInitCount++);
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2, generator3 }, parseOptions: parseOptions);
driver.RunGenerators(compilation);
// ran individual incremental and source generators
Assert.Equal(1, initCount);
Assert.Equal(1, executeCount);
Assert.Equal(1, incrementalInitCount);
// ran the combined generator only as an IIncrementalGenerator
Assert.Equal(0, dualInitCount);
Assert.Equal(0, dualExecuteCount);
Assert.Equal(1, dualIncrementalInitCount);
}
[Fact]
public void GeneratorDriver_Initializes_Incremental_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.Regular;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
int incrementalInitCount = 0;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => incrementalInitCount++));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver.RunGenerators(compilation);
// ran the incremental generator
Assert.Equal(1, incrementalInitCount);
}
[Fact]
public void Incremental_Generators_Exception_During_Initialization()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => throw e));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) => ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e)));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Produce_AnySource()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", ""));
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e);
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Single(runResults.Results);
Assert.Empty(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void Incremental_Generators_Exception_During_Execution_Doesnt_Stop_Other_Generators()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var e = new InvalidOperationException("abc");
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => throw e);
}));
var generator2 = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator2((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => spc.AddSource("test", ""));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator, generator2 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var runResults = driver.GetRunResult();
Assert.Single(runResults.Diagnostics);
Assert.Equal(2, runResults.Results.Length);
Assert.Single(runResults.GeneratedTrees);
Assert.Equal(e, runResults.Results[0].Exception);
}
[Fact]
public void IncrementalGenerator_With_No_Pipeline_Callback_Is_Valid()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => { }));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
outputCompilation.VerifyDiagnostics();
Assert.Empty(diagnostics);
}
[Fact]
public void IncrementalGenerator_Can_Add_PostInit_Source()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ic) => ic.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}"))));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);
Assert.Equal(2, outputCompilation.SyntaxTrees.Count());
Assert.Empty(diagnostics);
}
[Fact]
public void User_WrappedFunc_Throw_Exceptions()
{
Func<int, CancellationToken, int> func = (input, _) => input;
Func<int, CancellationToken, int> throwsFunc = (input, _) => throw new InvalidOperationException("user code exception");
Func<int, CancellationToken, int> timeoutFunc = (input, ct) => { ct.ThrowIfCancellationRequested(); return input; };
Func<int, CancellationToken, int> otherTimeoutFunc = (input, _) => throw new OperationCanceledException();
var userFunc = func.WrapUserFunction();
var userThrowsFunc = throwsFunc.WrapUserFunction();
var userTimeoutFunc = timeoutFunc.WrapUserFunction();
var userOtherTimeoutFunc = otherTimeoutFunc.WrapUserFunction();
// user functions return same values when wrapped
var result = userFunc(10, CancellationToken.None);
var userResult = userFunc(10, CancellationToken.None);
Assert.Equal(10, result);
Assert.Equal(result, userResult);
// exceptions thrown in user code are wrapped
Assert.Throws<InvalidOperationException>(() => throwsFunc(20, CancellationToken.None));
Assert.Throws<UserFunctionException>(() => userThrowsFunc(20, CancellationToken.None));
try
{
userThrowsFunc(20, CancellationToken.None);
}
catch (UserFunctionException e)
{
Assert.IsType<InvalidOperationException>(e.InnerException);
}
// cancellation is not wrapped, and is bubbled up
Assert.Throws<OperationCanceledException>(() => timeoutFunc(30, new CancellationToken(true)));
Assert.Throws<OperationCanceledException>(() => userTimeoutFunc(30, new CancellationToken(true)));
// unless it wasn't *our* cancellation token, in which case it still gets wrapped
Assert.Throws<OperationCanceledException>(() => otherTimeoutFunc(30, CancellationToken.None));
Assert.Throws<UserFunctionException>(() => userOtherTimeoutFunc(30, CancellationToken.None));
}
[Fact]
public void IncrementalGenerator_Doesnt_Run_For_Same_Input()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var filePaths = ctx.CompilationProvider.SelectMany((c, _) => c.SyntaxTrees).Select((tree, _) => tree.FilePath);
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); });
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
// run the same compilation through again, and confirm the output wasn't called
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_Runs_Only_For_Changed_Inputs()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var text1 = new InMemoryAdditionalText("Text1", "content1");
var text2 = new InMemoryAdditionalText("Text2", "content2");
List<Compilation> compilationsCalledFor = new List<Compilation>();
List<AdditionalText> textsCalledFor = new List<AdditionalText>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, c) => { compilationsCalledFor.Add(c); });
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, c) => { textsCalledFor.Add(c); });
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, additionalTexts: new[] { text1 }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
Assert.Equal(1, textsCalledFor.Count);
Assert.Equal(text1, textsCalledFor[0]);
// clear the results, add an additional text, but keep the compilation the same
compilationsCalledFor.Clear();
textsCalledFor.Clear();
driver = driver.AddAdditionalTexts(ImmutableArray.Create<AdditionalText>(text2));
driver = driver.RunGenerators(compilation);
Assert.Equal(0, compilationsCalledFor.Count);
Assert.Equal(1, textsCalledFor.Count);
Assert.Equal(text2, textsCalledFor[0]);
// now edit the compilation
compilationsCalledFor.Clear();
textsCalledFor.Clear();
var newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newComp"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(newCompilation, compilationsCalledFor[0]);
Assert.Equal(0, textsCalledFor.Count);
// re run without changing anything
compilationsCalledFor.Clear();
textsCalledFor.Clear();
driver = driver.RunGenerators(newCompilation);
Assert.Equal(0, compilationsCalledFor.Count);
Assert.Equal(0, textsCalledFor.Count);
}
[Fact]
public void IncrementalGenerator_Can_Add_Comparer_To_Input_Node()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var compilationSource = ctx.CompilationProvider.WithComparer(new LambdaComparer<Compilation>((c1, c2) => true, 0));
ctx.RegisterSourceOutput(compilationSource, (spc, c) =>
{
compilationsCalledFor.Add(c);
});
}));
// run the generator once, and check it was passed the compilation
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
// now edit the compilation, run the generator, and confirm that the output was not called again this time
Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_Can_Add_Comparer_To_Combine_Node()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<AdditionalText> texts = new List<AdditionalText>() { new InMemoryAdditionalText("abc", "") };
List<(Compilation, ImmutableArray<AdditionalText>)> calledFor = new List<(Compilation, ImmutableArray<AdditionalText>)>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var compilationSource = ctx.CompilationProvider.Combine(ctx.AdditionalTextsProvider.Collect())
// comparer that ignores the LHS (additional texts)
.WithComparer(new LambdaComparer<(Compilation, ImmutableArray<AdditionalText>)>((c1, c2) => c1.Item1 == c2.Item1, 0));
ctx.RegisterSourceOutput(compilationSource, (spc, c) =>
{
calledFor.Add(c);
});
}));
// run the generator once, and check it was passed the compilation + additional texts
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: texts);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, calledFor.Count);
Assert.Equal(compilation, calledFor[0].Item1);
Assert.Equal(texts[0], calledFor[0].Item2.Single());
// edit the additional texts, and verify that the output was *not* called again on the next run
driver = driver.RemoveAdditionalTexts(texts.ToImmutableArray());
driver = driver.RunGenerators(compilation);
Assert.Equal(1, calledFor.Count);
// now edit the compilation, run the generator, and confirm that the output *was* called again this time with the new compilation and no additional texts
Compilation newCompilation = compilation.WithOptions(compilation.Options.WithModuleName("newCompilation"));
driver = driver.RunGenerators(newCompilation);
Assert.Equal(2, calledFor.Count);
Assert.Equal(newCompilation, calledFor[1].Item1);
Assert.Empty(calledFor[1].Item2);
}
[Fact]
public void IncrementalGenerator_Register_End_Node_Only_Once_Through_Combines()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<Compilation> compilationsCalledFor = new List<Compilation>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var source = ctx.CompilationProvider;
var source2 = ctx.CompilationProvider.Combine(source);
var source3 = ctx.CompilationProvider.Combine(source2);
var source4 = ctx.CompilationProvider.Combine(source3);
var source5 = ctx.CompilationProvider.Combine(source4);
ctx.RegisterSourceOutput(source5, (spc, c) =>
{
compilationsCalledFor.Add(c.Item1);
});
}));
// run the generator and check that we didn't multiple register the generate source node through the combine
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, compilationsCalledFor.Count);
Assert.Equal(compilation, compilationsCalledFor[0]);
}
[Fact]
public void IncrementalGenerator_PostInit_Source_Is_Cached()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<ClassDeclarationSyntax> classes = new List<ClassDeclarationSyntax>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterPostInitializationOutput(c => c.AddSource("a", "class D {}"));
ctx.RegisterSourceOutput(ctx.SyntaxProvider.CreateSyntaxProvider(static (n, _) => n is ClassDeclarationSyntax, (gsc, _) => (ClassDeclarationSyntax)gsc.Node), (spc, node) => classes.Add(node));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(2, classes.Count);
Assert.Equal("C", classes[0].Identifier.ValueText);
Assert.Equal("D", classes[1].Identifier.ValueText);
// clear classes, re-run
classes.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(classes);
// modify the original tree, see that the post init is still cached
var c2 = compilation.ReplaceSyntaxTree(compilation.SyntaxTrees.First(), CSharpSyntaxTree.ParseText("class E{}", parseOptions));
classes.Clear();
driver = driver.RunGenerators(c2);
Assert.Single(classes);
Assert.Equal("E", classes[0].Identifier.ValueText);
}
[Fact]
public void Incremental_Generators_Can_Be_Cancelled()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
CancellationTokenSource cts = new CancellationTokenSource();
bool generatorCancelled = false;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator((ctx) =>
{
var step1 = ctx.CompilationProvider.Select((c, ct) => { generatorCancelled = true; cts.Cancel(); return c; });
var step2 = step1.Select((c, ct) => { ct.ThrowIfCancellationRequested(); return c; });
ctx.RegisterSourceOutput(step2, (spc, c) => spc.AddSource("a", ""));
}));
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
Assert.Throws<OperationCanceledException>(() => driver = driver.RunGenerators(compilation, cancellationToken: cts.Token));
Assert.True(generatorCancelled);
}
[Fact]
public void ParseOptions_Can_Be_Updated()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
List<ParseOptions> parseOptionsCalledFor = new List<ParseOptions>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, p) => { parseOptionsCalledFor.Add(p); });
}));
// run the generator once, and check it was passed the parse options
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
Assert.Equal(1, parseOptionsCalledFor.Count);
Assert.Equal(parseOptions, parseOptionsCalledFor[0]);
// clear the results, and re-run
parseOptionsCalledFor.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(parseOptionsCalledFor);
// now update the parse options
parseOptionsCalledFor.Clear();
var newParseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Diagnose);
driver = driver.WithUpdatedParseOptions(newParseOptions);
// check we ran
driver = driver.RunGenerators(compilation);
Assert.Equal(1, parseOptionsCalledFor.Count);
Assert.Equal(newParseOptions, parseOptionsCalledFor[0]);
// clear the results, and re-run
parseOptionsCalledFor.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(parseOptionsCalledFor);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedParseOptions(null!));
}
[Fact]
public void AnalyzerConfig_Can_Be_Updated()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
string? analyzerOptionsValue = string.Empty;
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, p) => p.GlobalOptions.TryGetValue("test", out analyzerOptionsValue));
}));
var builder = ImmutableDictionary<string, string>.Empty.ToBuilder();
builder.Add("test", "value1");
var optionsProvider = new CompilerAnalyzerConfigOptionsProvider(ImmutableDictionary<object, AnalyzerConfigOptions>.Empty, new CompilerAnalyzerConfigOptions(builder.ToImmutable()));
// run the generator once, and check it was passed the configs
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, optionsProvider: optionsProvider);
driver = driver.RunGenerators(compilation);
Assert.Equal("value1", analyzerOptionsValue);
// clear the results, and re-run
analyzerOptionsValue = null;
driver = driver.RunGenerators(compilation);
Assert.Null(analyzerOptionsValue);
// now update the config
analyzerOptionsValue = null;
builder.Clear();
builder.Add("test", "value2");
var newOptionsProvider = optionsProvider.WithGlobalOptions(new CompilerAnalyzerConfigOptions(builder.ToImmutable()));
driver = driver.WithUpdatedAnalyzerConfigOptions(newOptionsProvider);
// check we ran
driver = driver.RunGenerators(compilation);
Assert.Equal("value2", analyzerOptionsValue);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.WithUpdatedAnalyzerConfigOptions(null!));
}
[Fact]
public void AdditionalText_Can_Be_Replaced()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
InMemoryAdditionalText additionalText1 = new InMemoryAdditionalText("path1.txt", "");
InMemoryAdditionalText additionalText2 = new InMemoryAdditionalText("path2.txt", "");
InMemoryAdditionalText additionalText3 = new InMemoryAdditionalText("path3.txt", "");
List<string?> additionalTextPaths = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider.Select((t, _) => t.Path), (spc, p) => { additionalTextPaths.Add(p); });
}));
// run the generator once and check we saw the additional file
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText1, additionalText2, additionalText3 });
driver = driver.RunGenerators(compilation);
Assert.Equal(3, additionalTextPaths.Count);
Assert.Equal("path1.txt", additionalTextPaths[0]);
Assert.Equal("path2.txt", additionalTextPaths[1]);
Assert.Equal("path3.txt", additionalTextPaths[2]);
// re-run and check nothing else got added
additionalTextPaths.Clear();
driver = driver.RunGenerators(compilation);
Assert.Empty(additionalTextPaths);
// now, update the additional text, but keep the path the same
additionalTextPaths.Clear();
driver = driver.ReplaceAdditionalText(additionalText2, new InMemoryAdditionalText("path4.txt", ""));
// run, and check that only the replaced file was invoked
driver = driver.RunGenerators(compilation);
Assert.Single(additionalTextPaths);
Assert.Equal("path4.txt", additionalTextPaths[0]);
// replace it with null, and check that it throws
Assert.Throws<ArgumentNullException>(() => driver.ReplaceAdditionalText(additionalText1, null!));
}
[Fact]
public void Replaced_Input_Is_Treated_As_Modified()
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
InMemoryAdditionalText additionalText = new InMemoryAdditionalText("path.txt", "abc");
List<string?> additionalTextPaths = new List<string?>();
List<string?> additionalTextsContents = new List<string?>();
var generator = new IncrementalGeneratorWrapper(new PipelineCallbackGenerator(ctx =>
{
var texts = ctx.AdditionalTextsProvider;
var paths = texts.Select((t, _) => t?.Path);
var contents = texts.Select((t, _) => t?.GetText()?.ToString());
ctx.RegisterSourceOutput(paths, (spc, p) => { additionalTextPaths.Add(p); });
ctx.RegisterSourceOutput(contents, (spc, p) => { additionalTextsContents.Add(p); });
}));
// run the generator once and check we saw the additional file
GeneratorDriver driver = CSharpGeneratorDriver.Create(new ISourceGenerator[] { generator }, parseOptions: parseOptions, additionalTexts: new[] { additionalText });
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal("path.txt", additionalTextPaths[0]);
Assert.Equal(1, additionalTextsContents.Count);
Assert.Equal("abc", additionalTextsContents[0]);
// re-run and check nothing else got added
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal(1, additionalTextsContents.Count);
// now, update the additional text, but keep the path the same
additionalTextPaths.Clear();
additionalTextsContents.Clear();
var secondText = new InMemoryAdditionalText("path.txt", "def");
driver = driver.ReplaceAdditionalText(additionalText, secondText);
// run, and check that only the contents got re-run
driver = driver.RunGenerators(compilation);
Assert.Empty(additionalTextPaths);
Assert.Equal(1, additionalTextsContents.Count);
Assert.Equal("def", additionalTextsContents[0]);
// now replace the text with a different path, but the same text
additionalTextPaths.Clear();
additionalTextsContents.Clear();
var thirdText = new InMemoryAdditionalText("path2.txt", "def");
driver = driver.ReplaceAdditionalText(secondText, thirdText);
// run, and check that only the paths got re-run
driver = driver.RunGenerators(compilation);
Assert.Equal(1, additionalTextPaths.Count);
Assert.Equal("path2.txt", additionalTextPaths[0]);
Assert.Empty(additionalTextsContents);
}
[Theory]
[CombinatorialData]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation)]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.PostInit)]
[InlineData(IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)]
[InlineData(IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation | IncrementalGeneratorOutputKind.PostInit)]
public void Generator_Output_Kinds_Can_Be_Disabled(IncrementalGeneratorOutputKind disabledOutput)
{
var source = @"
class C { }
";
var parseOptions = TestOptions.RegularPreview;
Compilation compilation = CreateCompilation(source, options: TestOptions.DebugDll, parseOptions: parseOptions);
compilation.VerifyDiagnostics();
Assert.Single(compilation.SyntaxTrees);
var generator = new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterPostInitializationOutput((context) => context.AddSource("PostInit", ""));
ctx.RegisterSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Source", ""));
ctx.RegisterImplementationSourceOutput(ctx.CompilationProvider, (context, ct) => context.AddSource("Implementation", ""));
});
GeneratorDriver driver = CSharpGeneratorDriver.Create(new[] { generator.AsSourceGenerator() }, driverOptions: new GeneratorDriverOptions(disabledOutput), parseOptions: parseOptions);
driver = driver.RunGenerators(compilation);
var result = driver.GetRunResult();
Assert.Single(result.Results);
Assert.Empty(result.Results[0].Diagnostics);
// verify the expected outputs were generated
// NOTE: adding new output types will cause this test to fail. Update above as needed.
foreach (IncrementalGeneratorOutputKind kind in Enum.GetValues(typeof(IncrementalGeneratorOutputKind)))
{
if (kind == IncrementalGeneratorOutputKind.None)
continue;
if (disabledOutput.HasFlag((IncrementalGeneratorOutputKind)kind))
{
Assert.DoesNotContain(result.Results[0].GeneratedSources, isTextForKind);
}
else
{
Assert.Contains(result.Results[0].GeneratedSources, isTextForKind);
}
bool isTextForKind(GeneratedSourceResult s) => s.HintName == Enum.GetName(typeof(IncrementalGeneratorOutputKind), kind) + ".cs";
}
}
}
}
| 1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Test/Semantic/SourceGeneration/StateTableTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration
{
public class StateTableTests
{
[Fact]
public void Node_Table_Entries_Can_Be_Enumerated()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(2), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(3), EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added));
AssertTableEntries(table, expected);
}
[Fact]
public void Node_Table_Entries_Are_Flattened_When_Enumerated()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added), (5, EntryState.Added), (6, EntryState.Added), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added));
AssertTableEntries(table, expected);
}
[Fact]
public void Node_Table_Entries_Can_Be_The_Same_Object()
{
var o = new object();
var builder = NodeStateTable<object>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(o, o, o), EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((o, EntryState.Added), (o, EntryState.Added), (o, EntryState.Added));
AssertTableEntries(table, expected);
}
[Fact]
public void Node_Table_Entries_Can_Be_Null()
{
object? o = new object();
var builder = NodeStateTable<object?>.Empty.ToBuilder();
builder.AddEntry(o, EntryState.Added);
builder.AddEntry(null, EntryState.Added);
builder.AddEntry(o, EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((o, EntryState.Added), (null, EntryState.Added), (o, EntryState.Added));
AssertTableEntries(table, expected);
}
[Fact]
public void Node_Builder_Can_Add_Entries_From_Previous_Table()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(2, 3), EntryState.Cached);
builder.AddEntries(ImmutableArray.Create(4, 5), EntryState.Modified);
builder.AddEntries(ImmutableArray.Create(6), EntryState.Added);
var previousTable = builder.ToImmutableAndFree();
builder = previousTable.ToBuilder();
builder.AddEntries(ImmutableArray.Create(10, 11), EntryState.Added);
builder.TryUseCachedEntries(); // ((2, EntryState.Cached), (3, EntryState.Cached))
builder.AddEntries(ImmutableArray.Create(20, 21, 22), EntryState.Modified);
builder.RemoveEntries(); //((6, EntryState.Removed)));
var newTable = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((10, EntryState.Added), (11, EntryState.Added), (2, EntryState.Cached), (3, EntryState.Cached), (20, EntryState.Modified), (21, EntryState.Modified), (22, EntryState.Modified), (6, EntryState.Removed));
AssertTableEntries(newTable, expected);
}
[Fact]
public void Node_Table_Entries_Are_Cached_Or_Dropped_When_Cached()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed);
builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added));
AssertTableEntries(table, expected);
var compactedTable = table.AsCached();
expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached));
AssertTableEntries(compactedTable, expected);
}
[Fact]
public void Node_Table_AsCached_Occurs_Only_Once()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed);
builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added));
AssertTableEntries(table, expected);
var compactedTable = table.AsCached();
expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached));
AssertTableEntries(compactedTable, expected);
// calling as cached a second time just returns the same instance
var compactedTable2 = compactedTable.AsCached();
Assert.Same(compactedTable, compactedTable2);
}
[Fact]
public void Node_Table_Single_Returns_First_Item()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1), EntryState.Added);
var table = builder.ToImmutableAndFree();
Assert.Equal(1, table.Single());
}
[Fact]
public void Node_Table_Single_Returns_Second_Item_When_First_Is_Removed()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1), EntryState.Added);
var table = builder.ToImmutableAndFree();
AssertTableEntries(table, new[] { (1, EntryState.Added) });
// remove the first item and replace it in the table
builder = table.ToBuilder();
builder.RemoveEntries();
builder.AddEntries(ImmutableArray.Create(2), EntryState.Added);
table = builder.ToImmutableAndFree();
AssertTableEntries(table, new[] { (1, EntryState.Removed), (2, EntryState.Added) });
Assert.Equal(2, table.Single());
}
[Fact]
public void Node_Builder_Handles_Modification_When_Both_Tables_Have_Empty_Entries()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1, 2), EntryState.Added);
builder.AddEntries(ImmutableArray<int>.Empty, EntryState.Added);
builder.AddEntries(ImmutableArray.Create(3, 4), EntryState.Added);
var previousTable = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added));
AssertTableEntries(previousTable, expected);
builder = previousTable.ToBuilder();
Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 2), EqualityComparer<int>.Default)); // ((3, EntryState.Modified), (2, EntryState.Cached))
Assert.True(builder.TryModifyEntries(ImmutableArray<int>.Empty, EqualityComparer<int>.Default)); // nothing
Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 5), EqualityComparer<int>.Default)); // ((3, EntryState.Cached), (5, EntryState.Modified))
var newTable = builder.ToImmutableAndFree();
expected = ImmutableArray.Create((3, EntryState.Modified), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Modified));
AssertTableEntries(newTable, expected);
}
[Fact]
public void Node_Table_Doesnt_Modify_Single_Item_Multiple_Times_When_Same()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(2), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(3), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(4), EntryState.Added);
var previousTable = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added));
AssertTableEntries(previousTable, expected);
builder = previousTable.ToBuilder();
Assert.True(builder.TryModifyEntry(1, EqualityComparer<int>.Default)); // ((1, EntryState.Cached))
Assert.True(builder.TryModifyEntry(2, EqualityComparer<int>.Default)); // ((2, EntryState.Cached))
Assert.True(builder.TryModifyEntry(5, EqualityComparer<int>.Default)); // ((5, EntryState.Modified))
Assert.True(builder.TryModifyEntry(4, EqualityComparer<int>.Default)); // ((4, EntryState.Cached))
var newTable = builder.ToImmutableAndFree();
expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (5, EntryState.Modified), (4, EntryState.Cached));
AssertTableEntries(newTable, expected);
}
[Fact]
public void Driver_Table_Calls_Into_Node_With_Self()
{
DriverStateTable.Builder? passedIn = null;
CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) =>
{
passedIn = b;
return s;
});
DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty);
builder.GetLatestStateTableForNode(callbackNode);
Assert.Same(builder, passedIn);
}
[Fact]
public void Driver_Table_Calls_Into_Node_With_EmptyState_FirstTime()
{
NodeStateTable<int>? passedIn = null;
CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) =>
{
passedIn = s;
return s;
});
DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty);
builder.GetLatestStateTableForNode(callbackNode);
Assert.Same(NodeStateTable<int>.Empty, passedIn);
}
[Fact]
public void Driver_Table_Calls_Into_Node_With_PreviousTable()
{
var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder();
nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Cached);
var newTable = nodeBuilder.ToImmutableAndFree();
NodeStateTable<int>? passedIn = null;
CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) =>
{
passedIn = s;
return newTable;
});
// empty first time
DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty);
builder.GetLatestStateTableForNode(callbackNode);
Assert.Same(NodeStateTable<int>.Empty, passedIn);
// gives the returned table the second time around
DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable());
builder2.GetLatestStateTableForNode(callbackNode);
Assert.NotNull(passedIn);
AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) });
}
[Fact]
public void Driver_Table_Compacts_State_Tables_When_Made_Immutable()
{
var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder();
nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added);
nodeBuilder.AddEntries(ImmutableArray.Create(4), EntryState.Removed);
nodeBuilder.AddEntries(ImmutableArray.Create(5, 6), EntryState.Modified);
var newTable = nodeBuilder.ToImmutableAndFree();
NodeStateTable<int>? passedIn = null;
CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) =>
{
passedIn = s;
return newTable;
});
// empty first time
DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty);
builder.GetLatestStateTableForNode(callbackNode);
Assert.Same(NodeStateTable<int>.Empty, passedIn);
// gives the returned table the second time around
DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable());
builder2.GetLatestStateTableForNode(callbackNode);
// table returned from the first instance was compacted by the builder
Assert.NotNull(passedIn);
AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Cached), (6, EntryState.Cached) });
}
[Fact]
public void Driver_Table_Builder_Doesnt_Build_Twice()
{
int callCount = 0;
CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) =>
{
callCount++;
return s;
});
// multiple gets will only call it once
DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty);
builder.GetLatestStateTableForNode(callbackNode);
builder.GetLatestStateTableForNode(callbackNode);
builder.GetLatestStateTableForNode(callbackNode);
Assert.Equal(1, callCount);
// second time around we'll call it once, but no more
DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable());
builder2.GetLatestStateTableForNode(callbackNode);
builder2.GetLatestStateTableForNode(callbackNode);
builder2.GetLatestStateTableForNode(callbackNode);
Assert.Equal(2, callCount);
}
[Fact]
public void Batch_Node_Is_Cached_If_All_Inputs_Are_Cached()
{
var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, 3));
BatchNode<int> batchNode = new BatchNode<int>(inputNode);
// first time through will always be added (because it's not been run before)
DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty);
_ = dstBuilder.GetLatestStateTableForNode(batchNode);
// second time through should show as cached
dstBuilder = GetBuilder(dstBuilder.ToImmutable());
var table = dstBuilder.GetLatestStateTableForNode(batchNode);
AssertTableEntries(table, new[] { (ImmutableArray.Create(1, 2, 3), EntryState.Cached) });
}
[Fact]
public void Batch_Node_Is_Not_Cached_When_Inputs_Are_Changed()
{
int third = 3;
var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, third++));
BatchNode<int> batchNode = new BatchNode<int>(inputNode);
// first time through will always be added (because it's not been run before)
DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty);
_ = dstBuilder.GetLatestStateTableForNode(batchNode);
// second time through should show as modified
dstBuilder = GetBuilder(dstBuilder.ToImmutable());
var table = dstBuilder.GetLatestStateTableForNode(batchNode);
AssertTableEntries(table, new[] { (ImmutableArray.Create(1, 2, 4), EntryState.Modified) });
}
[Fact]
public void User_Comparer_Is_Not_Used_To_Determine_Inputs()
{
var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, 3))
.WithComparer(new LambdaComparer<int>((a, b) => false));
// first time through will always be added (because it's not been run before)
DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty);
_ = dstBuilder.GetLatestStateTableForNode(inputNode);
// second time through should show as cached, even though we supplied a comparer (comparer should only used to turn modified => cached)
dstBuilder = GetBuilder(dstBuilder.ToImmutable());
var table = dstBuilder.GetLatestStateTableForNode(inputNode);
AssertTableEntries(table, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) });
}
private void AssertTableEntries<T>(NodeStateTable<T> table, IList<(T item, EntryState state)> expected)
{
int index = 0;
foreach (var entry in table)
{
Assert.Equal(expected[index].item, entry.item);
Assert.Equal(expected[index].state, entry.state);
index++;
}
}
private void AssertTableEntries<T>(NodeStateTable<ImmutableArray<T>> table, IList<(ImmutableArray<T> item, EntryState state)> expected)
{
int index = 0;
foreach (var entry in table)
{
AssertEx.Equal(expected[index].item, entry.item);
Assert.Equal(expected[index].state, entry.state);
index++;
}
}
private DriverStateTable.Builder GetBuilder(DriverStateTable previous)
{
var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10);
var c = CSharpCompilation.Create("empty");
var state = new GeneratorDriverState(options,
CompilerAnalyzerConfigOptionsProvider.Empty,
ImmutableArray<ISourceGenerator>.Empty,
ImmutableArray<IIncrementalGenerator>.Empty,
ImmutableArray<AdditionalText>.Empty,
ImmutableArray<GeneratorState>.Empty,
previous,
enableIncremental: true,
disabledOutputs: IncrementalGeneratorOutputKind.None);
return new DriverStateTable.Builder(c, state, ImmutableArray<ISyntaxInputNode>.Empty);
}
private class CallbackNode<T> : IIncrementalGeneratorNode<T>
{
private readonly Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> _callback;
public CallbackNode(Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> callback)
{
_callback = callback;
}
public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken)
{
return _callback(graphState, previousTable);
}
public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => this;
public void RegisterOutput(IIncrementalGeneratorOutputNode output) { }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Xunit;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Test.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration
{
public class StateTableTests
{
[Fact]
public void Node_Table_Entries_Can_Be_Enumerated()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(2), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(3), EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added));
AssertTableEntries(table, expected);
}
[Fact]
public void Node_Table_Entries_Are_Flattened_When_Enumerated()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added), (5, EntryState.Added), (6, EntryState.Added), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added));
AssertTableEntries(table, expected);
}
[Fact]
public void Node_Table_Entries_Can_Be_The_Same_Object()
{
var o = new object();
var builder = NodeStateTable<object>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(o, o, o), EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((o, EntryState.Added), (o, EntryState.Added), (o, EntryState.Added));
AssertTableEntries(table, expected);
}
[Fact]
public void Node_Table_Entries_Can_Be_Null()
{
object? o = new object();
var builder = NodeStateTable<object?>.Empty.ToBuilder();
builder.AddEntry(o, EntryState.Added);
builder.AddEntry(null, EntryState.Added);
builder.AddEntry(o, EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((o, EntryState.Added), (null, EntryState.Added), (o, EntryState.Added));
AssertTableEntries(table, expected);
}
[Fact]
public void Node_Builder_Can_Add_Entries_From_Previous_Table()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(2, 3), EntryState.Cached);
builder.AddEntries(ImmutableArray.Create(4, 5), EntryState.Modified);
builder.AddEntries(ImmutableArray.Create(6), EntryState.Added);
var previousTable = builder.ToImmutableAndFree();
builder = previousTable.ToBuilder();
builder.AddEntries(ImmutableArray.Create(10, 11), EntryState.Added);
builder.TryUseCachedEntries(); // ((2, EntryState.Cached), (3, EntryState.Cached))
builder.AddEntries(ImmutableArray.Create(20, 21, 22), EntryState.Modified);
builder.RemoveEntries(); //((6, EntryState.Removed)));
var newTable = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((10, EntryState.Added), (11, EntryState.Added), (2, EntryState.Cached), (3, EntryState.Cached), (20, EntryState.Modified), (21, EntryState.Modified), (22, EntryState.Modified), (6, EntryState.Removed));
AssertTableEntries(newTable, expected);
}
[Fact]
public void Node_Table_Entries_Are_Cached_Or_Dropped_When_Cached()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed);
builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added));
AssertTableEntries(table, expected);
var compactedTable = table.AsCached();
expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached));
AssertTableEntries(compactedTable, expected);
}
[Fact]
public void Node_Table_AsCached_Occurs_Only_Once()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(4, 5, 6), EntryState.Removed);
builder.AddEntries(ImmutableArray.Create(7, 8, 9), EntryState.Added);
var table = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Removed), (5, EntryState.Removed), (6, EntryState.Removed), (7, EntryState.Added), (8, EntryState.Added), (9, EntryState.Added));
AssertTableEntries(table, expected);
var compactedTable = table.AsCached();
expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (7, EntryState.Cached), (8, EntryState.Cached), (9, EntryState.Cached));
AssertTableEntries(compactedTable, expected);
// calling as cached a second time just returns the same instance
var compactedTable2 = compactedTable.AsCached();
Assert.Same(compactedTable, compactedTable2);
}
[Fact]
public void Node_Table_Single_Returns_First_Item()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1), EntryState.Added);
var table = builder.ToImmutableAndFree();
Assert.Equal(1, table.Single());
}
[Fact]
public void Node_Table_Single_Returns_Second_Item_When_First_Is_Removed()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1), EntryState.Added);
var table = builder.ToImmutableAndFree();
AssertTableEntries(table, new[] { (1, EntryState.Added) });
// remove the first item and replace it in the table
builder = table.ToBuilder();
builder.RemoveEntries();
builder.AddEntries(ImmutableArray.Create(2), EntryState.Added);
table = builder.ToImmutableAndFree();
AssertTableEntries(table, new[] { (1, EntryState.Removed), (2, EntryState.Added) });
Assert.Equal(2, table.Single());
}
[Fact]
public void Node_Builder_Handles_Modification_When_Both_Tables_Have_Empty_Entries()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1, 2), EntryState.Added);
builder.AddEntries(ImmutableArray<int>.Empty, EntryState.Added);
builder.AddEntries(ImmutableArray.Create(3, 4), EntryState.Added);
var previousTable = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added));
AssertTableEntries(previousTable, expected);
builder = previousTable.ToBuilder();
Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 2), EqualityComparer<int>.Default)); // ((3, EntryState.Modified), (2, EntryState.Cached))
Assert.True(builder.TryModifyEntries(ImmutableArray<int>.Empty, EqualityComparer<int>.Default)); // nothing
Assert.True(builder.TryModifyEntries(ImmutableArray.Create(3, 5), EqualityComparer<int>.Default)); // ((3, EntryState.Cached), (5, EntryState.Modified))
var newTable = builder.ToImmutableAndFree();
expected = ImmutableArray.Create((3, EntryState.Modified), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Modified));
AssertTableEntries(newTable, expected);
}
[Fact]
public void Node_Table_Doesnt_Modify_Single_Item_Multiple_Times_When_Same()
{
var builder = NodeStateTable<int>.Empty.ToBuilder();
builder.AddEntries(ImmutableArray.Create(1), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(2), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(3), EntryState.Added);
builder.AddEntries(ImmutableArray.Create(4), EntryState.Added);
var previousTable = builder.ToImmutableAndFree();
var expected = ImmutableArray.Create((1, EntryState.Added), (2, EntryState.Added), (3, EntryState.Added), (4, EntryState.Added));
AssertTableEntries(previousTable, expected);
builder = previousTable.ToBuilder();
Assert.True(builder.TryModifyEntry(1, EqualityComparer<int>.Default)); // ((1, EntryState.Cached))
Assert.True(builder.TryModifyEntry(2, EqualityComparer<int>.Default)); // ((2, EntryState.Cached))
Assert.True(builder.TryModifyEntry(5, EqualityComparer<int>.Default)); // ((5, EntryState.Modified))
Assert.True(builder.TryModifyEntry(4, EqualityComparer<int>.Default)); // ((4, EntryState.Cached))
var newTable = builder.ToImmutableAndFree();
expected = ImmutableArray.Create((1, EntryState.Cached), (2, EntryState.Cached), (5, EntryState.Modified), (4, EntryState.Cached));
AssertTableEntries(newTable, expected);
}
[Fact]
public void Driver_Table_Calls_Into_Node_With_Self()
{
DriverStateTable.Builder? passedIn = null;
CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) =>
{
passedIn = b;
return s;
});
DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty);
builder.GetLatestStateTableForNode(callbackNode);
Assert.Same(builder, passedIn);
}
[Fact]
public void Driver_Table_Calls_Into_Node_With_EmptyState_FirstTime()
{
NodeStateTable<int>? passedIn = null;
CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) =>
{
passedIn = s;
return s;
});
DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty);
builder.GetLatestStateTableForNode(callbackNode);
Assert.Same(NodeStateTable<int>.Empty, passedIn);
}
[Fact]
public void Driver_Table_Calls_Into_Node_With_PreviousTable()
{
var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder();
nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Cached);
var newTable = nodeBuilder.ToImmutableAndFree();
NodeStateTable<int>? passedIn = null;
CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) =>
{
passedIn = s;
return newTable;
});
// empty first time
DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty);
builder.GetLatestStateTableForNode(callbackNode);
Assert.Same(NodeStateTable<int>.Empty, passedIn);
// gives the returned table the second time around
DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable());
builder2.GetLatestStateTableForNode(callbackNode);
Assert.NotNull(passedIn);
AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) });
}
[Fact]
public void Driver_Table_Compacts_State_Tables_When_Made_Immutable()
{
var nodeBuilder = NodeStateTable<int>.Empty.ToBuilder();
nodeBuilder.AddEntries(ImmutableArray.Create(1, 2, 3), EntryState.Added);
nodeBuilder.AddEntries(ImmutableArray.Create(4), EntryState.Removed);
nodeBuilder.AddEntries(ImmutableArray.Create(5, 6), EntryState.Modified);
var newTable = nodeBuilder.ToImmutableAndFree();
NodeStateTable<int>? passedIn = null;
CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) =>
{
passedIn = s;
return newTable;
});
// empty first time
DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty);
builder.GetLatestStateTableForNode(callbackNode);
Assert.Same(NodeStateTable<int>.Empty, passedIn);
// gives the returned table the second time around
DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable());
builder2.GetLatestStateTableForNode(callbackNode);
// table returned from the first instance was compacted by the builder
Assert.NotNull(passedIn);
AssertTableEntries(passedIn!, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached), (5, EntryState.Cached), (6, EntryState.Cached) });
}
[Fact]
public void Driver_Table_Builder_Doesnt_Build_Twice()
{
int callCount = 0;
CallbackNode<int> callbackNode = new CallbackNode<int>((b, s) =>
{
callCount++;
return s;
});
// multiple gets will only call it once
DriverStateTable.Builder builder = GetBuilder(DriverStateTable.Empty);
builder.GetLatestStateTableForNode(callbackNode);
builder.GetLatestStateTableForNode(callbackNode);
builder.GetLatestStateTableForNode(callbackNode);
Assert.Equal(1, callCount);
// second time around we'll call it once, but no more
DriverStateTable.Builder builder2 = GetBuilder(builder.ToImmutable());
builder2.GetLatestStateTableForNode(callbackNode);
builder2.GetLatestStateTableForNode(callbackNode);
builder2.GetLatestStateTableForNode(callbackNode);
Assert.Equal(2, callCount);
}
[Fact]
public void Batch_Node_Is_Cached_If_All_Inputs_Are_Cached()
{
var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, 3));
BatchNode<int> batchNode = new BatchNode<int>(inputNode);
// first time through will always be added (because it's not been run before)
DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty);
_ = dstBuilder.GetLatestStateTableForNode(batchNode);
// second time through should show as cached
dstBuilder = GetBuilder(dstBuilder.ToImmutable());
var table = dstBuilder.GetLatestStateTableForNode(batchNode);
AssertTableEntries(table, new[] { (ImmutableArray.Create(1, 2, 3), EntryState.Cached) });
}
[Fact]
public void Batch_Node_Is_Not_Cached_When_Inputs_Are_Changed()
{
int third = 3;
var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, third++));
BatchNode<int> batchNode = new BatchNode<int>(inputNode);
// first time through will always be added (because it's not been run before)
DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty);
_ = dstBuilder.GetLatestStateTableForNode(batchNode);
// second time through should show as modified
dstBuilder = GetBuilder(dstBuilder.ToImmutable());
var table = dstBuilder.GetLatestStateTableForNode(batchNode);
AssertTableEntries(table, new[] { (ImmutableArray.Create(1, 2, 4), EntryState.Modified) });
}
[Fact]
public void User_Comparer_Is_Not_Used_To_Determine_Inputs()
{
var inputNode = new InputNode<int>((_) => ImmutableArray.Create(1, 2, 3))
.WithComparer(new LambdaComparer<int>((a, b) => false));
// first time through will always be added (because it's not been run before)
DriverStateTable.Builder dstBuilder = GetBuilder(DriverStateTable.Empty);
_ = dstBuilder.GetLatestStateTableForNode(inputNode);
// second time through should show as cached, even though we supplied a comparer (comparer should only used to turn modified => cached)
dstBuilder = GetBuilder(dstBuilder.ToImmutable());
var table = dstBuilder.GetLatestStateTableForNode(inputNode);
AssertTableEntries(table, new[] { (1, EntryState.Cached), (2, EntryState.Cached), (3, EntryState.Cached) });
}
private void AssertTableEntries<T>(NodeStateTable<T> table, IList<(T item, EntryState state)> expected)
{
int index = 0;
foreach (var entry in table)
{
Assert.Equal(expected[index].item, entry.item);
Assert.Equal(expected[index].state, entry.state);
index++;
}
}
private void AssertTableEntries<T>(NodeStateTable<ImmutableArray<T>> table, IList<(ImmutableArray<T> item, EntryState state)> expected)
{
int index = 0;
foreach (var entry in table)
{
AssertEx.Equal(expected[index].item, entry.item);
Assert.Equal(expected[index].state, entry.state);
index++;
}
}
private DriverStateTable.Builder GetBuilder(DriverStateTable previous)
{
var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp10);
var c = CSharpCompilation.Create("empty");
var state = new GeneratorDriverState(options,
CompilerAnalyzerConfigOptionsProvider.Empty,
ImmutableArray<ISourceGenerator>.Empty,
ImmutableArray<IIncrementalGenerator>.Empty,
ImmutableArray<AdditionalText>.Empty,
ImmutableArray<GeneratorState>.Empty,
previous,
disabledOutputs: IncrementalGeneratorOutputKind.None);
return new DriverStateTable.Builder(c, state, ImmutableArray<ISyntaxInputNode>.Empty);
}
private class CallbackNode<T> : IIncrementalGeneratorNode<T>
{
private readonly Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> _callback;
public CallbackNode(Func<DriverStateTable.Builder, NodeStateTable<T>, NodeStateTable<T>> callback)
{
_callback = callback;
}
public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken)
{
return _callback(graphState, previousTable);
}
public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => this;
public void RegisterOutput(IIncrementalGeneratorOutputNode output) { }
}
}
}
| 1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/Core/Portable/SourceGeneration/GeneratorDriver.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Responsible for orchestrating a source generation pass
/// </summary>
/// <remarks>
/// GeneratorDriver is an immutable class that can be manipulated by returning a mutated copy of itself.
/// In the compiler we only ever create a single instance and ignore the mutated copy. The IDE may perform
/// multiple edits, or generation passes of the same driver, re-using the state as needed.
/// </remarks>
public abstract class GeneratorDriver
{
internal readonly GeneratorDriverState _state;
internal GeneratorDriver(GeneratorDriverState state)
{
Debug.Assert(state.Generators.GroupBy(s => s.GetGeneratorType()).Count() == state.Generators.Length); // ensure we don't have duplicate generator types
_state = state;
}
internal GeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, bool enableIncremental, GeneratorDriverOptions driverOptions)
{
(var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, enableIncremental);
_state = new GeneratorDriverState(parseOptions, optionsProvider, filteredGenerators, incrementalGenerators, additionalTexts, ImmutableArray.Create(new GeneratorState[filteredGenerators.Length]), DriverStateTable.Empty, enableIncremental, driverOptions.DisabledOutputs);
}
public GeneratorDriver RunGenerators(Compilation compilation, CancellationToken cancellationToken = default)
{
var state = RunGeneratorsCore(compilation, diagnosticsBag: null, cancellationToken); //don't directly collect diagnostics on this path
return FromState(state);
}
public GeneratorDriver RunGeneratorsAndUpdateCompilation(Compilation compilation, out Compilation outputCompilation, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken = default)
{
var diagnosticsBag = DiagnosticBag.GetInstance();
var state = RunGeneratorsCore(compilation, diagnosticsBag, cancellationToken);
// build the output compilation
diagnostics = diagnosticsBag.ToReadOnlyAndFree();
ArrayBuilder<SyntaxTree> trees = ArrayBuilder<SyntaxTree>.GetInstance();
foreach (var generatorState in state.GeneratorStates)
{
trees.AddRange(generatorState.PostInitTrees.Select(t => t.Tree));
trees.AddRange(generatorState.GeneratedTrees.Select(t => t.Tree));
}
outputCompilation = compilation.AddSyntaxTrees(trees);
trees.Free();
return FromState(state);
}
public GeneratorDriver AddGenerators(ImmutableArray<ISourceGenerator> generators)
{
(var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators, _state.EnableIncremental);
var newState = _state.With(sourceGenerators: _state.Generators.AddRange(filteredGenerators),
incrementalGenerators: _state.IncrementalGenerators.AddRange(incrementalGenerators),
generatorStates: _state.GeneratorStates.AddRange(new GeneratorState[filteredGenerators.Length]));
return FromState(newState);
}
public GeneratorDriver RemoveGenerators(ImmutableArray<ISourceGenerator> generators)
{
var newGenerators = _state.Generators;
var newStates = _state.GeneratorStates;
var newIncrementalGenerators = _state.IncrementalGenerators;
for (int i = 0; i < newGenerators.Length; i++)
{
if (generators.Contains(newGenerators[i]))
{
newGenerators = newGenerators.RemoveAt(i);
newStates = newStates.RemoveAt(i);
newIncrementalGenerators = newIncrementalGenerators.RemoveAt(i);
i--;
}
}
return FromState(_state.With(sourceGenerators: newGenerators, incrementalGenerators: newIncrementalGenerators, generatorStates: newStates));
}
public GeneratorDriver AddAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts)
{
var newState = _state.With(additionalTexts: _state.AdditionalTexts.AddRange(additionalTexts));
return FromState(newState);
}
public GeneratorDriver RemoveAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts)
{
var newState = _state.With(additionalTexts: _state.AdditionalTexts.RemoveRange(additionalTexts));
return FromState(newState);
}
public GeneratorDriver ReplaceAdditionalText(AdditionalText oldText, AdditionalText newText)
{
if (oldText is null)
{
throw new ArgumentNullException(nameof(oldText));
}
if (newText is null)
{
throw new ArgumentNullException(nameof(newText));
}
var newState = _state.With(additionalTexts: _state.AdditionalTexts.Replace(oldText, newText));
return FromState(newState);
}
public GeneratorDriver WithUpdatedParseOptions(ParseOptions newOptions) => newOptions is object
? FromState(_state.With(parseOptions: newOptions))
: throw new ArgumentNullException(nameof(newOptions));
public GeneratorDriver WithUpdatedAnalyzerConfigOptions(AnalyzerConfigOptionsProvider newOptions) => newOptions is object
? FromState(_state.With(optionsProvider: newOptions))
: throw new ArgumentNullException(nameof(newOptions));
public GeneratorDriverRunResult GetRunResult()
{
var results = _state.Generators.ZipAsArray(
_state.GeneratorStates,
(generator, generatorState)
=> new GeneratorRunResult(generator,
diagnostics: generatorState.Diagnostics,
exception: generatorState.Exception,
generatedSources: getGeneratorSources(generatorState)));
return new GeneratorDriverRunResult(results);
static ImmutableArray<GeneratedSourceResult> getGeneratorSources(GeneratorState generatorState)
{
ArrayBuilder<GeneratedSourceResult> sources = ArrayBuilder<GeneratedSourceResult>.GetInstance(generatorState.PostInitTrees.Length + generatorState.GeneratedTrees.Length);
foreach (var tree in generatorState.PostInitTrees)
{
sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName));
}
foreach (var tree in generatorState.GeneratedTrees)
{
sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName));
}
return sources.ToImmutableAndFree();
}
}
internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, DiagnosticBag? diagnosticsBag, CancellationToken cancellationToken = default)
{
// with no generators, there is no work to do
if (_state.Generators.IsEmpty)
{
return _state.With(stateTable: DriverStateTable.Empty);
}
// run the actual generation
var state = _state;
var stateBuilder = ArrayBuilder<GeneratorState>.GetInstance(state.Generators.Length);
var constantSourcesBuilder = ArrayBuilder<SyntaxTree>.GetInstance();
var syntaxInputNodes = ArrayBuilder<ISyntaxInputNode>.GetInstance();
for (int i = 0; i < state.IncrementalGenerators.Length; i++)
{
var generator = state.IncrementalGenerators[i];
var generatorState = state.GeneratorStates[i];
var sourceGenerator = state.Generators[i];
// initialize the generator if needed
if (!generatorState.Initialized)
{
var outputBuilder = ArrayBuilder<IIncrementalGeneratorOutputNode>.GetInstance();
var inputBuilder = ArrayBuilder<ISyntaxInputNode>.GetInstance();
var postInitSources = ImmutableArray<GeneratedSyntaxTree>.Empty;
var pipelineContext = new IncrementalGeneratorInitializationContext(inputBuilder, outputBuilder);
Exception? ex = null;
try
{
generator.Initialize(pipelineContext);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
ex = e;
}
var outputNodes = outputBuilder.ToImmutableAndFree();
var inputNodes = inputBuilder.ToImmutableAndFree();
// run post init
if (ex is null)
{
try
{
IncrementalExecutionContext context = UpdateOutputs(outputNodes, IncrementalGeneratorOutputKind.PostInit, cancellationToken);
postInitSources = ParseAdditionalSources(sourceGenerator, context.ToImmutableAndFree().sources, cancellationToken);
}
catch (UserFunctionException e)
{
ex = e.InnerException;
}
}
generatorState = ex is null
? new GeneratorState(generatorState.Info, postInitSources, inputNodes, outputNodes)
: SetGeneratorException(MessageProvider, generatorState, sourceGenerator, ex, diagnosticsBag, isInit: true);
}
// if the pipeline registered any syntax input nodes, record them
if (!generatorState.InputNodes.IsEmpty)
{
syntaxInputNodes.AddRange(generatorState.InputNodes);
}
// record any constant sources
if (generatorState.Exception is null && generatorState.PostInitTrees.Length > 0)
{
constantSourcesBuilder.AddRange(generatorState.PostInitTrees.Select(t => t.Tree));
}
stateBuilder.Add(generatorState);
}
// update the compilation with any constant sources
if (constantSourcesBuilder.Count > 0)
{
compilation = compilation.AddSyntaxTrees(constantSourcesBuilder);
}
constantSourcesBuilder.Free();
var driverStateBuilder = new DriverStateTable.Builder(compilation, _state, syntaxInputNodes.ToImmutableAndFree(), cancellationToken);
for (int i = 0; i < state.IncrementalGenerators.Length; i++)
{
var generatorState = stateBuilder[i];
if (generatorState.Exception is object)
{
continue;
}
try
{
var context = UpdateOutputs(generatorState.OutputNodes, IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation, cancellationToken, driverStateBuilder);
(var sources, var generatorDiagnostics) = context.ToImmutableAndFree();
generatorDiagnostics = FilterDiagnostics(compilation, generatorDiagnostics, driverDiagnostics: diagnosticsBag, cancellationToken);
stateBuilder[i] = new GeneratorState(generatorState.Info, generatorState.PostInitTrees, generatorState.InputNodes, generatorState.OutputNodes, ParseAdditionalSources(state.Generators[i], sources, cancellationToken), generatorDiagnostics);
}
catch (UserFunctionException ufe)
{
stateBuilder[i] = SetGeneratorException(MessageProvider, stateBuilder[i], state.Generators[i], ufe.InnerException, diagnosticsBag);
}
}
state = state.With(stateTable: driverStateBuilder.ToImmutable(), generatorStates: stateBuilder.ToImmutableAndFree());
return state;
}
private IncrementalExecutionContext UpdateOutputs(ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, IncrementalGeneratorOutputKind outputKind, CancellationToken cancellationToken, DriverStateTable.Builder? driverStateBuilder = null)
{
Debug.Assert(outputKind != IncrementalGeneratorOutputKind.None);
IncrementalExecutionContext context = new IncrementalExecutionContext(driverStateBuilder, CreateSourcesCollection());
foreach (var outputNode in outputNodes)
{
// if we're looking for this output kind, and it has not been explicitly disabled
if (outputKind.HasFlag(outputNode.Kind) && !_state.DisabledOutputs.HasFlag(outputNode.Kind))
{
outputNode.AppendOutputs(context, cancellationToken);
}
}
return context;
}
private ImmutableArray<GeneratedSyntaxTree> ParseAdditionalSources(ISourceGenerator generator, ImmutableArray<GeneratedSourceText> generatedSources, CancellationToken cancellationToken)
{
var trees = ArrayBuilder<GeneratedSyntaxTree>.GetInstance(generatedSources.Length);
var type = generator.GetGeneratorType();
var prefix = GetFilePathPrefixForGenerator(generator);
foreach (var source in generatedSources)
{
var tree = ParseGeneratedSourceText(source, Path.Combine(prefix, source.HintName), cancellationToken);
trees.Add(new GeneratedSyntaxTree(source.HintName, source.Text, tree));
}
return trees.ToImmutableAndFree();
}
private static GeneratorState SetGeneratorException(CommonMessageProvider provider, GeneratorState generatorState, ISourceGenerator generator, Exception e, DiagnosticBag? diagnosticBag, bool isInit = false)
{
var errorCode = isInit ? provider.WRN_GeneratorFailedDuringInitialization : provider.WRN_GeneratorFailedDuringGeneration;
// ISSUE: Diagnostics don't currently allow descriptions with arguments, so we have to manually create the diagnostic description
// ISSUE: Exceptions also don't support IFormattable, so will always be in the current UI Culture.
// ISSUE: See https://github.com/dotnet/roslyn/issues/46939
var description = string.Format(provider.GetDescription(errorCode).ToString(CultureInfo.CurrentUICulture), e);
var descriptor = new DiagnosticDescriptor(
provider.GetIdForErrorCode(errorCode),
provider.GetTitle(errorCode),
provider.GetMessageFormat(errorCode),
description: description,
category: "Compiler",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.AnalyzerException);
var diagnostic = Diagnostic.Create(descriptor, Location.None, generator.GetGeneratorType().Name, e.GetType().Name, e.Message);
diagnosticBag?.Add(diagnostic);
return new GeneratorState(generatorState.Info, e, diagnostic);
}
private static ImmutableArray<Diagnostic> FilterDiagnostics(Compilation compilation, ImmutableArray<Diagnostic> generatorDiagnostics, DiagnosticBag? driverDiagnostics, CancellationToken cancellationToken)
{
ArrayBuilder<Diagnostic> filteredDiagnostics = ArrayBuilder<Diagnostic>.GetInstance();
foreach (var diag in generatorDiagnostics)
{
var filtered = compilation.Options.FilterDiagnostic(diag, cancellationToken);
if (filtered is object)
{
filteredDiagnostics.Add(filtered);
driverDiagnostics?.Add(filtered);
}
}
return filteredDiagnostics.ToImmutableAndFree();
}
internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator)
{
var type = generator.GetGeneratorType();
return Path.Combine(type.Assembly.GetName().Name ?? string.Empty, type.FullName!);
}
private static (ImmutableArray<ISourceGenerator>, ImmutableArray<IIncrementalGenerator>) GetIncrementalGenerators(ImmutableArray<ISourceGenerator> generators, bool enableIncremental)
{
if (enableIncremental)
{
return (generators, generators.SelectAsArray(g => g switch
{
IncrementalGeneratorWrapper igw => igw.Generator,
IIncrementalGenerator ig => ig,
_ => new SourceGeneratorAdaptor(g)
}));
}
else
{
var filtered = generators.WhereAsArray(g => g is not IncrementalGeneratorWrapper);
return (filtered, filtered.SelectAsArray<ISourceGenerator, IIncrementalGenerator>(g => new SourceGeneratorAdaptor(g)));
}
}
internal abstract CommonMessageProvider MessageProvider { get; }
internal abstract GeneratorDriver FromState(GeneratorDriverState state);
internal abstract SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken);
internal abstract AdditionalSourcesCollection CreateSourcesCollection();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Responsible for orchestrating a source generation pass
/// </summary>
/// <remarks>
/// GeneratorDriver is an immutable class that can be manipulated by returning a mutated copy of itself.
/// In the compiler we only ever create a single instance and ignore the mutated copy. The IDE may perform
/// multiple edits, or generation passes of the same driver, re-using the state as needed.
/// </remarks>
public abstract class GeneratorDriver
{
internal readonly GeneratorDriverState _state;
internal GeneratorDriver(GeneratorDriverState state)
{
Debug.Assert(state.Generators.GroupBy(s => s.GetGeneratorType()).Count() == state.Generators.Length); // ensure we don't have duplicate generator types
_state = state;
}
internal GeneratorDriver(ParseOptions parseOptions, ImmutableArray<ISourceGenerator> generators, AnalyzerConfigOptionsProvider optionsProvider, ImmutableArray<AdditionalText> additionalTexts, GeneratorDriverOptions driverOptions)
{
(var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators);
_state = new GeneratorDriverState(parseOptions, optionsProvider, filteredGenerators, incrementalGenerators, additionalTexts, ImmutableArray.Create(new GeneratorState[filteredGenerators.Length]), DriverStateTable.Empty, driverOptions.DisabledOutputs);
}
public GeneratorDriver RunGenerators(Compilation compilation, CancellationToken cancellationToken = default)
{
var state = RunGeneratorsCore(compilation, diagnosticsBag: null, cancellationToken); //don't directly collect diagnostics on this path
return FromState(state);
}
public GeneratorDriver RunGeneratorsAndUpdateCompilation(Compilation compilation, out Compilation outputCompilation, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken = default)
{
var diagnosticsBag = DiagnosticBag.GetInstance();
var state = RunGeneratorsCore(compilation, diagnosticsBag, cancellationToken);
// build the output compilation
diagnostics = diagnosticsBag.ToReadOnlyAndFree();
ArrayBuilder<SyntaxTree> trees = ArrayBuilder<SyntaxTree>.GetInstance();
foreach (var generatorState in state.GeneratorStates)
{
trees.AddRange(generatorState.PostInitTrees.Select(t => t.Tree));
trees.AddRange(generatorState.GeneratedTrees.Select(t => t.Tree));
}
outputCompilation = compilation.AddSyntaxTrees(trees);
trees.Free();
return FromState(state);
}
public GeneratorDriver AddGenerators(ImmutableArray<ISourceGenerator> generators)
{
(var filteredGenerators, var incrementalGenerators) = GetIncrementalGenerators(generators);
var newState = _state.With(sourceGenerators: _state.Generators.AddRange(filteredGenerators),
incrementalGenerators: _state.IncrementalGenerators.AddRange(incrementalGenerators),
generatorStates: _state.GeneratorStates.AddRange(new GeneratorState[filteredGenerators.Length]));
return FromState(newState);
}
public GeneratorDriver RemoveGenerators(ImmutableArray<ISourceGenerator> generators)
{
var newGenerators = _state.Generators;
var newStates = _state.GeneratorStates;
var newIncrementalGenerators = _state.IncrementalGenerators;
for (int i = 0; i < newGenerators.Length; i++)
{
if (generators.Contains(newGenerators[i]))
{
newGenerators = newGenerators.RemoveAt(i);
newStates = newStates.RemoveAt(i);
newIncrementalGenerators = newIncrementalGenerators.RemoveAt(i);
i--;
}
}
return FromState(_state.With(sourceGenerators: newGenerators, incrementalGenerators: newIncrementalGenerators, generatorStates: newStates));
}
public GeneratorDriver AddAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts)
{
var newState = _state.With(additionalTexts: _state.AdditionalTexts.AddRange(additionalTexts));
return FromState(newState);
}
public GeneratorDriver RemoveAdditionalTexts(ImmutableArray<AdditionalText> additionalTexts)
{
var newState = _state.With(additionalTexts: _state.AdditionalTexts.RemoveRange(additionalTexts));
return FromState(newState);
}
public GeneratorDriver ReplaceAdditionalText(AdditionalText oldText, AdditionalText newText)
{
if (oldText is null)
{
throw new ArgumentNullException(nameof(oldText));
}
if (newText is null)
{
throw new ArgumentNullException(nameof(newText));
}
var newState = _state.With(additionalTexts: _state.AdditionalTexts.Replace(oldText, newText));
return FromState(newState);
}
public GeneratorDriver WithUpdatedParseOptions(ParseOptions newOptions) => newOptions is object
? FromState(_state.With(parseOptions: newOptions))
: throw new ArgumentNullException(nameof(newOptions));
public GeneratorDriver WithUpdatedAnalyzerConfigOptions(AnalyzerConfigOptionsProvider newOptions) => newOptions is object
? FromState(_state.With(optionsProvider: newOptions))
: throw new ArgumentNullException(nameof(newOptions));
public GeneratorDriverRunResult GetRunResult()
{
var results = _state.Generators.ZipAsArray(
_state.GeneratorStates,
(generator, generatorState)
=> new GeneratorRunResult(generator,
diagnostics: generatorState.Diagnostics,
exception: generatorState.Exception,
generatedSources: getGeneratorSources(generatorState)));
return new GeneratorDriverRunResult(results);
static ImmutableArray<GeneratedSourceResult> getGeneratorSources(GeneratorState generatorState)
{
ArrayBuilder<GeneratedSourceResult> sources = ArrayBuilder<GeneratedSourceResult>.GetInstance(generatorState.PostInitTrees.Length + generatorState.GeneratedTrees.Length);
foreach (var tree in generatorState.PostInitTrees)
{
sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName));
}
foreach (var tree in generatorState.GeneratedTrees)
{
sources.Add(new GeneratedSourceResult(tree.Tree, tree.Text, tree.HintName));
}
return sources.ToImmutableAndFree();
}
}
internal GeneratorDriverState RunGeneratorsCore(Compilation compilation, DiagnosticBag? diagnosticsBag, CancellationToken cancellationToken = default)
{
// with no generators, there is no work to do
if (_state.Generators.IsEmpty)
{
return _state.With(stateTable: DriverStateTable.Empty);
}
// run the actual generation
var state = _state;
var stateBuilder = ArrayBuilder<GeneratorState>.GetInstance(state.Generators.Length);
var constantSourcesBuilder = ArrayBuilder<SyntaxTree>.GetInstance();
var syntaxInputNodes = ArrayBuilder<ISyntaxInputNode>.GetInstance();
for (int i = 0; i < state.IncrementalGenerators.Length; i++)
{
var generator = state.IncrementalGenerators[i];
var generatorState = state.GeneratorStates[i];
var sourceGenerator = state.Generators[i];
// initialize the generator if needed
if (!generatorState.Initialized)
{
var outputBuilder = ArrayBuilder<IIncrementalGeneratorOutputNode>.GetInstance();
var inputBuilder = ArrayBuilder<ISyntaxInputNode>.GetInstance();
var postInitSources = ImmutableArray<GeneratedSyntaxTree>.Empty;
var pipelineContext = new IncrementalGeneratorInitializationContext(inputBuilder, outputBuilder);
Exception? ex = null;
try
{
generator.Initialize(pipelineContext);
}
catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken))
{
ex = e;
}
var outputNodes = outputBuilder.ToImmutableAndFree();
var inputNodes = inputBuilder.ToImmutableAndFree();
// run post init
if (ex is null)
{
try
{
IncrementalExecutionContext context = UpdateOutputs(outputNodes, IncrementalGeneratorOutputKind.PostInit, cancellationToken);
postInitSources = ParseAdditionalSources(sourceGenerator, context.ToImmutableAndFree().sources, cancellationToken);
}
catch (UserFunctionException e)
{
ex = e.InnerException;
}
}
generatorState = ex is null
? new GeneratorState(generatorState.Info, postInitSources, inputNodes, outputNodes)
: SetGeneratorException(MessageProvider, generatorState, sourceGenerator, ex, diagnosticsBag, isInit: true);
}
// if the pipeline registered any syntax input nodes, record them
if (!generatorState.InputNodes.IsEmpty)
{
syntaxInputNodes.AddRange(generatorState.InputNodes);
}
// record any constant sources
if (generatorState.Exception is null && generatorState.PostInitTrees.Length > 0)
{
constantSourcesBuilder.AddRange(generatorState.PostInitTrees.Select(t => t.Tree));
}
stateBuilder.Add(generatorState);
}
// update the compilation with any constant sources
if (constantSourcesBuilder.Count > 0)
{
compilation = compilation.AddSyntaxTrees(constantSourcesBuilder);
}
constantSourcesBuilder.Free();
var driverStateBuilder = new DriverStateTable.Builder(compilation, _state, syntaxInputNodes.ToImmutableAndFree(), cancellationToken);
for (int i = 0; i < state.IncrementalGenerators.Length; i++)
{
var generatorState = stateBuilder[i];
if (generatorState.Exception is object)
{
continue;
}
try
{
var context = UpdateOutputs(generatorState.OutputNodes, IncrementalGeneratorOutputKind.Source | IncrementalGeneratorOutputKind.Implementation, cancellationToken, driverStateBuilder);
(var sources, var generatorDiagnostics) = context.ToImmutableAndFree();
generatorDiagnostics = FilterDiagnostics(compilation, generatorDiagnostics, driverDiagnostics: diagnosticsBag, cancellationToken);
stateBuilder[i] = new GeneratorState(generatorState.Info, generatorState.PostInitTrees, generatorState.InputNodes, generatorState.OutputNodes, ParseAdditionalSources(state.Generators[i], sources, cancellationToken), generatorDiagnostics);
}
catch (UserFunctionException ufe)
{
stateBuilder[i] = SetGeneratorException(MessageProvider, stateBuilder[i], state.Generators[i], ufe.InnerException, diagnosticsBag);
}
}
state = state.With(stateTable: driverStateBuilder.ToImmutable(), generatorStates: stateBuilder.ToImmutableAndFree());
return state;
}
private IncrementalExecutionContext UpdateOutputs(ImmutableArray<IIncrementalGeneratorOutputNode> outputNodes, IncrementalGeneratorOutputKind outputKind, CancellationToken cancellationToken, DriverStateTable.Builder? driverStateBuilder = null)
{
Debug.Assert(outputKind != IncrementalGeneratorOutputKind.None);
IncrementalExecutionContext context = new IncrementalExecutionContext(driverStateBuilder, CreateSourcesCollection());
foreach (var outputNode in outputNodes)
{
// if we're looking for this output kind, and it has not been explicitly disabled
if (outputKind.HasFlag(outputNode.Kind) && !_state.DisabledOutputs.HasFlag(outputNode.Kind))
{
outputNode.AppendOutputs(context, cancellationToken);
}
}
return context;
}
private ImmutableArray<GeneratedSyntaxTree> ParseAdditionalSources(ISourceGenerator generator, ImmutableArray<GeneratedSourceText> generatedSources, CancellationToken cancellationToken)
{
var trees = ArrayBuilder<GeneratedSyntaxTree>.GetInstance(generatedSources.Length);
var type = generator.GetGeneratorType();
var prefix = GetFilePathPrefixForGenerator(generator);
foreach (var source in generatedSources)
{
var tree = ParseGeneratedSourceText(source, Path.Combine(prefix, source.HintName), cancellationToken);
trees.Add(new GeneratedSyntaxTree(source.HintName, source.Text, tree));
}
return trees.ToImmutableAndFree();
}
private static GeneratorState SetGeneratorException(CommonMessageProvider provider, GeneratorState generatorState, ISourceGenerator generator, Exception e, DiagnosticBag? diagnosticBag, bool isInit = false)
{
var errorCode = isInit ? provider.WRN_GeneratorFailedDuringInitialization : provider.WRN_GeneratorFailedDuringGeneration;
// ISSUE: Diagnostics don't currently allow descriptions with arguments, so we have to manually create the diagnostic description
// ISSUE: Exceptions also don't support IFormattable, so will always be in the current UI Culture.
// ISSUE: See https://github.com/dotnet/roslyn/issues/46939
var description = string.Format(provider.GetDescription(errorCode).ToString(CultureInfo.CurrentUICulture), e);
var descriptor = new DiagnosticDescriptor(
provider.GetIdForErrorCode(errorCode),
provider.GetTitle(errorCode),
provider.GetMessageFormat(errorCode),
description: description,
category: "Compiler",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
customTags: WellKnownDiagnosticTags.AnalyzerException);
var diagnostic = Diagnostic.Create(descriptor, Location.None, generator.GetGeneratorType().Name, e.GetType().Name, e.Message);
diagnosticBag?.Add(diagnostic);
return new GeneratorState(generatorState.Info, e, diagnostic);
}
private static ImmutableArray<Diagnostic> FilterDiagnostics(Compilation compilation, ImmutableArray<Diagnostic> generatorDiagnostics, DiagnosticBag? driverDiagnostics, CancellationToken cancellationToken)
{
ArrayBuilder<Diagnostic> filteredDiagnostics = ArrayBuilder<Diagnostic>.GetInstance();
foreach (var diag in generatorDiagnostics)
{
var filtered = compilation.Options.FilterDiagnostic(diag, cancellationToken);
if (filtered is object)
{
filteredDiagnostics.Add(filtered);
driverDiagnostics?.Add(filtered);
}
}
return filteredDiagnostics.ToImmutableAndFree();
}
internal static string GetFilePathPrefixForGenerator(ISourceGenerator generator)
{
var type = generator.GetGeneratorType();
return Path.Combine(type.Assembly.GetName().Name ?? string.Empty, type.FullName!);
}
private static (ImmutableArray<ISourceGenerator>, ImmutableArray<IIncrementalGenerator>) GetIncrementalGenerators(ImmutableArray<ISourceGenerator> generators)
{
return (generators, generators.SelectAsArray(g => g switch
{
IncrementalGeneratorWrapper igw => igw.Generator,
IIncrementalGenerator ig => ig,
_ => new SourceGeneratorAdaptor(g)
}));
}
internal abstract CommonMessageProvider MessageProvider { get; }
internal abstract GeneratorDriver FromState(GeneratorDriverState state);
internal abstract SyntaxTree ParseGeneratedSourceText(GeneratedSourceText input, string fileName, CancellationToken cancellationToken);
internal abstract AdditionalSourcesCollection CreateSourcesCollection();
}
}
| 1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/Core/Portable/SourceGeneration/GeneratorDriverState.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis
{
internal readonly struct GeneratorDriverState
{
internal GeneratorDriverState(ParseOptions parseOptions,
AnalyzerConfigOptionsProvider optionsProvider,
ImmutableArray<ISourceGenerator> sourceGenerators,
ImmutableArray<IIncrementalGenerator> incrementalGenerators,
ImmutableArray<AdditionalText> additionalTexts,
ImmutableArray<GeneratorState> generatorStates,
DriverStateTable stateTable,
bool enableIncremental,
IncrementalGeneratorOutputKind disabledOutputs)
{
Generators = sourceGenerators;
IncrementalGenerators = incrementalGenerators;
GeneratorStates = generatorStates;
AdditionalTexts = additionalTexts;
ParseOptions = parseOptions;
OptionsProvider = optionsProvider;
StateTable = stateTable;
EnableIncremental = enableIncremental;
DisabledOutputs = disabledOutputs;
Debug.Assert(Generators.Length == GeneratorStates.Length);
Debug.Assert(IncrementalGenerators.Length == GeneratorStates.Length);
}
/// <summary>
/// The set of <see cref="ISourceGenerator"/>s associated with this state.
/// </summary>
/// <remarks>
/// This is the set of generators that will run on next generation.
/// If there are any states present in <see cref="GeneratorStates" />, they were produced by a subset of these generators.
/// </remarks>
internal readonly ImmutableArray<ISourceGenerator> Generators;
/// <summary>
/// The set of <see cref="IIncrementalGenerator"/>s associated with this state.
/// </summary>
/// <remarks>
/// This is the 'internal' representation of the <see cref="Generators"/> collection. There is a 1-to-1 mapping
/// where each entry is either the unwrapped incremental generator or a wrapped <see cref="ISourceGenerator"/>
/// </remarks>
internal readonly ImmutableArray<IIncrementalGenerator> IncrementalGenerators;
/// <summary>
/// The last run state of each generator, by the generator that created it
/// </summary>
/// <remarks>
/// There will be a 1-to-1 mapping for each generator. If a generator has yet to
/// be initialized or failed during initialization it's state will be <c>default(GeneratorState)</c>
/// </remarks>
internal readonly ImmutableArray<GeneratorState> GeneratorStates;
/// <summary>
/// The set of <see cref="AdditionalText"/>s available to source generators during a run
/// </summary>
internal readonly ImmutableArray<AdditionalText> AdditionalTexts;
/// <summary>
/// Gets a provider for analyzer options
/// </summary>
internal readonly AnalyzerConfigOptionsProvider OptionsProvider;
/// <summary>
/// ParseOptions to use when parsing generator provided source.
/// </summary>
internal readonly ParseOptions ParseOptions;
internal readonly DriverStateTable StateTable;
/// <summary>
/// Should this driver run incremental generators or not
/// </summary>
/// <remarks>
/// Only used during preview period when incremental generators are enabled/disabled by preview flag
/// </remarks>
internal readonly bool EnableIncremental;
/// <summary>
/// A bit field containing the output kinds that should not be produced by this generator driver.
/// </summary>
internal readonly IncrementalGeneratorOutputKind DisabledOutputs;
internal GeneratorDriverState With(
ImmutableArray<ISourceGenerator>? sourceGenerators = null,
ImmutableArray<IIncrementalGenerator>? incrementalGenerators = null,
ImmutableArray<GeneratorState>? generatorStates = null,
ImmutableArray<AdditionalText>? additionalTexts = null,
DriverStateTable? stateTable = null,
ParseOptions? parseOptions = null,
AnalyzerConfigOptionsProvider? optionsProvider = null,
IncrementalGeneratorOutputKind? disabledOutputs = null)
{
return new GeneratorDriverState(
parseOptions ?? this.ParseOptions,
optionsProvider ?? this.OptionsProvider,
sourceGenerators ?? this.Generators,
incrementalGenerators ?? this.IncrementalGenerators,
additionalTexts ?? this.AdditionalTexts,
generatorStates ?? this.GeneratorStates,
stateTable ?? this.StateTable,
this.EnableIncremental,
disabledOutputs ?? this.DisabledOutputs
);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis
{
internal readonly struct GeneratorDriverState
{
internal GeneratorDriverState(ParseOptions parseOptions,
AnalyzerConfigOptionsProvider optionsProvider,
ImmutableArray<ISourceGenerator> sourceGenerators,
ImmutableArray<IIncrementalGenerator> incrementalGenerators,
ImmutableArray<AdditionalText> additionalTexts,
ImmutableArray<GeneratorState> generatorStates,
DriverStateTable stateTable,
IncrementalGeneratorOutputKind disabledOutputs)
{
Generators = sourceGenerators;
IncrementalGenerators = incrementalGenerators;
GeneratorStates = generatorStates;
AdditionalTexts = additionalTexts;
ParseOptions = parseOptions;
OptionsProvider = optionsProvider;
StateTable = stateTable;
DisabledOutputs = disabledOutputs;
Debug.Assert(Generators.Length == GeneratorStates.Length);
Debug.Assert(IncrementalGenerators.Length == GeneratorStates.Length);
}
/// <summary>
/// The set of <see cref="ISourceGenerator"/>s associated with this state.
/// </summary>
/// <remarks>
/// This is the set of generators that will run on next generation.
/// If there are any states present in <see cref="GeneratorStates" />, they were produced by a subset of these generators.
/// </remarks>
internal readonly ImmutableArray<ISourceGenerator> Generators;
/// <summary>
/// The set of <see cref="IIncrementalGenerator"/>s associated with this state.
/// </summary>
/// <remarks>
/// This is the 'internal' representation of the <see cref="Generators"/> collection. There is a 1-to-1 mapping
/// where each entry is either the unwrapped incremental generator or a wrapped <see cref="ISourceGenerator"/>
/// </remarks>
internal readonly ImmutableArray<IIncrementalGenerator> IncrementalGenerators;
/// <summary>
/// The last run state of each generator, by the generator that created it
/// </summary>
/// <remarks>
/// There will be a 1-to-1 mapping for each generator. If a generator has yet to
/// be initialized or failed during initialization it's state will be <c>default(GeneratorState)</c>
/// </remarks>
internal readonly ImmutableArray<GeneratorState> GeneratorStates;
/// <summary>
/// The set of <see cref="AdditionalText"/>s available to source generators during a run
/// </summary>
internal readonly ImmutableArray<AdditionalText> AdditionalTexts;
/// <summary>
/// Gets a provider for analyzer options
/// </summary>
internal readonly AnalyzerConfigOptionsProvider OptionsProvider;
/// <summary>
/// ParseOptions to use when parsing generator provided source.
/// </summary>
internal readonly ParseOptions ParseOptions;
internal readonly DriverStateTable StateTable;
/// <summary>
/// A bit field containing the output kinds that should not be produced by this generator driver.
/// </summary>
internal readonly IncrementalGeneratorOutputKind DisabledOutputs;
internal GeneratorDriverState With(
ImmutableArray<ISourceGenerator>? sourceGenerators = null,
ImmutableArray<IIncrementalGenerator>? incrementalGenerators = null,
ImmutableArray<GeneratorState>? generatorStates = null,
ImmutableArray<AdditionalText>? additionalTexts = null,
DriverStateTable? stateTable = null,
ParseOptions? parseOptions = null,
AnalyzerConfigOptionsProvider? optionsProvider = null,
IncrementalGeneratorOutputKind? disabledOutputs = null)
{
return new GeneratorDriverState(
parseOptions ?? this.ParseOptions,
optionsProvider ?? this.OptionsProvider,
sourceGenerators ?? this.Generators,
incrementalGenerators ?? this.IncrementalGenerators,
additionalTexts ?? this.AdditionalTexts,
generatorStates ?? this.GeneratorStates,
stateTable ?? this.StateTable,
disabledOutputs ?? this.DisabledOutputs
);
}
}
}
| 1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/VisualBasic/Portable/SourceGeneration/VisualBasicGeneratorDriver.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.ComponentModel
Imports System.Threading
Imports Microsoft.CodeAnalysis.Diagnostics
Namespace Microsoft.CodeAnalysis.VisualBasic
Public Class VisualBasicGeneratorDriver
Inherits GeneratorDriver
Private Sub New(state As GeneratorDriverState)
MyBase.New(state)
End Sub
Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), driverOptions As GeneratorDriverOptions)
MyBase.New(parseOptions, generators, optionsProvider, additionalTexts, enableIncremental:=False, driverOptions)
End Sub
Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider
Get
Return VisualBasic.MessageProvider.Instance
End Get
End Property
Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver
Return New VisualBasicGeneratorDriver(state)
End Function
Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree
Return VisualBasicSyntaxTree.ParseTextLazy(input.Text, CType(_state.ParseOptions, VisualBasicParseOptions), fileName)
End Function
Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing, Optional driverOptions As GeneratorDriverOptions = Nothing) As VisualBasicGeneratorDriver
Return New VisualBasicGeneratorDriver(parseOptions, generators, If(analyzerConfigOptionsProvider, CompilerAnalyzerConfigOptionsProvider.Empty), additionalTexts.NullToEmpty(), driverOptions)
End Function
' 3.11 BACK COMPAT OVERLOAD -- DO NOT TOUCH
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), additionalTexts As ImmutableArray(Of AdditionalText), parseOptions As VisualBasicParseOptions, analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As VisualBasicGeneratorDriver
Return Create(generators, additionalTexts, parseOptions, analyzerConfigOptionsProvider, driverOptions:=Nothing)
End Function
Friend Overrides Function CreateSourcesCollection() As AdditionalSourcesCollection
Return New AdditionalSourcesCollection(".vb")
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.ComponentModel
Imports System.Threading
Imports Microsoft.CodeAnalysis.Diagnostics
Namespace Microsoft.CodeAnalysis.VisualBasic
Public Class VisualBasicGeneratorDriver
Inherits GeneratorDriver
Private Sub New(state As GeneratorDriverState)
MyBase.New(state)
End Sub
Friend Sub New(parseOptions As VisualBasicParseOptions, generators As ImmutableArray(Of ISourceGenerator), optionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), driverOptions As GeneratorDriverOptions)
MyBase.New(parseOptions, generators, optionsProvider, additionalTexts, driverOptions)
End Sub
Friend Overrides ReadOnly Property MessageProvider As CommonMessageProvider
Get
Return VisualBasic.MessageProvider.Instance
End Get
End Property
Friend Overrides Function FromState(state As GeneratorDriverState) As GeneratorDriver
Return New VisualBasicGeneratorDriver(state)
End Function
Friend Overrides Function ParseGeneratedSourceText(input As GeneratedSourceText, fileName As String, cancellationToken As CancellationToken) As SyntaxTree
Return VisualBasicSyntaxTree.ParseTextLazy(input.Text, CType(_state.ParseOptions, VisualBasicParseOptions), fileName)
End Function
Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), Optional additionalTexts As ImmutableArray(Of AdditionalText) = Nothing, Optional parseOptions As VisualBasicParseOptions = Nothing, Optional analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider = Nothing, Optional driverOptions As GeneratorDriverOptions = Nothing) As VisualBasicGeneratorDriver
Return New VisualBasicGeneratorDriver(parseOptions, generators, If(analyzerConfigOptionsProvider, CompilerAnalyzerConfigOptionsProvider.Empty), additionalTexts.NullToEmpty(), driverOptions)
End Function
' 3.11 BACK COMPAT OVERLOAD -- DO NOT TOUCH
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shared Function Create(generators As ImmutableArray(Of ISourceGenerator), additionalTexts As ImmutableArray(Of AdditionalText), parseOptions As VisualBasicParseOptions, analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider) As VisualBasicGeneratorDriver
Return Create(generators, additionalTexts, parseOptions, analyzerConfigOptionsProvider, driverOptions:=Nothing)
End Function
Friend Overrides Function CreateSourcesCollection() As AdditionalSourcesCollection
Return New AdditionalSourcesCollection(".vb")
End Function
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/VisualBasic/Test/Semantic/SourceGeneration/GeneratorDriverTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities.TestGenerators
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class GeneratorDriverTests
Inherits BasicTestBase
<Fact>
Public Sub Single_File_Is_Added()
Dim generatorSource = "
Public Class GeneratedClass
End Class
"
Dim parseOptions = TestOptions.Regular
Dim compilation = GetCompilation(parseOptions)
Dim testGenerator As SingleFileTestGenerator = New SingleFileTestGenerator(generatorSource)
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
Assert.Equal(2, outputCompilation.SyntaxTrees.Count())
Assert.NotEqual(compilation, outputCompilation)
End Sub
<Fact>
Public Sub Can_Access_Additional_Files()
Dim additionalText = New InMemoryAdditionalText("a\\file1.cs", "Hello World")
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i)
End Sub,
Sub(e) Assert.Equal("Hello World", e.AdditionalFiles.First().GetText().ToString()))
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator),
additionalTexts:=ImmutableArray.Create(Of AdditionalText)(additionalText),
parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
End Sub
<Fact>
Public Sub Generator_Can_Be_Written_In_Visual_Basic()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As VBGenerator = New VBGenerator()
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
Assert.Equal(2, outputCompilation.SyntaxTrees.Count())
Assert.NotEqual(compilation, outputCompilation)
End Sub
<Fact>
Public Sub Generator_Can_See_Syntax()
Dim source = "
Imports System
Namespace ANamespace
Public Class AClass
Public Sub AMethod(p as String)
Throw New InvalidOperationException()
End Sub
End Class
End Namespace
"
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions, source)
Dim testGenerator As VBGenerator = New VBGenerator()
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
Assert.Equal(23, testGenerator._receiver._nodes.Count)
Assert.IsType(GetType(CompilationUnitSyntax), testGenerator._receiver._nodes(0))
Assert.IsType(GetType(ClassStatementSyntax), testGenerator._receiver._nodes(8))
Assert.IsType(GetType(ThrowStatementSyntax), testGenerator._receiver._nodes(16))
Assert.IsType(GetType(EndBlockStatementSyntax), testGenerator._receiver._nodes(22))
End Sub
<Fact>
Public Sub Exception_During_Init()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) Throw New Exception("Init Exception"),
Sub(e)
End Sub)
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify(
Diagnostic("BC42501").WithArguments("CallbackGenerator", "Exception", "Init Exception").WithLocation(1, 1)
)
End Sub
<Fact>
Public Sub Exception_During_Execute()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i)
End Sub,
Sub(e) Throw New Exception("Generate Exception"))
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify(
Diagnostic("BC42502").WithArguments("CallbackGenerator", "Exception", "Generate Exception").WithLocation(1, 1)
)
End Sub
<Fact>
Public Sub Exception_During_SyntaxWalk()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As VBGenerator = New VBGenerator()
testGenerator._receiver._throw = True
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify(
Diagnostic("BC42502").WithArguments("VBGenerator", "Exception", "Syntax Walk").WithLocation(1, 1)
)
End Sub
<Fact>
Public Sub SyntaxTrees_Are_Lazy()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator = New SingleFileTestGenerator("Class C : End Class")
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
driver = driver.RunGenerators(compilation)
Dim results = driver.GetRunResult()
Dim tree = Assert.Single(results.GeneratedTrees)
Dim rootFromTryGetRoot As SyntaxNode = Nothing
Assert.False(tree.TryGetRoot(rootFromTryGetRoot))
Dim rootFromGetRoot = tree.GetRoot()
Assert.NotNull(rootFromGetRoot)
Assert.True(tree.TryGetRoot(rootFromTryGetRoot))
Assert.Same(rootFromGetRoot, rootFromTryGetRoot)
End Sub
<Fact>
Public Sub Diagnostics_Respect_Suppression()
Dim compilation As Compilation = GetCompilation(TestOptions.Regular)
Dim gen As CallbackGenerator = New CallbackGenerator(Sub(c)
End Sub,
Sub(c)
c.ReportDiagnostic(VBDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 2))
c.ReportDiagnostic(VBDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 3))
End Sub)
VerifyDiagnosticsWithOptions(gen, compilation,
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1))
Dim warnings As IDictionary(Of String, ReportDiagnostic) = New Dictionary(Of String, ReportDiagnostic)()
warnings.Add("GEN001", ReportDiagnostic.Suppress)
VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)),
Diagnostic("GEN002").WithLocation(1, 1))
warnings.Clear()
warnings.Add("GEN002", ReportDiagnostic.Suppress)
VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)),
Diagnostic("GEN001").WithLocation(1, 1))
warnings.Clear()
warnings.Add("GEN001", ReportDiagnostic.Error)
VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)),
Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(True),
Diagnostic("GEN002").WithLocation(1, 1))
warnings.Clear()
warnings.Add("GEN002", ReportDiagnostic.Error)
VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(True))
End Sub
<Fact>
Public Sub Diagnostics_Respect_Pragma_Suppression()
Dim gen001 = VBDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 2)
VerifyDiagnosticsWithSource("'comment",
gen001, TextSpan.FromBounds(1, 4),
Diagnostic("GEN001", "com").WithLocation(1, 2))
VerifyDiagnosticsWithSource("#disable warning
'comment",
gen001, TextSpan.FromBounds(19, 22),
Diagnostic("GEN001", "com", isSuppressed:=True).WithLocation(2, 2))
VerifyDiagnosticsWithSource("#disable warning
'comment",
gen001, New TextSpan(0, 0),
Diagnostic("GEN001").WithLocation(1, 1))
VerifyDiagnosticsWithSource("#disable warning GEN001
'comment",
gen001, TextSpan.FromBounds(26, 29),
Diagnostic("GEN001", "com", isSuppressed:=True).WithLocation(2, 2))
VerifyDiagnosticsWithSource("#disable warning GEN001
'comment
#enable warning GEN001
'another",
gen001, TextSpan.FromBounds(60, 63),
Diagnostic("GEN001", "ano").WithLocation(4, 2))
End Sub
<Fact>
Public Sub Does_Not_Enable_Incremental_Generators()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As VBIncrementalGenerator = New VBIncrementalGenerator()
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(New IncrementalGeneratorWrapper(testGenerator)), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
Assert.Equal(1, outputCompilation.SyntaxTrees.Count())
Assert.Equal(compilation, compilation)
Assert.False(testGenerator._initialized)
End Sub
<Fact>
Public Sub Does_Not_Prefer_Incremental_Generators()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As VBIncrementalAndSourceGenerator = New VBIncrementalAndSourceGenerator()
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
Assert.Equal(1, outputCompilation.SyntaxTrees.Count())
Assert.Equal(compilation, compilation)
Assert.False(testGenerator._initialized)
Assert.True(testGenerator._sourceInitialized)
Assert.True(testGenerator._sourceExecuted)
End Sub
Shared Function GetCompilation(parseOptions As VisualBasicParseOptions, Optional source As String = "") As Compilation
If (String.IsNullOrWhiteSpace(source)) Then
source = "
Public Class C
End Class
"
End If
Dim compilation As Compilation = CreateCompilation(source, options:=TestOptions.DebugDll, parseOptions:=parseOptions)
compilation.VerifyDiagnostics()
Assert.Single(compilation.SyntaxTrees)
Return compilation
End Function
Shared Sub VerifyDiagnosticsWithOptions(generator As ISourceGenerator, compilation As Compilation, ParamArray expected As DiagnosticDescription())
compilation.VerifyDiagnostics()
Assert.Single(compilation.SyntaxTrees)
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(generator), parseOptions:=TestOptions.Regular)
Dim outputCompilation As Compilation = Nothing
Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, diagnostics)
outputCompilation.VerifyDiagnostics()
diagnostics.Verify(expected)
End Sub
Shared Sub VerifyDiagnosticsWithSource(source As String, diag As Diagnostic, location As TextSpan, ParamArray expected As DiagnosticDescription())
Dim parseOptions = TestOptions.Regular
source = source.Replace(Environment.NewLine, vbCrLf)
Dim compilation As Compilation = CreateCompilation(source)
compilation.VerifyDiagnostics()
Assert.Single(compilation.SyntaxTrees)
Dim gen As ISourceGenerator = New CallbackGenerator(Sub(c)
End Sub,
Sub(c)
If location.IsEmpty Then
c.ReportDiagnostic(diag)
Else
c.ReportDiagnostic(diag.WithLocation(CodeAnalysis.Location.Create(c.Compilation.SyntaxTrees.First(), location)))
End If
End Sub)
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions:=TestOptions.Regular)
Dim outputCompilation As Compilation = Nothing
Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, diagnostics)
outputCompilation.VerifyDiagnostics()
diagnostics.Verify(expected)
End Sub
End Class
<Generator(LanguageNames.VisualBasic)>
Friend Class VBGenerator
Implements ISourceGenerator
Public _receiver As Receiver = New Receiver()
Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize
context.RegisterForSyntaxNotifications(Function() _receiver)
End Sub
Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute
context.AddSource("source.vb", "
Public Class D
End Class
")
End Sub
Class Receiver
Implements ISyntaxReceiver
Public _throw As Boolean
Public _nodes As List(Of SyntaxNode) = New List(Of SyntaxNode)()
Public Sub OnVisitSyntaxNode(syntaxNode As SyntaxNode) Implements ISyntaxReceiver.OnVisitSyntaxNode
If (_throw) Then
Throw New Exception("Syntax Walk")
End If
_nodes.Add(syntaxNode)
End Sub
End Class
End Class
<Generator(LanguageNames.VisualBasic)>
Friend Class VBIncrementalGenerator
Implements IIncrementalGenerator
Public _initialized As Boolean
Public Sub Initialize(context As IncrementalGeneratorInitializationContext) Implements IIncrementalGenerator.Initialize
_initialized = True
End Sub
End Class
<Generator(LanguageNames.VisualBasic)>
Friend Class VBIncrementalAndSourceGenerator
Implements IIncrementalGenerator
Implements ISourceGenerator
Public _initialized As Boolean
Public _sourceInitialized As Boolean
Public _sourceExecuted As Boolean
Public Sub Initialize(context As IncrementalGeneratorInitializationContext) Implements IIncrementalGenerator.Initialize
_initialized = True
End Sub
Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize
_sourceInitialized = True
End Sub
Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute
_sourceExecuted = True
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities.TestGenerators
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class GeneratorDriverTests
Inherits BasicTestBase
<Fact>
Public Sub Single_File_Is_Added()
Dim generatorSource = "
Public Class GeneratedClass
End Class
"
Dim parseOptions = TestOptions.Regular
Dim compilation = GetCompilation(parseOptions)
Dim testGenerator As SingleFileTestGenerator = New SingleFileTestGenerator(generatorSource)
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
Assert.Equal(2, outputCompilation.SyntaxTrees.Count())
Assert.NotEqual(compilation, outputCompilation)
End Sub
<Fact>
Public Sub Can_Access_Additional_Files()
Dim additionalText = New InMemoryAdditionalText("a\\file1.cs", "Hello World")
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i)
End Sub,
Sub(e) Assert.Equal("Hello World", e.AdditionalFiles.First().GetText().ToString()))
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator),
additionalTexts:=ImmutableArray.Create(Of AdditionalText)(additionalText),
parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
End Sub
<Fact>
Public Sub Generator_Can_Be_Written_In_Visual_Basic()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As VBGenerator = New VBGenerator()
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
Assert.Equal(2, outputCompilation.SyntaxTrees.Count())
Assert.NotEqual(compilation, outputCompilation)
End Sub
<Fact>
Public Sub Generator_Can_See_Syntax()
Dim source = "
Imports System
Namespace ANamespace
Public Class AClass
Public Sub AMethod(p as String)
Throw New InvalidOperationException()
End Sub
End Class
End Namespace
"
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions, source)
Dim testGenerator As VBGenerator = New VBGenerator()
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
Assert.Equal(23, testGenerator._receiver._nodes.Count)
Assert.IsType(GetType(CompilationUnitSyntax), testGenerator._receiver._nodes(0))
Assert.IsType(GetType(ClassStatementSyntax), testGenerator._receiver._nodes(8))
Assert.IsType(GetType(ThrowStatementSyntax), testGenerator._receiver._nodes(16))
Assert.IsType(GetType(EndBlockStatementSyntax), testGenerator._receiver._nodes(22))
End Sub
<Fact>
Public Sub Exception_During_Init()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) Throw New Exception("Init Exception"),
Sub(e)
End Sub)
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify(
Diagnostic("BC42501").WithArguments("CallbackGenerator", "Exception", "Init Exception").WithLocation(1, 1)
)
End Sub
<Fact>
Public Sub Exception_During_Execute()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i)
End Sub,
Sub(e) Throw New Exception("Generate Exception"))
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify(
Diagnostic("BC42502").WithArguments("CallbackGenerator", "Exception", "Generate Exception").WithLocation(1, 1)
)
End Sub
<Fact>
Public Sub Exception_During_SyntaxWalk()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As VBGenerator = New VBGenerator()
testGenerator._receiver._throw = True
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify(
Diagnostic("BC42502").WithArguments("VBGenerator", "Exception", "Syntax Walk").WithLocation(1, 1)
)
End Sub
<Fact>
Public Sub SyntaxTrees_Are_Lazy()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator = New SingleFileTestGenerator("Class C : End Class")
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
driver = driver.RunGenerators(compilation)
Dim results = driver.GetRunResult()
Dim tree = Assert.Single(results.GeneratedTrees)
Dim rootFromTryGetRoot As SyntaxNode = Nothing
Assert.False(tree.TryGetRoot(rootFromTryGetRoot))
Dim rootFromGetRoot = tree.GetRoot()
Assert.NotNull(rootFromGetRoot)
Assert.True(tree.TryGetRoot(rootFromTryGetRoot))
Assert.Same(rootFromGetRoot, rootFromTryGetRoot)
End Sub
<Fact>
Public Sub Diagnostics_Respect_Suppression()
Dim compilation As Compilation = GetCompilation(TestOptions.Regular)
Dim gen As CallbackGenerator = New CallbackGenerator(Sub(c)
End Sub,
Sub(c)
c.ReportDiagnostic(VBDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 2))
c.ReportDiagnostic(VBDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 3))
End Sub)
VerifyDiagnosticsWithOptions(gen, compilation,
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1))
Dim warnings As IDictionary(Of String, ReportDiagnostic) = New Dictionary(Of String, ReportDiagnostic)()
warnings.Add("GEN001", ReportDiagnostic.Suppress)
VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)),
Diagnostic("GEN002").WithLocation(1, 1))
warnings.Clear()
warnings.Add("GEN002", ReportDiagnostic.Suppress)
VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)),
Diagnostic("GEN001").WithLocation(1, 1))
warnings.Clear()
warnings.Add("GEN001", ReportDiagnostic.Error)
VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)),
Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(True),
Diagnostic("GEN002").WithLocation(1, 1))
warnings.Clear()
warnings.Add("GEN002", ReportDiagnostic.Error)
VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)),
Diagnostic("GEN001").WithLocation(1, 1),
Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(True))
End Sub
<Fact>
Public Sub Diagnostics_Respect_Pragma_Suppression()
Dim gen001 = VBDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 2)
VerifyDiagnosticsWithSource("'comment",
gen001, TextSpan.FromBounds(1, 4),
Diagnostic("GEN001", "com").WithLocation(1, 2))
VerifyDiagnosticsWithSource("#disable warning
'comment",
gen001, TextSpan.FromBounds(19, 22),
Diagnostic("GEN001", "com", isSuppressed:=True).WithLocation(2, 2))
VerifyDiagnosticsWithSource("#disable warning
'comment",
gen001, New TextSpan(0, 0),
Diagnostic("GEN001").WithLocation(1, 1))
VerifyDiagnosticsWithSource("#disable warning GEN001
'comment",
gen001, TextSpan.FromBounds(26, 29),
Diagnostic("GEN001", "com", isSuppressed:=True).WithLocation(2, 2))
VerifyDiagnosticsWithSource("#disable warning GEN001
'comment
#enable warning GEN001
'another",
gen001, TextSpan.FromBounds(60, 63),
Diagnostic("GEN001", "ano").WithLocation(4, 2))
End Sub
<Fact>
Public Sub Enable_Incremental_Generators()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As VBIncrementalGenerator = New VBIncrementalGenerator()
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(New IncrementalGeneratorWrapper(testGenerator)), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
Assert.Equal(1, outputCompilation.SyntaxTrees.Count())
Assert.Equal(compilation, compilation)
Assert.True(testGenerator._initialized)
End Sub
<Fact>
Public Sub Prefer_Incremental_Generators()
Dim parseOptions = TestOptions.Regular
Dim compilation As Compilation = GetCompilation(parseOptions)
Dim testGenerator As VBIncrementalAndSourceGenerator = New VBIncrementalAndSourceGenerator()
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions)
Dim outputCompilation As Compilation = Nothing
Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics)
outputDiagnostics.Verify()
Assert.Equal(1, outputCompilation.SyntaxTrees.Count())
Assert.Equal(compilation, compilation)
Assert.True(testGenerator._initialized)
Assert.False(testGenerator._sourceInitialized)
Assert.False(testGenerator._sourceExecuted)
End Sub
Shared Function GetCompilation(parseOptions As VisualBasicParseOptions, Optional source As String = "") As Compilation
If (String.IsNullOrWhiteSpace(source)) Then
source = "
Public Class C
End Class
"
End If
Dim compilation As Compilation = CreateCompilation(source, options:=TestOptions.DebugDll, parseOptions:=parseOptions)
compilation.VerifyDiagnostics()
Assert.Single(compilation.SyntaxTrees)
Return compilation
End Function
Shared Sub VerifyDiagnosticsWithOptions(generator As ISourceGenerator, compilation As Compilation, ParamArray expected As DiagnosticDescription())
compilation.VerifyDiagnostics()
Assert.Single(compilation.SyntaxTrees)
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(generator), parseOptions:=TestOptions.Regular)
Dim outputCompilation As Compilation = Nothing
Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, diagnostics)
outputCompilation.VerifyDiagnostics()
diagnostics.Verify(expected)
End Sub
Shared Sub VerifyDiagnosticsWithSource(source As String, diag As Diagnostic, location As TextSpan, ParamArray expected As DiagnosticDescription())
Dim parseOptions = TestOptions.Regular
source = source.Replace(Environment.NewLine, vbCrLf)
Dim compilation As Compilation = CreateCompilation(source)
compilation.VerifyDiagnostics()
Assert.Single(compilation.SyntaxTrees)
Dim gen As ISourceGenerator = New CallbackGenerator(Sub(c)
End Sub,
Sub(c)
If location.IsEmpty Then
c.ReportDiagnostic(diag)
Else
c.ReportDiagnostic(diag.WithLocation(CodeAnalysis.Location.Create(c.Compilation.SyntaxTrees.First(), location)))
End If
End Sub)
Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions:=TestOptions.Regular)
Dim outputCompilation As Compilation = Nothing
Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing
driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, diagnostics)
outputCompilation.VerifyDiagnostics()
diagnostics.Verify(expected)
End Sub
End Class
<Generator(LanguageNames.VisualBasic)>
Friend Class VBGenerator
Implements ISourceGenerator
Public _receiver As Receiver = New Receiver()
Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize
context.RegisterForSyntaxNotifications(Function() _receiver)
End Sub
Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute
context.AddSource("source.vb", "
Public Class D
End Class
")
End Sub
Class Receiver
Implements ISyntaxReceiver
Public _throw As Boolean
Public _nodes As List(Of SyntaxNode) = New List(Of SyntaxNode)()
Public Sub OnVisitSyntaxNode(syntaxNode As SyntaxNode) Implements ISyntaxReceiver.OnVisitSyntaxNode
If (_throw) Then
Throw New Exception("Syntax Walk")
End If
_nodes.Add(syntaxNode)
End Sub
End Class
End Class
<Generator(LanguageNames.VisualBasic)>
Friend Class VBIncrementalGenerator
Implements IIncrementalGenerator
Public _initialized As Boolean
Public Sub Initialize(context As IncrementalGeneratorInitializationContext) Implements IIncrementalGenerator.Initialize
_initialized = True
End Sub
End Class
<Generator(LanguageNames.VisualBasic)>
Friend Class VBIncrementalAndSourceGenerator
Implements IIncrementalGenerator
Implements ISourceGenerator
Public _initialized As Boolean
Public _sourceInitialized As Boolean
Public _sourceExecuted As Boolean
Public Sub Initialize(context As IncrementalGeneratorInitializationContext) Implements IIncrementalGenerator.Initialize
_initialized = True
End Sub
Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize
_sourceInitialized = True
End Sub
Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute
_sourceExecuted = True
End Sub
End Class
End Namespace
| 1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarSelectedItems.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Editor
{
internal class NavigationBarSelectedTypeAndMember : IEquatable<NavigationBarSelectedTypeAndMember>
{
public NavigationBarItem? TypeItem { get; }
public bool ShowTypeItemGrayed { get; }
public NavigationBarItem? MemberItem { get; }
public bool ShowMemberItemGrayed { get; }
public NavigationBarSelectedTypeAndMember(NavigationBarItem? typeItem, NavigationBarItem? memberItem)
: this(typeItem, showTypeItemGrayed: false, memberItem, showMemberItemGrayed: false)
{
}
public NavigationBarSelectedTypeAndMember(
NavigationBarItem? typeItem,
bool showTypeItemGrayed,
NavigationBarItem? memberItem,
bool showMemberItemGrayed)
{
TypeItem = typeItem;
MemberItem = memberItem;
ShowTypeItemGrayed = showTypeItemGrayed;
ShowMemberItemGrayed = showMemberItemGrayed;
}
public override bool Equals(object? obj)
=> Equals(obj as NavigationBarSelectedTypeAndMember);
public bool Equals(NavigationBarSelectedTypeAndMember? other)
=> other != null &&
this.ShowTypeItemGrayed == other.ShowTypeItemGrayed &&
this.ShowMemberItemGrayed == other.ShowMemberItemGrayed &&
Equals(this.TypeItem, other.TypeItem) &&
Equals(this.MemberItem, other.MemberItem);
public override int GetHashCode()
=> throw new NotImplementedException();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.Editor
{
internal class NavigationBarSelectedTypeAndMember : IEquatable<NavigationBarSelectedTypeAndMember>
{
public NavigationBarItem? TypeItem { get; }
public bool ShowTypeItemGrayed { get; }
public NavigationBarItem? MemberItem { get; }
public bool ShowMemberItemGrayed { get; }
public NavigationBarSelectedTypeAndMember(NavigationBarItem? typeItem, NavigationBarItem? memberItem)
: this(typeItem, showTypeItemGrayed: false, memberItem, showMemberItemGrayed: false)
{
}
public NavigationBarSelectedTypeAndMember(
NavigationBarItem? typeItem,
bool showTypeItemGrayed,
NavigationBarItem? memberItem,
bool showMemberItemGrayed)
{
TypeItem = typeItem;
MemberItem = memberItem;
ShowTypeItemGrayed = showTypeItemGrayed;
ShowMemberItemGrayed = showMemberItemGrayed;
}
public override bool Equals(object? obj)
=> Equals(obj as NavigationBarSelectedTypeAndMember);
public bool Equals(NavigationBarSelectedTypeAndMember? other)
=> other != null &&
this.ShowTypeItemGrayed == other.ShowTypeItemGrayed &&
this.ShowMemberItemGrayed == other.ShowMemberItemGrayed &&
Equals(this.TypeItem, other.TypeItem) &&
Equals(this.MemberItem, other.MemberItem);
public override int GetHashCode()
=> throw new NotImplementedException();
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceSimpleParameterSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A source parameter that has no default value, no attributes,
/// and is not params.
/// </summary>
internal sealed class SourceSimpleParameterSymbol : SourceParameterSymbol
{
public SourceSimpleParameterSymbol(
Symbol owner,
TypeWithAnnotations parameterType,
int ordinal,
RefKind refKind,
string name,
ImmutableArray<Location> locations)
: base(owner, parameterType, ordinal, refKind, name, locations)
{
}
public override bool IsDiscard => false;
internal override ConstantValue? ExplicitDefaultConstantValue
{
get { return null; }
}
internal override bool IsMetadataOptional
{
get { return false; }
}
public override bool IsParams
{
get { return false; }
}
internal override bool HasDefaultArgumentSyntax
{
get { return false; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
internal override SyntaxReference? SyntaxReference
{
get { return null; }
}
internal override bool IsExtensionMethodThis
{
get { return false; }
}
internal override bool IsIDispatchConstant
{
get { return false; }
}
internal override bool IsIUnknownConstant
{
get { return false; }
}
internal override bool IsCallerFilePath
{
get { return false; }
}
internal override bool IsCallerLineNumber
{
get { return false; }
}
internal override bool IsCallerMemberName
{
get { return false; }
}
internal override int CallerArgumentExpressionParameterIndex
{
get { return -1; }
}
internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => ImmutableArray<int>.Empty;
internal override bool HasInterpolatedStringHandlerArgumentError => false;
internal override FlowAnalysisAnnotations FlowAnalysisAnnotations
{
get { return FlowAnalysisAnnotations.None; }
}
internal override ImmutableHashSet<string> NotNullIfParameterNotNull => ImmutableHashSet<string>.Empty;
internal override MarshalPseudoCustomAttributeData? MarshallingInformation
{
get { return null; }
}
internal override bool HasOptionalAttribute
{
get { return false; }
}
internal override SyntaxList<AttributeListSyntax> AttributeDeclarationList
{
get { return default(SyntaxList<AttributeListSyntax>); }
}
internal override CustomAttributesBag<CSharpAttributeData> GetAttributesBag()
{
state.NotePartComplete(CompletionPart.Attributes);
return CustomAttributesBag<CSharpAttributeData>.Empty;
}
internal override ConstantValue DefaultValueFromAttributes
{
get { return ConstantValue.NotAvailable; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A source parameter that has no default value, no attributes,
/// and is not params.
/// </summary>
internal sealed class SourceSimpleParameterSymbol : SourceParameterSymbol
{
public SourceSimpleParameterSymbol(
Symbol owner,
TypeWithAnnotations parameterType,
int ordinal,
RefKind refKind,
string name,
ImmutableArray<Location> locations)
: base(owner, parameterType, ordinal, refKind, name, locations)
{
}
public override bool IsDiscard => false;
internal override ConstantValue? ExplicitDefaultConstantValue
{
get { return null; }
}
internal override bool IsMetadataOptional
{
get { return false; }
}
public override bool IsParams
{
get { return false; }
}
internal override bool HasDefaultArgumentSyntax
{
get { return false; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
internal override SyntaxReference? SyntaxReference
{
get { return null; }
}
internal override bool IsExtensionMethodThis
{
get { return false; }
}
internal override bool IsIDispatchConstant
{
get { return false; }
}
internal override bool IsIUnknownConstant
{
get { return false; }
}
internal override bool IsCallerFilePath
{
get { return false; }
}
internal override bool IsCallerLineNumber
{
get { return false; }
}
internal override bool IsCallerMemberName
{
get { return false; }
}
internal override int CallerArgumentExpressionParameterIndex
{
get { return -1; }
}
internal override ImmutableArray<int> InterpolatedStringHandlerArgumentIndexes => ImmutableArray<int>.Empty;
internal override bool HasInterpolatedStringHandlerArgumentError => false;
internal override FlowAnalysisAnnotations FlowAnalysisAnnotations
{
get { return FlowAnalysisAnnotations.None; }
}
internal override ImmutableHashSet<string> NotNullIfParameterNotNull => ImmutableHashSet<string>.Empty;
internal override MarshalPseudoCustomAttributeData? MarshallingInformation
{
get { return null; }
}
internal override bool HasOptionalAttribute
{
get { return false; }
}
internal override SyntaxList<AttributeListSyntax> AttributeDeclarationList
{
get { return default(SyntaxList<AttributeListSyntax>); }
}
internal override CustomAttributesBag<CSharpAttributeData> GetAttributesBag()
{
state.NotePartComplete(CompletionPart.Attributes);
return CustomAttributesBag<CSharpAttributeData>.Empty;
}
internal override ConstantValue DefaultValueFromAttributes
{
get { return ConstantValue.NotAvailable; }
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEAssemblySymbol.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.Generic
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports System.Linq.Enumerable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Runtime.InteropServices
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
''' <summary>
''' Represents an assembly imported from a PE.
''' </summary>
''' <remarks></remarks>
Friend NotInheritable Class PEAssemblySymbol
Inherits MetadataOrSourceAssemblySymbol
''' <summary>
''' An Assembly object providing metadata for the assembly.
''' </summary>
''' <remarks></remarks>
Private ReadOnly _assembly As PEAssembly
''' <summary>
''' A MetadataDocumentationProvider providing XML documentation for this assembly.
''' </summary>
Private ReadOnly _documentationProvider As DocumentationProvider
''' <summary>
''' The list of contained PEModuleSymbol objects.
''' The list doesn't use type ReadOnlyCollection(Of PEModuleSymbol) so that we
''' can return it from Modules property as is.
''' </summary>
''' <remarks></remarks>
Private ReadOnly _modules As ImmutableArray(Of ModuleSymbol)
''' <summary>
''' An array of assemblies involved in canonical type resolution of
''' NoPia local types defined within this assembly. In other words, all
''' references used by a compilation referencing this assembly.
''' The array and its content is provided by ReferenceManager and must not be modified.
''' </summary>
Private _noPiaResolutionAssemblies As ImmutableArray(Of AssemblySymbol)
''' <summary>
''' An array of assemblies referenced by this assembly, which are linked (/l-ed) by
''' each compilation that is using this AssemblySymbol as a reference.
''' If this AssemblySymbol is linked too, it will be in this array too.
''' The array and its content is provided by ReferenceManager and must not be modified.
''' </summary>
Private _linkedReferencedAssemblies As ImmutableArray(Of AssemblySymbol)
''' <summary>
''' Assembly is /l-ed by compilation that is using it as a reference.
''' </summary>
Private ReadOnly _isLinked As Boolean
Private _lazyMightContainExtensionMethods As Byte = ThreeState.Unknown
Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData)
Friend Sub New(assembly As PEAssembly, documentationProvider As DocumentationProvider,
isLinked As Boolean, importOptions As MetadataImportOptions)
Debug.Assert(assembly IsNot Nothing)
_assembly = assembly
_documentationProvider = documentationProvider
Dim modules(assembly.Modules.Length - 1) As ModuleSymbol
For i As Integer = 0 To assembly.Modules.Length - 1 Step 1
modules(i) = New PEModuleSymbol(Me, assembly.Modules(i), importOptions, i)
Next
_modules = modules.AsImmutableOrNull()
_isLinked = isLinked
End Sub
Friend ReadOnly Property Assembly As PEAssembly
Get
Return _assembly
End Get
End Property
Public Overrides ReadOnly Property Identity As AssemblyIdentity
Get
Return _assembly.Identity
End Get
End Property
Public Overrides ReadOnly Property AssemblyVersionPattern As Version
Get
' TODO: https://github.com/dotnet/roslyn/issues/9000
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property PublicKey As ImmutableArray(Of Byte)
Get
Return _assembly.Identity.PublicKey
End Get
End Property
Friend Overrides Function GetGuidString(ByRef guidString As String) As Boolean
Return Assembly.Modules(0).HasGuidAttribute(Assembly.Handle, guidString)
End Function
Friend Overrides Function AreInternalsVisibleToThisAssembly(potentialGiverOfAccess As AssemblySymbol) As Boolean
Return MakeFinalIVTDetermination(potentialGiverOfAccess) = IVTConclusion.Match
End Function
Friend Overrides Function GetInternalsVisibleToPublicKeys(simpleName As String) As IEnumerable(Of ImmutableArray(Of Byte))
Return Assembly.GetInternalsVisibleToPublicKeys(simpleName)
End Function
Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
If _lazyCustomAttributes.IsDefault Then
PrimaryModule.LoadCustomAttributes(Me.Assembly.Handle, _lazyCustomAttributes)
End If
Return _lazyCustomAttributes
End Function
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return StaticCast(Of Location).From(PrimaryModule.MetadataLocation)
End Get
End Property
Public Overrides ReadOnly Property Modules As ImmutableArray(Of ModuleSymbol)
Get
Return _modules
End Get
End Property
Friend ReadOnly Property PrimaryModule As PEModuleSymbol
Get
Return DirectCast(Me.Modules(0), PEModuleSymbol)
End Get
End Property
''' <summary>
''' Look up the assemblies to which the given metadata type Is forwarded.
''' </summary>
''' <param name="emittedName"></param>
''' <param name="ignoreCase">Pass true to look up fullName case-insensitively. WARNING: more expensive.</param>
''' <param name="matchedName">Returns the actual casing of the matching name.</param>
''' <returns>
''' The assemblies to which the given type Is forwarded Or null, if there isn't one.
''' </returns>
''' <remarks>
''' The returned assemblies may also forward the type.
''' </remarks>
Friend Function LookupAssembliesForForwardedMetadataType(ByRef emittedName As MetadataTypeName, ignoreCase As Boolean, <Out> ByRef matchedName As String) As (FirstSymbol As AssemblySymbol, SecondSymbol As AssemblySymbol)
' Look in the type forwarders of the primary module of this assembly, clr does not honor type forwarder
' in non-primary modules.
' Examine the type forwarders, but only from the primary module.
Return PrimaryModule.GetAssembliesForForwardedType(emittedName, ignoreCase, matchedName)
End Function
Friend Overrides Function GetAllTopLevelForwardedTypes() As IEnumerable(Of NamedTypeSymbol)
Return PrimaryModule.GetForwardedTypes()
End Function
Friend Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol
' Check if it is a forwarded type.
Dim matchedName As String = Nothing
Dim forwardedToAssemblies = LookupAssembliesForForwardedMetadataType(emittedName, ignoreCase, matchedName)
If forwardedToAssemblies.FirstSymbol IsNot Nothing Then
If forwardedToAssemblies.SecondSymbol IsNot Nothing Then
' Report the main module as that is the only one checked. clr does not honor type forwarders in non-primary modules.
Return CreateMultipleForwardingErrorTypeSymbol(emittedName, PrimaryModule, forwardedToAssemblies.FirstSymbol, forwardedToAssemblies.SecondSymbol)
End If
' Don't bother to check the forwarded-to assembly if we've already seen it.
If visitedAssemblies IsNot Nothing AndAlso visitedAssemblies.Contains(forwardedToAssemblies.FirstSymbol) Then
Return CreateCycleInTypeForwarderErrorTypeSymbol(emittedName)
Else
visitedAssemblies = New ConsList(Of AssemblySymbol)(Me, If(visitedAssemblies, ConsList(Of AssemblySymbol).Empty))
If ignoreCase AndAlso Not String.Equals(emittedName.FullName, matchedName, StringComparison.Ordinal) Then
emittedName = MetadataTypeName.FromFullName(matchedName, emittedName.UseCLSCompliantNameArityEncoding, emittedName.ForcedArity)
End If
Return forwardedToAssemblies.FirstSymbol.LookupTopLevelMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, digThroughForwardedTypes:=True)
End If
End If
Return Nothing
End Function
Friend Overrides Function GetNoPiaResolutionAssemblies() As ImmutableArray(Of AssemblySymbol)
Return _noPiaResolutionAssemblies
End Function
Friend Overrides Sub SetNoPiaResolutionAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
_noPiaResolutionAssemblies = assemblies
End Sub
Friend Overrides Sub SetLinkedReferencedAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
_linkedReferencedAssemblies = assemblies
End Sub
Friend Overrides Function GetLinkedReferencedAssemblies() As ImmutableArray(Of AssemblySymbol)
Return _linkedReferencedAssemblies
End Function
Friend Overrides ReadOnly Property IsLinked As Boolean
Get
Return _isLinked
End Get
End Property
Friend ReadOnly Property DocumentationProvider As DocumentationProvider
Get
Return _documentationProvider
End Get
End Property
Public Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
If _lazyMightContainExtensionMethods = ThreeState.Unknown Then
Dim primaryModuleSymbol = PrimaryModule
If primaryModuleSymbol.Module.HasExtensionAttribute(_assembly.Handle, ignoreCase:=True) Then
_lazyMightContainExtensionMethods = ThreeState.True
Else
_lazyMightContainExtensionMethods = ThreeState.False
End If
End If
Return _lazyMightContainExtensionMethods = ThreeState.True
End Get
End Property
''' <remarks>
''' This is for perf, not for correctness.
''' </remarks>
Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation
Get
Return Nothing
End Get
End Property
Public Overrides Function GetMetadata() As AssemblyMetadata
Return _assembly.GetNonDisposableMetadata()
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.Generic
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports System.Linq.Enumerable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports System.Runtime.InteropServices
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
''' <summary>
''' Represents an assembly imported from a PE.
''' </summary>
''' <remarks></remarks>
Friend NotInheritable Class PEAssemblySymbol
Inherits MetadataOrSourceAssemblySymbol
''' <summary>
''' An Assembly object providing metadata for the assembly.
''' </summary>
''' <remarks></remarks>
Private ReadOnly _assembly As PEAssembly
''' <summary>
''' A MetadataDocumentationProvider providing XML documentation for this assembly.
''' </summary>
Private ReadOnly _documentationProvider As DocumentationProvider
''' <summary>
''' The list of contained PEModuleSymbol objects.
''' The list doesn't use type ReadOnlyCollection(Of PEModuleSymbol) so that we
''' can return it from Modules property as is.
''' </summary>
''' <remarks></remarks>
Private ReadOnly _modules As ImmutableArray(Of ModuleSymbol)
''' <summary>
''' An array of assemblies involved in canonical type resolution of
''' NoPia local types defined within this assembly. In other words, all
''' references used by a compilation referencing this assembly.
''' The array and its content is provided by ReferenceManager and must not be modified.
''' </summary>
Private _noPiaResolutionAssemblies As ImmutableArray(Of AssemblySymbol)
''' <summary>
''' An array of assemblies referenced by this assembly, which are linked (/l-ed) by
''' each compilation that is using this AssemblySymbol as a reference.
''' If this AssemblySymbol is linked too, it will be in this array too.
''' The array and its content is provided by ReferenceManager and must not be modified.
''' </summary>
Private _linkedReferencedAssemblies As ImmutableArray(Of AssemblySymbol)
''' <summary>
''' Assembly is /l-ed by compilation that is using it as a reference.
''' </summary>
Private ReadOnly _isLinked As Boolean
Private _lazyMightContainExtensionMethods As Byte = ThreeState.Unknown
Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData)
Friend Sub New(assembly As PEAssembly, documentationProvider As DocumentationProvider,
isLinked As Boolean, importOptions As MetadataImportOptions)
Debug.Assert(assembly IsNot Nothing)
_assembly = assembly
_documentationProvider = documentationProvider
Dim modules(assembly.Modules.Length - 1) As ModuleSymbol
For i As Integer = 0 To assembly.Modules.Length - 1 Step 1
modules(i) = New PEModuleSymbol(Me, assembly.Modules(i), importOptions, i)
Next
_modules = modules.AsImmutableOrNull()
_isLinked = isLinked
End Sub
Friend ReadOnly Property Assembly As PEAssembly
Get
Return _assembly
End Get
End Property
Public Overrides ReadOnly Property Identity As AssemblyIdentity
Get
Return _assembly.Identity
End Get
End Property
Public Overrides ReadOnly Property AssemblyVersionPattern As Version
Get
' TODO: https://github.com/dotnet/roslyn/issues/9000
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property PublicKey As ImmutableArray(Of Byte)
Get
Return _assembly.Identity.PublicKey
End Get
End Property
Friend Overrides Function GetGuidString(ByRef guidString As String) As Boolean
Return Assembly.Modules(0).HasGuidAttribute(Assembly.Handle, guidString)
End Function
Friend Overrides Function AreInternalsVisibleToThisAssembly(potentialGiverOfAccess As AssemblySymbol) As Boolean
Return MakeFinalIVTDetermination(potentialGiverOfAccess) = IVTConclusion.Match
End Function
Friend Overrides Function GetInternalsVisibleToPublicKeys(simpleName As String) As IEnumerable(Of ImmutableArray(Of Byte))
Return Assembly.GetInternalsVisibleToPublicKeys(simpleName)
End Function
Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
If _lazyCustomAttributes.IsDefault Then
PrimaryModule.LoadCustomAttributes(Me.Assembly.Handle, _lazyCustomAttributes)
End If
Return _lazyCustomAttributes
End Function
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return StaticCast(Of Location).From(PrimaryModule.MetadataLocation)
End Get
End Property
Public Overrides ReadOnly Property Modules As ImmutableArray(Of ModuleSymbol)
Get
Return _modules
End Get
End Property
Friend ReadOnly Property PrimaryModule As PEModuleSymbol
Get
Return DirectCast(Me.Modules(0), PEModuleSymbol)
End Get
End Property
''' <summary>
''' Look up the assemblies to which the given metadata type Is forwarded.
''' </summary>
''' <param name="emittedName"></param>
''' <param name="ignoreCase">Pass true to look up fullName case-insensitively. WARNING: more expensive.</param>
''' <param name="matchedName">Returns the actual casing of the matching name.</param>
''' <returns>
''' The assemblies to which the given type Is forwarded Or null, if there isn't one.
''' </returns>
''' <remarks>
''' The returned assemblies may also forward the type.
''' </remarks>
Friend Function LookupAssembliesForForwardedMetadataType(ByRef emittedName As MetadataTypeName, ignoreCase As Boolean, <Out> ByRef matchedName As String) As (FirstSymbol As AssemblySymbol, SecondSymbol As AssemblySymbol)
' Look in the type forwarders of the primary module of this assembly, clr does not honor type forwarder
' in non-primary modules.
' Examine the type forwarders, but only from the primary module.
Return PrimaryModule.GetAssembliesForForwardedType(emittedName, ignoreCase, matchedName)
End Function
Friend Overrides Function GetAllTopLevelForwardedTypes() As IEnumerable(Of NamedTypeSymbol)
Return PrimaryModule.GetForwardedTypes()
End Function
Friend Overrides Function TryLookupForwardedMetadataTypeWithCycleDetection(ByRef emittedName As MetadataTypeName, visitedAssemblies As ConsList(Of AssemblySymbol), ignoreCase As Boolean) As NamedTypeSymbol
' Check if it is a forwarded type.
Dim matchedName As String = Nothing
Dim forwardedToAssemblies = LookupAssembliesForForwardedMetadataType(emittedName, ignoreCase, matchedName)
If forwardedToAssemblies.FirstSymbol IsNot Nothing Then
If forwardedToAssemblies.SecondSymbol IsNot Nothing Then
' Report the main module as that is the only one checked. clr does not honor type forwarders in non-primary modules.
Return CreateMultipleForwardingErrorTypeSymbol(emittedName, PrimaryModule, forwardedToAssemblies.FirstSymbol, forwardedToAssemblies.SecondSymbol)
End If
' Don't bother to check the forwarded-to assembly if we've already seen it.
If visitedAssemblies IsNot Nothing AndAlso visitedAssemblies.Contains(forwardedToAssemblies.FirstSymbol) Then
Return CreateCycleInTypeForwarderErrorTypeSymbol(emittedName)
Else
visitedAssemblies = New ConsList(Of AssemblySymbol)(Me, If(visitedAssemblies, ConsList(Of AssemblySymbol).Empty))
If ignoreCase AndAlso Not String.Equals(emittedName.FullName, matchedName, StringComparison.Ordinal) Then
emittedName = MetadataTypeName.FromFullName(matchedName, emittedName.UseCLSCompliantNameArityEncoding, emittedName.ForcedArity)
End If
Return forwardedToAssemblies.FirstSymbol.LookupTopLevelMetadataTypeWithCycleDetection(emittedName, visitedAssemblies, digThroughForwardedTypes:=True)
End If
End If
Return Nothing
End Function
Friend Overrides Function GetNoPiaResolutionAssemblies() As ImmutableArray(Of AssemblySymbol)
Return _noPiaResolutionAssemblies
End Function
Friend Overrides Sub SetNoPiaResolutionAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
_noPiaResolutionAssemblies = assemblies
End Sub
Friend Overrides Sub SetLinkedReferencedAssemblies(assemblies As ImmutableArray(Of AssemblySymbol))
_linkedReferencedAssemblies = assemblies
End Sub
Friend Overrides Function GetLinkedReferencedAssemblies() As ImmutableArray(Of AssemblySymbol)
Return _linkedReferencedAssemblies
End Function
Friend Overrides ReadOnly Property IsLinked As Boolean
Get
Return _isLinked
End Get
End Property
Friend ReadOnly Property DocumentationProvider As DocumentationProvider
Get
Return _documentationProvider
End Get
End Property
Public Overrides ReadOnly Property MightContainExtensionMethods As Boolean
Get
If _lazyMightContainExtensionMethods = ThreeState.Unknown Then
Dim primaryModuleSymbol = PrimaryModule
If primaryModuleSymbol.Module.HasExtensionAttribute(_assembly.Handle, ignoreCase:=True) Then
_lazyMightContainExtensionMethods = ThreeState.True
Else
_lazyMightContainExtensionMethods = ThreeState.False
End If
End If
Return _lazyMightContainExtensionMethods = ThreeState.True
End Get
End Property
''' <remarks>
''' This is for perf, not for correctness.
''' </remarks>
Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation
Get
Return Nothing
End Get
End Property
Public Overrides Function GetMetadata() As AssemblyMetadata
Return _assembly.GetNonDisposableMetadata()
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/VisualStudio/CSharp/Impl/LanguageService/CSharpEditorFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.FileHeaders;
using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.FileHeaders;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
[ExcludeFromCodeCoverage]
[Guid(Guids.CSharpEditorFactoryIdString)]
internal class CSharpEditorFactory : AbstractEditorFactory
{
public CSharpEditorFactory(IComponentModel componentModel)
: base(componentModel)
{
}
protected override string ContentTypeName => ContentTypeNames.CSharpContentType;
protected override string LanguageName => LanguageNames.CSharp;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.FileHeaders;
using Microsoft.CodeAnalysis.CSharp.MisplacedUsingDirectives;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.FileHeaders;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Implementation;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
[ExcludeFromCodeCoverage]
[Guid(Guids.CSharpEditorFactoryIdString)]
internal class CSharpEditorFactory : AbstractEditorFactory
{
public CSharpEditorFactory(IComponentModel componentModel)
: base(componentModel)
{
}
protected override string ContentTypeName => ContentTypeNames.CSharpContentType;
protected override string LanguageName => LanguageNames.CSharp;
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/VisualBasicLanguageInstructionDecoder.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.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
<DkmReportNonFatalWatsonException(ExcludeExceptionType:=GetType(NotImplementedException)), DkmContinueCorruptingException>
Friend NotInheritable Class VisualBasicLanguageInstructionDecoder : Inherits LanguageInstructionDecoder(Of VisualBasicCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol, ParameterSymbol)
Public Sub New()
MyBase.New(VisualBasicInstructionDecoder.Instance)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
<DkmReportNonFatalWatsonException(ExcludeExceptionType:=GetType(NotImplementedException)), DkmContinueCorruptingException>
Friend NotInheritable Class VisualBasicLanguageInstructionDecoder : Inherits LanguageInstructionDecoder(Of VisualBasicCompilation, MethodSymbol, PEModuleSymbol, TypeSymbol, TypeParameterSymbol, ParameterSymbol)
Public Sub New()
MyBase.New(VisualBasicInstructionDecoder.Instance)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/CSharpSyntaxRewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
using Microsoft.CodeAnalysis.Syntax.InternalSyntax;
#nullable enable
internal partial class CSharpSyntaxRewriter : CSharpSyntaxVisitor<CSharpSyntaxNode>
#nullable disable
{
protected readonly bool VisitIntoStructuredTrivia;
public CSharpSyntaxRewriter(bool visitIntoStructuredTrivia = false)
{
this.VisitIntoStructuredTrivia = visitIntoStructuredTrivia;
}
public override CSharpSyntaxNode VisitToken(SyntaxToken token)
{
var leading = this.VisitList(token.LeadingTrivia);
var trailing = this.VisitList(token.TrailingTrivia);
if (leading != token.LeadingTrivia || trailing != token.TrailingTrivia)
{
if (leading != token.LeadingTrivia)
{
token = token.TokenWithLeadingTrivia(leading.Node);
}
if (trailing != token.TrailingTrivia)
{
token = token.TokenWithTrailingTrivia(trailing.Node);
}
}
return token;
}
public SyntaxList<TNode> VisitList<TNode>(SyntaxList<TNode> list) where TNode : CSharpSyntaxNode
{
SyntaxListBuilder alternate = null;
for (int i = 0, n = list.Count; i < n; i++)
{
var item = list[i];
var visited = this.Visit(item);
if (item != visited && alternate == null)
{
alternate = new SyntaxListBuilder(n);
alternate.AddRange(list, 0, i);
}
if (alternate != null)
{
Debug.Assert(visited != null && visited.Kind != SyntaxKind.None, "Cannot remove node using Syntax.InternalSyntax.SyntaxRewriter.");
alternate.Add(visited);
}
}
if (alternate != null)
{
return alternate.ToList();
}
return list;
}
public SeparatedSyntaxList<TNode> VisitList<TNode>(SeparatedSyntaxList<TNode> list) where TNode : CSharpSyntaxNode
{
// A separated list is filled with C# nodes and C# tokens. Both of which
// derive from InternalSyntax.CSharpSyntaxNode. So this cast is appropriately
// typesafe.
var withSeps = (SyntaxList<CSharpSyntaxNode>)list.GetWithSeparators();
var result = this.VisitList(withSeps);
if (result != withSeps)
{
return result.AsSeparatedList<TNode>();
}
return list;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
using Microsoft.CodeAnalysis.Syntax.InternalSyntax;
#nullable enable
internal partial class CSharpSyntaxRewriter : CSharpSyntaxVisitor<CSharpSyntaxNode>
#nullable disable
{
protected readonly bool VisitIntoStructuredTrivia;
public CSharpSyntaxRewriter(bool visitIntoStructuredTrivia = false)
{
this.VisitIntoStructuredTrivia = visitIntoStructuredTrivia;
}
public override CSharpSyntaxNode VisitToken(SyntaxToken token)
{
var leading = this.VisitList(token.LeadingTrivia);
var trailing = this.VisitList(token.TrailingTrivia);
if (leading != token.LeadingTrivia || trailing != token.TrailingTrivia)
{
if (leading != token.LeadingTrivia)
{
token = token.TokenWithLeadingTrivia(leading.Node);
}
if (trailing != token.TrailingTrivia)
{
token = token.TokenWithTrailingTrivia(trailing.Node);
}
}
return token;
}
public SyntaxList<TNode> VisitList<TNode>(SyntaxList<TNode> list) where TNode : CSharpSyntaxNode
{
SyntaxListBuilder alternate = null;
for (int i = 0, n = list.Count; i < n; i++)
{
var item = list[i];
var visited = this.Visit(item);
if (item != visited && alternate == null)
{
alternate = new SyntaxListBuilder(n);
alternate.AddRange(list, 0, i);
}
if (alternate != null)
{
Debug.Assert(visited != null && visited.Kind != SyntaxKind.None, "Cannot remove node using Syntax.InternalSyntax.SyntaxRewriter.");
alternate.Add(visited);
}
}
if (alternate != null)
{
return alternate.ToList();
}
return list;
}
public SeparatedSyntaxList<TNode> VisitList<TNode>(SeparatedSyntaxList<TNode> list) where TNode : CSharpSyntaxNode
{
// A separated list is filled with C# nodes and C# tokens. Both of which
// derive from InternalSyntax.CSharpSyntaxNode. So this cast is appropriately
// typesafe.
var withSeps = (SyntaxList<CSharpSyntaxNode>)list.GetWithSeparators();
var result = this.VisitList(withSeps);
if (result != withSeps)
{
return result.AsSeparatedList<TNode>();
}
return list;
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Analyzers/CSharp/Analyzers/RemoveUnreachableCode/CSharpRemoveUnreachableCodeDiagnosticAnalyzer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Fading;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpRemoveUnreachableCodeDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
private const string CS0162 = nameof(CS0162); // Unreachable code detected
public const string IsSubsequentSection = nameof(IsSubsequentSection);
private static readonly ImmutableDictionary<string, string> s_subsequentSectionProperties = ImmutableDictionary<string, string>.Empty.Add(IsSubsequentSection, "");
public CSharpRemoveUnreachableCodeDiagnosticAnalyzer()
: base(IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId,
EnforceOnBuildValues.RemoveUnreachableCode,
option: null,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Unreachable_code_detected), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
// This analyzer supports fading through AdditionalLocations since it's a user-controlled option
isUnnecessary: false,
configurable: false)
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSemanticModelAction(AnalyzeSemanticModel);
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context)
{
var fadeCode = context.GetOption(FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp);
var semanticModel = context.SemanticModel;
var cancellationToken = context.CancellationToken;
// There is no good existing API to check if a statement is unreachable in an efficient
// manner. While there is SemanticModel.AnalyzeControlFlow, it can only operate on a
// statement at a time, and it will reanalyze and allocate on each call.
//
// To avoid this, we simply ask the semantic model for all the diagnostics for this
// block and we look for any reported "unreachable code detected" diagnostics.
//
// This is actually quite fast to do because the compiler does not actually need to
// recompile things to determine the diagnostics. It will have already stashed the
// binding diagnostics directly on the SourceMethodSymbol containing this block, and
// so it can retrieve the diagnostics at practically no cost.
var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
var diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);
foreach (var diagnostic in diagnostics)
{
cancellationToken.ThrowIfCancellationRequested();
if (diagnostic.Id == CS0162)
{
ProcessUnreachableDiagnostic(context, root, diagnostic.Location.SourceSpan, fadeCode);
}
}
}
private void ProcessUnreachableDiagnostic(
SemanticModelAnalysisContext context, SyntaxNode root, TextSpan sourceSpan, bool fadeOutCode)
{
var node = root.FindNode(sourceSpan);
// Note: this approach works as the language only supports the concept of
// unreachable statements. If we ever get unreachable subexpressions, then
// we'll need to revise this code accordingly.
var firstUnreachableStatement = node.FirstAncestorOrSelf<StatementSyntax>();
if (firstUnreachableStatement == null ||
firstUnreachableStatement.SpanStart != sourceSpan.Start)
{
return;
}
// At a high level, we can think about us wanting to fade out a "section" of unreachable
// statements. However, the compiler only reports the first statement in that "section".
// We want to figure out what other statements are in that section and fade them all out
// along with the first statement. This is made somewhat tricky due to the fact that
// subsequent sibling statements possibly being reachable due to explicit gotos+labels.
//
// On top of this, an unreachable section might not be contiguous. This is possible
// when there is unreachable code that contains a local function declaration in-situ.
// This is legal, and the local function declaration may be called from other reachable code.
//
// As such, it's not possible to just get first unreachable statement, and the last, and
// then report that whole region as unreachable. Instead, when we are told about an
// unreachable statement, we simply determine which other statements are also unreachable
// and bucket them into contiguous chunks.
//
// We then fade each of these contiguous chunks, while also having each diagnostic we
// report point back to the first unreachable statement so that we can easily determine
// what to remove if the user fixes the issue. (The fix itself has to go recompute this
// as the total set of statements to remove may be larger than the actual faded code
// that that diagnostic corresponds to).
// Get the location of this first unreachable statement. It will be given to all
// the diagnostics we create off of this single compiler diagnostic so that we always
// know how to find it regardless of which of our diagnostics the user invokes the
// fix off of.
var firstStatementLocation = root.SyntaxTree.GetLocation(firstUnreachableStatement.FullSpan);
// 'additionalLocations' is how we always pass along the locaiton of the first unreachable
// statement in this group.
var additionalLocations = ImmutableArray.Create(firstStatementLocation);
if (fadeOutCode)
{
context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
Descriptor,
firstStatementLocation,
ReportDiagnostic.Default,
additionalLocations: ImmutableArray<Location>.Empty,
additionalUnnecessaryLocations: additionalLocations));
}
else
{
context.ReportDiagnostic(
Diagnostic.Create(Descriptor, firstStatementLocation, additionalLocations));
}
var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement);
foreach (var section in sections)
{
var span = TextSpan.FromBounds(section[0].FullSpan.Start, section.Last().FullSpan.End);
var location = root.SyntaxTree.GetLocation(span);
var additionalUnnecessaryLocations = ImmutableArray<Location>.Empty;
// Mark subsequent sections as being 'cascaded'. We don't need to actually process them
// when doing a fix-all as they'll be scooped up when we process the fix for the first
// section.
if (fadeOutCode)
{
additionalUnnecessaryLocations = ImmutableArray.Create(location);
}
context.ReportDiagnostic(
DiagnosticHelper.CreateWithLocationTags(Descriptor, location, ReportDiagnostic.Default, additionalLocations, additionalUnnecessaryLocations, s_subsequentSectionProperties));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Fading;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.RemoveUnreachableCode
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class CSharpRemoveUnreachableCodeDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer
{
private const string CS0162 = nameof(CS0162); // Unreachable code detected
public const string IsSubsequentSection = nameof(IsSubsequentSection);
private static readonly ImmutableDictionary<string, string> s_subsequentSectionProperties = ImmutableDictionary<string, string>.Empty.Add(IsSubsequentSection, "");
public CSharpRemoveUnreachableCodeDiagnosticAnalyzer()
: base(IDEDiagnosticIds.RemoveUnreachableCodeDiagnosticId,
EnforceOnBuildValues.RemoveUnreachableCode,
option: null,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Unreachable_code_detected), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
// This analyzer supports fading through AdditionalLocations since it's a user-controlled option
isUnnecessary: false,
configurable: false)
{
}
public override DiagnosticAnalyzerCategory GetAnalyzerCategory()
=> DiagnosticAnalyzerCategory.SemanticSpanAnalysis;
protected override void InitializeWorker(AnalysisContext context)
=> context.RegisterSemanticModelAction(AnalyzeSemanticModel);
private void AnalyzeSemanticModel(SemanticModelAnalysisContext context)
{
var fadeCode = context.GetOption(FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp);
var semanticModel = context.SemanticModel;
var cancellationToken = context.CancellationToken;
// There is no good existing API to check if a statement is unreachable in an efficient
// manner. While there is SemanticModel.AnalyzeControlFlow, it can only operate on a
// statement at a time, and it will reanalyze and allocate on each call.
//
// To avoid this, we simply ask the semantic model for all the diagnostics for this
// block and we look for any reported "unreachable code detected" diagnostics.
//
// This is actually quite fast to do because the compiler does not actually need to
// recompile things to determine the diagnostics. It will have already stashed the
// binding diagnostics directly on the SourceMethodSymbol containing this block, and
// so it can retrieve the diagnostics at practically no cost.
var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
var diagnostics = semanticModel.GetDiagnostics(cancellationToken: cancellationToken);
foreach (var diagnostic in diagnostics)
{
cancellationToken.ThrowIfCancellationRequested();
if (diagnostic.Id == CS0162)
{
ProcessUnreachableDiagnostic(context, root, diagnostic.Location.SourceSpan, fadeCode);
}
}
}
private void ProcessUnreachableDiagnostic(
SemanticModelAnalysisContext context, SyntaxNode root, TextSpan sourceSpan, bool fadeOutCode)
{
var node = root.FindNode(sourceSpan);
// Note: this approach works as the language only supports the concept of
// unreachable statements. If we ever get unreachable subexpressions, then
// we'll need to revise this code accordingly.
var firstUnreachableStatement = node.FirstAncestorOrSelf<StatementSyntax>();
if (firstUnreachableStatement == null ||
firstUnreachableStatement.SpanStart != sourceSpan.Start)
{
return;
}
// At a high level, we can think about us wanting to fade out a "section" of unreachable
// statements. However, the compiler only reports the first statement in that "section".
// We want to figure out what other statements are in that section and fade them all out
// along with the first statement. This is made somewhat tricky due to the fact that
// subsequent sibling statements possibly being reachable due to explicit gotos+labels.
//
// On top of this, an unreachable section might not be contiguous. This is possible
// when there is unreachable code that contains a local function declaration in-situ.
// This is legal, and the local function declaration may be called from other reachable code.
//
// As such, it's not possible to just get first unreachable statement, and the last, and
// then report that whole region as unreachable. Instead, when we are told about an
// unreachable statement, we simply determine which other statements are also unreachable
// and bucket them into contiguous chunks.
//
// We then fade each of these contiguous chunks, while also having each diagnostic we
// report point back to the first unreachable statement so that we can easily determine
// what to remove if the user fixes the issue. (The fix itself has to go recompute this
// as the total set of statements to remove may be larger than the actual faded code
// that that diagnostic corresponds to).
// Get the location of this first unreachable statement. It will be given to all
// the diagnostics we create off of this single compiler diagnostic so that we always
// know how to find it regardless of which of our diagnostics the user invokes the
// fix off of.
var firstStatementLocation = root.SyntaxTree.GetLocation(firstUnreachableStatement.FullSpan);
// 'additionalLocations' is how we always pass along the locaiton of the first unreachable
// statement in this group.
var additionalLocations = ImmutableArray.Create(firstStatementLocation);
if (fadeOutCode)
{
context.ReportDiagnostic(DiagnosticHelper.CreateWithLocationTags(
Descriptor,
firstStatementLocation,
ReportDiagnostic.Default,
additionalLocations: ImmutableArray<Location>.Empty,
additionalUnnecessaryLocations: additionalLocations));
}
else
{
context.ReportDiagnostic(
Diagnostic.Create(Descriptor, firstStatementLocation, additionalLocations));
}
var sections = RemoveUnreachableCodeHelpers.GetSubsequentUnreachableSections(firstUnreachableStatement);
foreach (var section in sections)
{
var span = TextSpan.FromBounds(section[0].FullSpan.Start, section.Last().FullSpan.End);
var location = root.SyntaxTree.GetLocation(span);
var additionalUnnecessaryLocations = ImmutableArray<Location>.Empty;
// Mark subsequent sections as being 'cascaded'. We don't need to actually process them
// when doing a fix-all as they'll be scooped up when we process the fix for the first
// section.
if (fadeOutCode)
{
additionalUnnecessaryLocations = ImmutableArray.Create(location);
}
context.ReportDiagnostic(
DiagnosticHelper.CreateWithLocationTags(Descriptor, location, ReportDiagnostic.Default, additionalLocations, additionalUnnecessaryLocations, s_subsequentSectionProperties));
}
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/Core/Tagging/TaggerDelay.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Editor.Tagging
{
/// <summary>
/// How quickly the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> should update tags after
/// receiving an <see cref="ITaggerEventSource.Changed"/> notification.
/// </summary>
internal enum TaggerDelay
{
/// <summary>
/// Indicates that the tagger should retag after a short, but imperceptible delay. This is
/// for features that want to appear instantaneous to the user, but which can wait a short
/// while until a batch of changes has occurred before processing. Specifically, if a user
/// expects the tag immediately after typing a character or moving the caret, then this
/// delay should be used.
/// </summary>
NearImmediate,
/// <summary>
/// Not as fast as NearImmediate. A user typing quickly or navigating quickly should not
/// trigger this. However, any sort of pause will cause it to trigger
/// </summary>
Short,
/// <summary>
/// Not as fast as 'Short'. The user's pause should be more significant until the tag
/// appears.
/// </summary>
Medium,
/// <summary>
/// Indicates that the tagger should run when the user appears to be
/// idle.
/// </summary>
OnIdle
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Editor.Tagging
{
/// <summary>
/// How quickly the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> should update tags after
/// receiving an <see cref="ITaggerEventSource.Changed"/> notification.
/// </summary>
internal enum TaggerDelay
{
/// <summary>
/// Indicates that the tagger should retag after a short, but imperceptible delay. This is
/// for features that want to appear instantaneous to the user, but which can wait a short
/// while until a batch of changes has occurred before processing. Specifically, if a user
/// expects the tag immediately after typing a character or moving the caret, then this
/// delay should be used.
/// </summary>
NearImmediate,
/// <summary>
/// Not as fast as NearImmediate. A user typing quickly or navigating quickly should not
/// trigger this. However, any sort of pause will cause it to trigger
/// </summary>
Short,
/// <summary>
/// Not as fast as 'Short'. The user's pause should be more significant until the tag
/// appears.
/// </summary>
Medium,
/// <summary>
/// Indicates that the tagger should run when the user appears to be
/// idle.
/// </summary>
OnIdle
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/CSharpTest/EditorConfigSettings/DataProvider/DataProviderTests.TestViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditorConfigSettings.DataProvider
{
public partial class DataProviderTests
{
private class TestViewModel : ISettingsEditorViewModel
{
public void NotifyOfUpdate() { }
Task<SourceText> ISettingsEditorViewModel.UpdateEditorConfigAsync(SourceText sourceText)
{
throw new NotImplementedException();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditorConfigSettings.DataProvider
{
public partial class DataProviderTests
{
private class TestViewModel : ISettingsEditorViewModel
{
public void NotifyOfUpdate() { }
Task<SourceText> ISettingsEditorViewModel.UpdateEditorConfigAsync(SourceText sourceText)
{
throw new NotImplementedException();
}
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Portable/Symbols/ErrorTypeSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// An ErrorSymbol is used when the compiler cannot determine a symbol object to return because
/// of an error. For example, if a field is declared "Goo x;", and the type "Goo" cannot be
/// found, an ErrorSymbol is returned when asking the field "x" what it's type is.
/// </summary>
internal abstract partial class ErrorTypeSymbol : NamedTypeSymbol
{
internal static readonly ErrorTypeSymbol UnknownResultType = new UnsupportedMetadataTypeSymbol();
private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters;
/// <summary>
/// The underlying error.
/// </summary>
internal abstract DiagnosticInfo? ErrorInfo { get; }
/// <summary>
/// Summary of the reason why the type is bad.
/// </summary>
internal virtual LookupResultKind ResultKind { get { return LookupResultKind.Empty; } }
/// <summary>
/// Called by <see cref="AbstractTypeMap.SubstituteType(TypeSymbol)"/> to perform substitution
/// on types with TypeKind ErrorType. The general pattern is to use the type map
/// to perform substitution on the wrapped type, if any, and then construct a new
/// error type symbol from the result (if there was a change).
/// </summary>
internal TypeWithAnnotations Substitute(AbstractTypeMap typeMap)
{
return TypeWithAnnotations.Create(typeMap.SubstituteNamedType(this));
}
/// <summary>
/// When constructing this ErrorTypeSymbol, there may have been symbols that seemed to
/// be what the user intended, but were unsuitable. For example, a type might have been
/// inaccessible, or ambiguous. This property returns the possible symbols that the user
/// might have intended. It will return no symbols if no possible symbols were found.
/// See the CandidateReason property to understand why the symbols were unsuitable.
/// </summary>
public virtual ImmutableArray<Symbol> CandidateSymbols
{
get
{
return ImmutableArray<Symbol>.Empty;
}
}
///<summary>
/// If CandidateSymbols returns one or more symbols, returns the reason that those
/// symbols were not chosen. Otherwise, returns None.
/// </summary>
public CandidateReason CandidateReason
{
get
{
if (!CandidateSymbols.IsEmpty)
{
Debug.Assert(ResultKind != LookupResultKind.Viable, "Shouldn't have viable result kind on error symbol");
return ResultKind.ToCandidateReason();
}
else
{
return CandidateReason.None;
}
}
}
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
return new UseSiteInfo<AssemblySymbol>(this.ErrorInfo);
}
/// <summary>
/// Returns true if this type is known to be a reference type. It is never the case that
/// IsReferenceType and IsValueType both return true. However, for an unconstrained type
/// parameter, IsReferenceType and IsValueType will both return false.
/// </summary>
public override bool IsReferenceType
{
// TODO: Consider returning False.
get { return true; }
}
/// <summary>
/// Returns true if this type is known to be a value type. It is never the case that
/// IsReferenceType and IsValueType both return true. However, for an unconstrained type
/// parameter, IsReferenceType and IsValueType will both return false.
/// </summary>
public sealed override bool IsValueType
{
get { return false; }
}
public sealed override bool IsRefLikeType
{
get
{
return false;
}
}
public sealed override bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Collection of names of members declared within this type.
/// </summary>
public override IEnumerable<string> MemberNames
{
get
{
return SpecializedCollections.EmptyEnumerable<string>();
}
}
/// <summary>
/// Get all the members of this symbol.
/// </summary>
/// <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members,
/// returns an empty ImmutableArray. Never returns Null.</returns>
public override ImmutableArray<Symbol> GetMembers()
{
if (IsTupleType)
{
var result = AddOrWrapTupleMembers(ImmutableArray<Symbol>.Empty);
RoslynDebug.Assert(result is object);
return result.ToImmutableAndFree();
}
return ImmutableArray<Symbol>.Empty;
}
/// <summary>
/// Get all the members of this symbol that have a particular name.
/// </summary>
/// <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are
/// no members with this name, returns an empty ImmutableArray. Never returns Null.</returns>
public override ImmutableArray<Symbol> GetMembers(string name)
{
return GetMembers().WhereAsArray((m, name) => m.Name == name, name);
}
internal sealed override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return this.GetMembersUnordered();
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
return this.GetMembers(name);
}
/// <summary>
/// Get all the members of this symbol that are types.
/// </summary>
/// <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members,
/// returns an empty ImmutableArray. Never returns null.</returns>
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
/// <summary>
/// Get all the members of this symbol that are types that have a particular name, of any arity.
/// </summary>
/// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name.
/// If this symbol has no type members with this name,
/// returns an empty ImmutableArray. Never returns null.</returns>
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
/// <summary>
/// Get all the members of this symbol that are types that have a particular name and arity
/// </summary>
/// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity.
/// If this symbol has no type members with this name and arity,
/// returns an empty ImmutableArray. Never returns null.</returns>
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
/// <summary>
/// Gets the kind of this symbol.
/// </summary>
public sealed override SymbolKind Kind
{
get
{
return SymbolKind.ErrorType;
}
}
/// <summary>
/// Gets the kind of this type.
/// </summary>
public sealed override TypeKind TypeKind
{
get
{
return TypeKind.Error;
}
}
internal sealed override bool IsInterface
{
get { return false; }
}
/// <summary>
/// Get the symbol that logically contains this symbol.
/// </summary>
public override Symbol? ContainingSymbol
{
get
{
return null;
}
}
/// <summary>
/// Gets the locations where this symbol was originally defined, either in source or
/// metadata. Some symbols (for example, partial classes) may be defined in more than one
/// location.
/// </summary>
public override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray<Location>.Empty;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
/// <summary>
/// Returns the arity of this type, or the number of type parameters it takes.
/// A non-generic type has zero arity.
/// </summary>
public override int Arity
{
get
{
return 0;
}
}
/// <summary>
/// Gets the name of this symbol. Symbols without a name return the empty string; null is
/// never returned.
/// </summary>
public override string Name
{
get
{
return string.Empty;
}
}
/// <summary>
/// Returns the type arguments that have been substituted for the type parameters.
/// If nothing has been substituted for a give type parameters,
/// then the type parameter itself is consider the type argument.
/// </summary>
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get
{
return GetTypeParametersAsTypeArguments();
}
}
/// <summary>
/// Returns the type parameters that this type has. If this is a non-generic type,
/// returns an empty ImmutableArray.
/// </summary>
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get
{
if (_lazyTypeParameters.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters,
GetTypeParameters(),
default(ImmutableArray<TypeParameterSymbol>));
}
return _lazyTypeParameters;
}
}
private ImmutableArray<TypeParameterSymbol> GetTypeParameters()
{
int arity = this.Arity;
if (arity == 0)
{
return ImmutableArray<TypeParameterSymbol>.Empty;
}
else
{
var @params = new TypeParameterSymbol[arity];
for (int i = 0; i < arity; i++)
{
@params[i] = new ErrorTypeParameterSymbol(this, string.Empty, i);
}
return @params.AsImmutableOrNull();
}
}
/// <summary>
/// Returns the type symbol that this type was constructed from. This type symbol
/// has the same containing type (if any), but has type arguments that are the same
/// as the type parameters (although its containing type might not).
/// </summary>
public override NamedTypeSymbol ConstructedFrom
{
get
{
return this;
}
}
/// <summary>
/// Implements visitor pattern.
/// </summary>
internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument)
{
return visitor.VisitErrorType(this, argument);
}
// Only the compiler should create error symbols.
internal ErrorTypeSymbol(TupleExtraData? tupleData = null)
: base(tupleData)
{
}
/// <summary>
/// Get this accessibility that was declared on this symbol. For symbols that do not have
/// accessibility declared on them, returns NotApplicable.
/// </summary>
public sealed override Accessibility DeclaredAccessibility
{
get
{
return Accessibility.NotApplicable;
}
}
/// <summary>
/// Returns true if this symbol is "static"; i.e., declared with the "static" modifier or
/// implicitly static.
/// </summary>
public sealed override bool IsStatic
{
get
{
return false;
}
}
/// <summary>
/// Returns true if this symbol was declared as requiring an override; i.e., declared with
/// the "abstract" modifier. Also returns true on a type declared as "abstract", all
/// interface types, and members of interface types.
/// </summary>
public sealed override bool IsAbstract
{
get
{
return false;
}
}
/// <summary>
/// Returns true if this symbol was declared to override a base class member and was also
/// sealed from further overriding; i.e., declared with the "sealed" modifier. Also set for
/// types that do not allow a derived class (declared with "sealed" or "static" or "struct"
/// or "enum" or "delegate").
/// </summary>
public sealed override bool IsSealed
{
get
{
return false;
}
}
internal sealed override bool HasSpecialName
{
get { return false; }
}
public sealed override bool MightContainExtensionMethods
{
get
{
return false;
}
}
internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null;
internal override bool HasCodeAnalysisEmbeddedAttribute => false;
internal override bool IsInterpolatedStringHandlerType => false;
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit()
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
internal override NamedTypeSymbol? GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
return null;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
protected override NamedTypeSymbol ConstructCore(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound)
{
return new ConstructedErrorTypeSymbol(this, typeArguments);
}
internal override NamedTypeSymbol AsMember(NamedTypeSymbol newOwner)
{
Debug.Assert(this.IsDefinition);
Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol?.OriginalDefinition));
return newOwner.IsDefinition ? this : new SubstitutedNestedErrorTypeSymbol(newOwner, this);
}
internal sealed override bool ShouldAddWinRTMembers
{
get { return false; }
}
internal sealed override bool IsWindowsRuntimeImport
{
get { return false; }
}
internal sealed override TypeLayout Layout
{
get { return default(TypeLayout); }
}
internal override CharSet MarshallingCharSet
{
get { return DefaultMarshallingCharSet; }
}
public sealed override bool IsSerializable
{
get { return false; }
}
internal sealed override bool HasDeclarativeSecurity
{
get { return false; }
}
internal sealed override bool IsComImport
{
get { return false; }
}
internal sealed override ObsoleteAttributeData? ObsoleteAttributeData
{
get { return null; }
}
internal sealed override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols()
{
return ImmutableArray<string>.Empty;
}
internal override AttributeUsageInfo GetAttributeUsageInfo()
{
return AttributeUsageInfo.Null;
}
internal virtual bool Unreported
{
get { return false; }
}
public sealed override bool AreLocalsZeroed
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal override NamedTypeSymbol? NativeIntegerUnderlyingType => null;
protected sealed override ISymbol CreateISymbol()
{
return new PublicModel.ErrorTypeSymbol(this, DefaultNullableAnnotation);
}
protected sealed override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
Debug.Assert(nullableAnnotation != DefaultNullableAnnotation);
return new PublicModel.ErrorTypeSymbol(this, nullableAnnotation);
}
internal sealed override bool IsRecord => false;
internal override bool IsRecordStruct => false;
internal sealed override bool HasPossibleWellKnownCloneMethod() => false;
internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>();
}
}
internal abstract class SubstitutedErrorTypeSymbol : ErrorTypeSymbol
{
private readonly ErrorTypeSymbol _originalDefinition;
private int _hashCode;
protected SubstitutedErrorTypeSymbol(ErrorTypeSymbol originalDefinition, TupleExtraData? tupleData = null)
: base(tupleData)
{
_originalDefinition = originalDefinition;
}
public override NamedTypeSymbol OriginalDefinition
{
get { return _originalDefinition; }
}
internal override bool MangleName
{
get { return _originalDefinition.MangleName; }
}
internal override DiagnosticInfo? ErrorInfo
{
get { return _originalDefinition.ErrorInfo; }
}
public override int Arity
{
get { return _originalDefinition.Arity; }
}
public override string Name
{
get { return _originalDefinition.Name; }
}
public override ImmutableArray<Location> Locations
{
get { return _originalDefinition.Locations; }
}
public override ImmutableArray<Symbol> CandidateSymbols
{
get { return _originalDefinition.CandidateSymbols; }
}
internal override LookupResultKind ResultKind
{
get { return _originalDefinition.ResultKind; }
}
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
return _originalDefinition.GetUseSiteInfo();
}
public override int GetHashCode()
{
if (_hashCode == 0)
{
_hashCode = this.ComputeHashCode();
}
return _hashCode;
}
}
internal sealed class ConstructedErrorTypeSymbol : SubstitutedErrorTypeSymbol
{
private readonly ErrorTypeSymbol _constructedFrom;
private readonly ImmutableArray<TypeWithAnnotations> _typeArgumentsWithAnnotations;
private readonly TypeMap _map;
public ConstructedErrorTypeSymbol(ErrorTypeSymbol constructedFrom, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, TupleExtraData? tupleData = null) :
base((ErrorTypeSymbol)constructedFrom.OriginalDefinition, tupleData)
{
_constructedFrom = constructedFrom;
_typeArgumentsWithAnnotations = typeArgumentsWithAnnotations;
_map = new TypeMap(constructedFrom.ContainingType, constructedFrom.OriginalDefinition.TypeParameters, typeArgumentsWithAnnotations);
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
{
return new ConstructedErrorTypeSymbol(_constructedFrom, _typeArgumentsWithAnnotations, tupleData: newData);
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _constructedFrom.TypeParameters; }
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get { return _typeArgumentsWithAnnotations; }
}
public override NamedTypeSymbol ConstructedFrom
{
get { return _constructedFrom; }
}
public override Symbol? ContainingSymbol
{
get { return _constructedFrom.ContainingSymbol; }
}
internal override TypeMap TypeSubstitution
{
get { return _map; }
}
}
internal sealed class SubstitutedNestedErrorTypeSymbol : SubstitutedErrorTypeSymbol
{
private readonly NamedTypeSymbol _containingSymbol;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly TypeMap _map;
public SubstitutedNestedErrorTypeSymbol(NamedTypeSymbol containingSymbol, ErrorTypeSymbol originalDefinition) :
base(originalDefinition)
{
_containingSymbol = containingSymbol;
_map = containingSymbol.TypeSubstitution.WithAlphaRename(originalDefinition, this, out _typeParameters);
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get { return GetTypeParametersAsTypeArguments(); }
}
public override NamedTypeSymbol ConstructedFrom
{
get { return this; }
}
public override Symbol ContainingSymbol
{
get { return _containingSymbol; }
}
internal override TypeMap TypeSubstitution
{
get { return _map; }
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
=> throw ExceptionUtilities.Unreachable;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Roslyn.Utilities;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// An ErrorSymbol is used when the compiler cannot determine a symbol object to return because
/// of an error. For example, if a field is declared "Goo x;", and the type "Goo" cannot be
/// found, an ErrorSymbol is returned when asking the field "x" what it's type is.
/// </summary>
internal abstract partial class ErrorTypeSymbol : NamedTypeSymbol
{
internal static readonly ErrorTypeSymbol UnknownResultType = new UnsupportedMetadataTypeSymbol();
private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters;
/// <summary>
/// The underlying error.
/// </summary>
internal abstract DiagnosticInfo? ErrorInfo { get; }
/// <summary>
/// Summary of the reason why the type is bad.
/// </summary>
internal virtual LookupResultKind ResultKind { get { return LookupResultKind.Empty; } }
/// <summary>
/// Called by <see cref="AbstractTypeMap.SubstituteType(TypeSymbol)"/> to perform substitution
/// on types with TypeKind ErrorType. The general pattern is to use the type map
/// to perform substitution on the wrapped type, if any, and then construct a new
/// error type symbol from the result (if there was a change).
/// </summary>
internal TypeWithAnnotations Substitute(AbstractTypeMap typeMap)
{
return TypeWithAnnotations.Create(typeMap.SubstituteNamedType(this));
}
/// <summary>
/// When constructing this ErrorTypeSymbol, there may have been symbols that seemed to
/// be what the user intended, but were unsuitable. For example, a type might have been
/// inaccessible, or ambiguous. This property returns the possible symbols that the user
/// might have intended. It will return no symbols if no possible symbols were found.
/// See the CandidateReason property to understand why the symbols were unsuitable.
/// </summary>
public virtual ImmutableArray<Symbol> CandidateSymbols
{
get
{
return ImmutableArray<Symbol>.Empty;
}
}
///<summary>
/// If CandidateSymbols returns one or more symbols, returns the reason that those
/// symbols were not chosen. Otherwise, returns None.
/// </summary>
public CandidateReason CandidateReason
{
get
{
if (!CandidateSymbols.IsEmpty)
{
Debug.Assert(ResultKind != LookupResultKind.Viable, "Shouldn't have viable result kind on error symbol");
return ResultKind.ToCandidateReason();
}
else
{
return CandidateReason.None;
}
}
}
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
return new UseSiteInfo<AssemblySymbol>(this.ErrorInfo);
}
/// <summary>
/// Returns true if this type is known to be a reference type. It is never the case that
/// IsReferenceType and IsValueType both return true. However, for an unconstrained type
/// parameter, IsReferenceType and IsValueType will both return false.
/// </summary>
public override bool IsReferenceType
{
// TODO: Consider returning False.
get { return true; }
}
/// <summary>
/// Returns true if this type is known to be a value type. It is never the case that
/// IsReferenceType and IsValueType both return true. However, for an unconstrained type
/// parameter, IsReferenceType and IsValueType will both return false.
/// </summary>
public sealed override bool IsValueType
{
get { return false; }
}
public sealed override bool IsRefLikeType
{
get
{
return false;
}
}
public sealed override bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Collection of names of members declared within this type.
/// </summary>
public override IEnumerable<string> MemberNames
{
get
{
return SpecializedCollections.EmptyEnumerable<string>();
}
}
/// <summary>
/// Get all the members of this symbol.
/// </summary>
/// <returns>An ImmutableArray containing all the members of this symbol. If this symbol has no members,
/// returns an empty ImmutableArray. Never returns Null.</returns>
public override ImmutableArray<Symbol> GetMembers()
{
if (IsTupleType)
{
var result = AddOrWrapTupleMembers(ImmutableArray<Symbol>.Empty);
RoslynDebug.Assert(result is object);
return result.ToImmutableAndFree();
}
return ImmutableArray<Symbol>.Empty;
}
/// <summary>
/// Get all the members of this symbol that have a particular name.
/// </summary>
/// <returns>An ImmutableArray containing all the members of this symbol with the given name. If there are
/// no members with this name, returns an empty ImmutableArray. Never returns Null.</returns>
public override ImmutableArray<Symbol> GetMembers(string name)
{
return GetMembers().WhereAsArray((m, name) => m.Name == name, name);
}
internal sealed override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return this.GetMembersUnordered();
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
return this.GetMembers(name);
}
/// <summary>
/// Get all the members of this symbol that are types.
/// </summary>
/// <returns>An ImmutableArray containing all the types that are members of this symbol. If this symbol has no type members,
/// returns an empty ImmutableArray. Never returns null.</returns>
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
/// <summary>
/// Get all the members of this symbol that are types that have a particular name, of any arity.
/// </summary>
/// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name.
/// If this symbol has no type members with this name,
/// returns an empty ImmutableArray. Never returns null.</returns>
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
/// <summary>
/// Get all the members of this symbol that are types that have a particular name and arity
/// </summary>
/// <returns>An ImmutableArray containing all the types that are members of this symbol with the given name and arity.
/// If this symbol has no type members with this name and arity,
/// returns an empty ImmutableArray. Never returns null.</returns>
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
/// <summary>
/// Gets the kind of this symbol.
/// </summary>
public sealed override SymbolKind Kind
{
get
{
return SymbolKind.ErrorType;
}
}
/// <summary>
/// Gets the kind of this type.
/// </summary>
public sealed override TypeKind TypeKind
{
get
{
return TypeKind.Error;
}
}
internal sealed override bool IsInterface
{
get { return false; }
}
/// <summary>
/// Get the symbol that logically contains this symbol.
/// </summary>
public override Symbol? ContainingSymbol
{
get
{
return null;
}
}
/// <summary>
/// Gets the locations where this symbol was originally defined, either in source or
/// metadata. Some symbols (for example, partial classes) may be defined in more than one
/// location.
/// </summary>
public override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray<Location>.Empty;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
/// <summary>
/// Returns the arity of this type, or the number of type parameters it takes.
/// A non-generic type has zero arity.
/// </summary>
public override int Arity
{
get
{
return 0;
}
}
/// <summary>
/// Gets the name of this symbol. Symbols without a name return the empty string; null is
/// never returned.
/// </summary>
public override string Name
{
get
{
return string.Empty;
}
}
/// <summary>
/// Returns the type arguments that have been substituted for the type parameters.
/// If nothing has been substituted for a give type parameters,
/// then the type parameter itself is consider the type argument.
/// </summary>
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get
{
return GetTypeParametersAsTypeArguments();
}
}
/// <summary>
/// Returns the type parameters that this type has. If this is a non-generic type,
/// returns an empty ImmutableArray.
/// </summary>
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get
{
if (_lazyTypeParameters.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters,
GetTypeParameters(),
default(ImmutableArray<TypeParameterSymbol>));
}
return _lazyTypeParameters;
}
}
private ImmutableArray<TypeParameterSymbol> GetTypeParameters()
{
int arity = this.Arity;
if (arity == 0)
{
return ImmutableArray<TypeParameterSymbol>.Empty;
}
else
{
var @params = new TypeParameterSymbol[arity];
for (int i = 0; i < arity; i++)
{
@params[i] = new ErrorTypeParameterSymbol(this, string.Empty, i);
}
return @params.AsImmutableOrNull();
}
}
/// <summary>
/// Returns the type symbol that this type was constructed from. This type symbol
/// has the same containing type (if any), but has type arguments that are the same
/// as the type parameters (although its containing type might not).
/// </summary>
public override NamedTypeSymbol ConstructedFrom
{
get
{
return this;
}
}
/// <summary>
/// Implements visitor pattern.
/// </summary>
internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument)
{
return visitor.VisitErrorType(this, argument);
}
// Only the compiler should create error symbols.
internal ErrorTypeSymbol(TupleExtraData? tupleData = null)
: base(tupleData)
{
}
/// <summary>
/// Get this accessibility that was declared on this symbol. For symbols that do not have
/// accessibility declared on them, returns NotApplicable.
/// </summary>
public sealed override Accessibility DeclaredAccessibility
{
get
{
return Accessibility.NotApplicable;
}
}
/// <summary>
/// Returns true if this symbol is "static"; i.e., declared with the "static" modifier or
/// implicitly static.
/// </summary>
public sealed override bool IsStatic
{
get
{
return false;
}
}
/// <summary>
/// Returns true if this symbol was declared as requiring an override; i.e., declared with
/// the "abstract" modifier. Also returns true on a type declared as "abstract", all
/// interface types, and members of interface types.
/// </summary>
public sealed override bool IsAbstract
{
get
{
return false;
}
}
/// <summary>
/// Returns true if this symbol was declared to override a base class member and was also
/// sealed from further overriding; i.e., declared with the "sealed" modifier. Also set for
/// types that do not allow a derived class (declared with "sealed" or "static" or "struct"
/// or "enum" or "delegate").
/// </summary>
public sealed override bool IsSealed
{
get
{
return false;
}
}
internal sealed override bool HasSpecialName
{
get { return false; }
}
public sealed override bool MightContainExtensionMethods
{
get
{
return false;
}
}
internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null;
internal override bool HasCodeAnalysisEmbeddedAttribute => false;
internal override bool IsInterpolatedStringHandlerType => false;
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit()
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
internal override NamedTypeSymbol? GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
return null;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
protected override NamedTypeSymbol ConstructCore(ImmutableArray<TypeWithAnnotations> typeArguments, bool unbound)
{
return new ConstructedErrorTypeSymbol(this, typeArguments);
}
internal override NamedTypeSymbol AsMember(NamedTypeSymbol newOwner)
{
Debug.Assert(this.IsDefinition);
Debug.Assert(ReferenceEquals(newOwner.OriginalDefinition, this.ContainingSymbol?.OriginalDefinition));
return newOwner.IsDefinition ? this : new SubstitutedNestedErrorTypeSymbol(newOwner, this);
}
internal sealed override bool ShouldAddWinRTMembers
{
get { return false; }
}
internal sealed override bool IsWindowsRuntimeImport
{
get { return false; }
}
internal sealed override TypeLayout Layout
{
get { return default(TypeLayout); }
}
internal override CharSet MarshallingCharSet
{
get { return DefaultMarshallingCharSet; }
}
public sealed override bool IsSerializable
{
get { return false; }
}
internal sealed override bool HasDeclarativeSecurity
{
get { return false; }
}
internal sealed override bool IsComImport
{
get { return false; }
}
internal sealed override ObsoleteAttributeData? ObsoleteAttributeData
{
get { return null; }
}
internal sealed override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols()
{
return ImmutableArray<string>.Empty;
}
internal override AttributeUsageInfo GetAttributeUsageInfo()
{
return AttributeUsageInfo.Null;
}
internal virtual bool Unreported
{
get { return false; }
}
public sealed override bool AreLocalsZeroed
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal override NamedTypeSymbol? NativeIntegerUnderlyingType => null;
protected sealed override ISymbol CreateISymbol()
{
return new PublicModel.ErrorTypeSymbol(this, DefaultNullableAnnotation);
}
protected sealed override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
Debug.Assert(nullableAnnotation != DefaultNullableAnnotation);
return new PublicModel.ErrorTypeSymbol(this, nullableAnnotation);
}
internal sealed override bool IsRecord => false;
internal override bool IsRecordStruct => false;
internal sealed override bool HasPossibleWellKnownCloneMethod() => false;
internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>();
}
}
internal abstract class SubstitutedErrorTypeSymbol : ErrorTypeSymbol
{
private readonly ErrorTypeSymbol _originalDefinition;
private int _hashCode;
protected SubstitutedErrorTypeSymbol(ErrorTypeSymbol originalDefinition, TupleExtraData? tupleData = null)
: base(tupleData)
{
_originalDefinition = originalDefinition;
}
public override NamedTypeSymbol OriginalDefinition
{
get { return _originalDefinition; }
}
internal override bool MangleName
{
get { return _originalDefinition.MangleName; }
}
internal override DiagnosticInfo? ErrorInfo
{
get { return _originalDefinition.ErrorInfo; }
}
public override int Arity
{
get { return _originalDefinition.Arity; }
}
public override string Name
{
get { return _originalDefinition.Name; }
}
public override ImmutableArray<Location> Locations
{
get { return _originalDefinition.Locations; }
}
public override ImmutableArray<Symbol> CandidateSymbols
{
get { return _originalDefinition.CandidateSymbols; }
}
internal override LookupResultKind ResultKind
{
get { return _originalDefinition.ResultKind; }
}
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
return _originalDefinition.GetUseSiteInfo();
}
public override int GetHashCode()
{
if (_hashCode == 0)
{
_hashCode = this.ComputeHashCode();
}
return _hashCode;
}
}
internal sealed class ConstructedErrorTypeSymbol : SubstitutedErrorTypeSymbol
{
private readonly ErrorTypeSymbol _constructedFrom;
private readonly ImmutableArray<TypeWithAnnotations> _typeArgumentsWithAnnotations;
private readonly TypeMap _map;
public ConstructedErrorTypeSymbol(ErrorTypeSymbol constructedFrom, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, TupleExtraData? tupleData = null) :
base((ErrorTypeSymbol)constructedFrom.OriginalDefinition, tupleData)
{
_constructedFrom = constructedFrom;
_typeArgumentsWithAnnotations = typeArgumentsWithAnnotations;
_map = new TypeMap(constructedFrom.ContainingType, constructedFrom.OriginalDefinition.TypeParameters, typeArgumentsWithAnnotations);
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
{
return new ConstructedErrorTypeSymbol(_constructedFrom, _typeArgumentsWithAnnotations, tupleData: newData);
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _constructedFrom.TypeParameters; }
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get { return _typeArgumentsWithAnnotations; }
}
public override NamedTypeSymbol ConstructedFrom
{
get { return _constructedFrom; }
}
public override Symbol? ContainingSymbol
{
get { return _constructedFrom.ContainingSymbol; }
}
internal override TypeMap TypeSubstitution
{
get { return _map; }
}
}
internal sealed class SubstitutedNestedErrorTypeSymbol : SubstitutedErrorTypeSymbol
{
private readonly NamedTypeSymbol _containingSymbol;
private readonly ImmutableArray<TypeParameterSymbol> _typeParameters;
private readonly TypeMap _map;
public SubstitutedNestedErrorTypeSymbol(NamedTypeSymbol containingSymbol, ErrorTypeSymbol originalDefinition) :
base(originalDefinition)
{
_containingSymbol = containingSymbol;
_map = containingSymbol.TypeSubstitution.WithAlphaRename(originalDefinition, this, out _typeParameters);
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return _typeParameters; }
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get { return GetTypeParametersAsTypeArguments(); }
}
public override NamedTypeSymbol ConstructedFrom
{
get { return this; }
}
public override Symbol ContainingSymbol
{
get { return _containingSymbol; }
}
internal override TypeMap TypeSubstitution
{
get { return _map; }
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
=> throw ExceptionUtilities.Unreachable;
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/MSBuildTest/NetCoreTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.CodeAnalysis.UnitTests.TestFiles;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.MSBuild.UnitTests
{
public class NetCoreTests : MSBuildWorkspaceTestBase
{
private readonly TempDirectory _nugetCacheDir;
public NetCoreTests()
{
_nugetCacheDir = SolutionDirectory.CreateDirectory(".packages");
}
private void RunDotNet(string arguments)
{
Assert.NotNull(DotNetCoreSdk.ExePath);
var environmentVariables = new Dictionary<string, string>()
{
["NUGET_PACKAGES"] = _nugetCacheDir.Path
};
var restoreResult = ProcessUtilities.Run(
DotNetCoreSdk.ExePath, arguments,
workingDirectory: SolutionDirectory.Path,
additionalEnvironmentVars: environmentVariables);
Assert.True(restoreResult.ExitCode == 0, $"{DotNetCoreSdk.ExePath} failed with exit code {restoreResult.ExitCode}: {restoreResult.Output}");
}
private void DotNetRestore(string solutionOrProjectFileName)
{
var arguments = $@"msbuild ""{solutionOrProjectFileName}"" /t:restore /bl:{Path.Combine(SolutionDirectory.Path, "restore.binlog")}";
RunDotNet(arguments);
}
private void DotNetBuild(string solutionOrProjectFileName, string configuration = null)
{
var arguments = $@"msbuild ""{solutionOrProjectFileName}"" /bl:{Path.Combine(SolutionDirectory.Path, "build.binlog")}";
if (configuration != null)
{
arguments += $" /p:Configuration={configuration}";
}
RunDotNet(arguments);
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_NetCoreApp2()
{
CreateFiles(GetNetCoreApp2Files());
var projectFilePath = GetSolutionFileName("Project.csproj");
DotNetRestore("Project.csproj");
using (var workspace = CreateMSBuildWorkspace())
{
var project = await workspace.OpenProjectAsync(projectFilePath);
// Assert that there is a single project loaded.
Assert.Single(workspace.CurrentSolution.ProjectIds);
// Assert that the project does not have any diagnostics in Program.cs
var document = project.Documents.First(d => d.Name == "Program.cs");
var semanticModel = await document.GetSemanticModelAsync();
var diagnostics = semanticModel.GetDiagnostics();
Assert.Empty(diagnostics);
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProjectTwice_NetCoreApp2AndLibrary()
{
CreateFiles(GetNetCoreApp2AndLibraryFiles());
var projectFilePath = GetSolutionFileName(@"Project\Project.csproj");
var libraryFilePath = GetSolutionFileName(@"Library\Library.csproj");
DotNetRestore(@"Project\Project.csproj");
using var workspace = CreateMSBuildWorkspace();
var libraryProject = await workspace.OpenProjectAsync(libraryFilePath);
// Assert that there is a single project loaded.
Assert.Single(workspace.CurrentSolution.ProjectIds);
// Assert that the project does not have any diagnostics in Class1.cs
var document = libraryProject.Documents.First(d => d.Name == "Class1.cs");
var semanticModel = await document.GetSemanticModelAsync();
var diagnostics = semanticModel.GetDiagnostics();
Assert.Empty(diagnostics);
var project = await workspace.OpenProjectAsync(projectFilePath);
// Assert that there are only two projects opened.
Assert.Equal(2, workspace.CurrentSolution.ProjectIds.Count);
// Assert that there is a project reference between Project.csproj and Library.csproj
var projectReference = Assert.Single(project.ProjectReferences);
var projectRefId = projectReference.ProjectId;
Assert.Equal(libraryProject.Id, projectRefId);
Assert.Equal(libraryProject.FilePath, workspace.CurrentSolution.GetProject(projectRefId).FilePath);
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProjectTwice_NetCoreApp2AndTwoLibraries()
{
CreateFiles(GetNetCoreApp2AndTwoLibrariesFiles());
var projectFilePath = GetSolutionFileName(@"Project\Project.csproj");
var library1FilePath = GetSolutionFileName(@"Library1\Library1.csproj");
var library2FilePath = GetSolutionFileName(@"Library2\Library2.csproj");
DotNetRestore(@"Project\Project.csproj");
DotNetRestore(@"Library2\Library2.csproj");
using (var workspace = CreateMSBuildWorkspace())
{
var project = await workspace.OpenProjectAsync(projectFilePath);
// Assert that there is are two projects loaded (Project.csproj references Library1.csproj).
Assert.Equal(2, workspace.CurrentSolution.ProjectIds.Count);
// Assert that the project does not have any diagnostics in Program.cs
var document = project.Documents.First(d => d.Name == "Program.cs");
var semanticModel = await document.GetSemanticModelAsync();
var diagnostics = semanticModel.GetDiagnostics();
Assert.Empty(diagnostics);
var library2 = await workspace.OpenProjectAsync(library2FilePath);
// Assert that there are now three projects loaded (Library2.csproj also references Library1.csproj)
Assert.Equal(3, workspace.CurrentSolution.ProjectIds.Count);
// Assert that there is a project reference between Project.csproj and Library1.csproj
AssertSingleProjectReference(project, library1FilePath);
// Assert that there is a project reference between Library2.csproj and Library1.csproj
AssertSingleProjectReference(library2, library1FilePath);
}
static void AssertSingleProjectReference(Project project, string projectRefFilePath)
{
var projectReference = Assert.Single(project.ProjectReferences);
var projectRefId = projectReference.ProjectId;
Assert.Equal(projectRefFilePath, project.Solution.GetProject(projectRefId).FilePath);
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_NetCoreMultiTFM()
{
CreateFiles(GetNetCoreMultiTFMFiles());
var projectFilePath = GetSolutionFileName("Project.csproj");
DotNetRestore("Project.csproj");
using (var workspace = CreateMSBuildWorkspace())
{
await workspace.OpenProjectAsync(projectFilePath);
// Assert that three projects have been loaded, one for each TFM.
Assert.Equal(3, workspace.CurrentSolution.ProjectIds.Count);
var projectPaths = new HashSet<string>();
var outputFilePaths = new HashSet<string>();
foreach (var project in workspace.CurrentSolution.Projects)
{
projectPaths.Add(project.FilePath);
outputFilePaths.Add(project.OutputFilePath);
}
// Assert that the three projects share the same file path
Assert.Single(projectPaths);
// Assert that the three projects have different output file paths
Assert.Equal(3, outputFilePaths.Count);
// Assert that none of the projects have any diagnostics in Program.cs
foreach (var project in workspace.CurrentSolution.Projects)
{
var document = project.Documents.First(d => d.Name == "Program.cs");
var semanticModel = await document.GetSemanticModelAsync();
var diagnostics = semanticModel.GetDiagnostics();
Assert.Empty(diagnostics);
}
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_NetCoreMultiTFM_ExtensionWithConditionOnTFM()
{
CreateFiles(GetNetCoreMultiTFMFiles_ExtensionWithConditionOnTFM());
var projectFilePath = GetSolutionFileName("Project.csproj");
DotNetRestore("Project.csproj");
using (var workspace = CreateMSBuildWorkspace())
{
await workspace.OpenProjectAsync(projectFilePath);
// Assert that three projects have been loaded, one for each TFM.
Assert.Equal(3, workspace.CurrentSolution.ProjectIds.Count);
// Assert the TFM is accessible from project extensions.
// The test project extension sets the default namespace based on the TFM.
foreach (var project in workspace.CurrentSolution.Projects)
{
switch (project.Name)
{
case "Project(netcoreapp2.1)":
Assert.Equal("Project.NetCore", project.DefaultNamespace);
break;
case "Project(netstandard2.0)":
Assert.Equal("Project.NetStandard", project.DefaultNamespace);
break;
case "Project(net461)":
Assert.Equal("Project.NetFramework", project.DefaultNamespace);
break;
default:
Assert.True(false, $"Unexpected project: {project.Name}");
break;
}
}
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_NetCoreMultiTFM_ProjectReference()
{
CreateFiles(GetNetCoreMultiTFMFiles_ProjectReference());
// Restoring for Project.csproj should also restore Library.csproj
DotNetRestore(@"Project\Project.csproj");
var projectFilePath = GetSolutionFileName(@"Project\Project.csproj");
await AssertNetCoreMultiTFMProject(projectFilePath);
}
private static async Task AssertNetCoreMultiTFMProject(string projectFilePath)
{
using (var workspace = CreateMSBuildWorkspace())
{
await workspace.OpenProjectAsync(projectFilePath);
// Assert that four projects have been loaded, one for each TFM.
Assert.Equal(4, workspace.CurrentSolution.ProjectIds.Count);
var projectPaths = new HashSet<string>();
var outputFilePaths = new HashSet<string>();
foreach (var project in workspace.CurrentSolution.Projects)
{
projectPaths.Add(project.FilePath);
outputFilePaths.Add(project.OutputFilePath);
}
// Assert that there are two project file path among the four projects
Assert.Equal(2, projectPaths.Count);
// Assert that the four projects each have different output file paths
Assert.Equal(4, outputFilePaths.Count);
var expectedNames = new HashSet<string>()
{
"Library(netstandard2",
"Library(net461)",
"Project(netcoreapp2",
"Project(net461)"
};
var actualNames = new HashSet<string>();
foreach (var project in workspace.CurrentSolution.Projects)
{
var dotIndex = project.Name.IndexOf('.');
var projectName = dotIndex >= 0
? project.Name.Substring(0, dotIndex)
: project.Name;
actualNames.Add(projectName);
var fileName = PathUtilities.GetFileName(project.FilePath);
Document document;
switch (fileName)
{
case "Project.csproj":
document = project.Documents.First(d => d.Name == "Program.cs");
break;
case "Library.csproj":
document = project.Documents.First(d => d.Name == "Class1.cs");
break;
default:
Assert.True(false, $"Encountered unexpected project: {project.FilePath}");
return;
}
// Assert that none of the projects have any diagnostics in their primary .cs file.
var semanticModel = await document.GetSemanticModelAsync();
var diagnostics = semanticModel.GetDiagnostics();
Assert.Empty(diagnostics);
}
Assert.True(actualNames.SetEquals(expectedNames), $"Project names differ!{Environment.NewLine}Actual: {{{actualNames.Join(",")}}}{Environment.NewLine}Expected: {{{expectedNames.Join(",")}}}");
// Verify that the projects reference the correct TFMs
var projects = workspace.CurrentSolution.Projects.Where(p => p.FilePath.EndsWith("Project.csproj"));
foreach (var project in projects)
{
var projectReference = Assert.Single(project.ProjectReferences);
var referencedProject = workspace.CurrentSolution.GetProject(projectReference.ProjectId);
if (project.OutputFilePath.Contains("netcoreapp2"))
{
Assert.Contains("netstandard2", referencedProject.OutputFilePath);
}
else if (project.OutputFilePath.Contains("net461"))
{
Assert.Contains("net461", referencedProject.OutputFilePath);
}
else
{
Assert.True(false, "OutputFilePath with expected TFM not found.");
}
}
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/41917")]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenSolution_NetCoreMultiTFMWithProjectReferenceToFSharp()
{
CreateFiles(GetNetCoreMultiTFMFiles_ProjectReferenceToFSharp());
var solutionFilePath = GetSolutionFileName("Solution.sln");
DotNetRestore("Solution.sln");
using (var workspace = CreateMSBuildWorkspace())
{
var solution = await workspace.OpenSolutionAsync(solutionFilePath);
var projects = solution.Projects.ToArray();
Assert.Equal(2, projects.Length);
foreach (var project in projects)
{
Assert.StartsWith("csharplib", project.Name);
Assert.Empty(project.ProjectReferences);
Assert.Single(project.AllProjectReferences);
}
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_ReferenceConfigurationSpecificMetadata()
{
var files = GetBaseFiles()
.WithFile(@"Solution.sln", Resources.SolutionFiles.Issue30174_Solution)
.WithFile(@"InspectedLibrary\InspectedLibrary.csproj", Resources.ProjectFiles.CSharp.Issue30174_InspectedLibrary)
.WithFile(@"InspectedLibrary\InspectedClass.cs", Resources.SourceFiles.CSharp.Issue30174_InspectedClass)
.WithFile(@"ReferencedLibrary\ReferencedLibrary.csproj", Resources.ProjectFiles.CSharp.Issue30174_ReferencedLibrary)
.WithFile(@"ReferencedLibrary\SomeMetadataAttribute.cs", Resources.SourceFiles.CSharp.Issue30174_SomeMetadataAttribute);
CreateFiles(files);
DotNetRestore("Solution.sln");
DotNetBuild("Solution.sln", configuration: "Release");
var projectFilePath = GetSolutionFileName(@"InspectedLibrary\InspectedLibrary.csproj");
using (var workspace = CreateMSBuildWorkspace(("Configuration", "Release")))
{
workspace.LoadMetadataForReferencedProjects = true;
var project = await workspace.OpenProjectAsync(projectFilePath);
Assert.Empty(project.ProjectReferences);
Assert.Empty(workspace.Diagnostics);
var compilation = await project.GetCompilationAsync();
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_OverrideTFM()
{
CreateFiles(GetNetCoreApp2AndLibraryFiles());
var projectFilePath = GetSolutionFileName(@"Library\Library.csproj");
DotNetRestore(@"Library\Library.csproj");
// Override the TFM properties defined in the file
using (var workspace = CreateMSBuildWorkspace((PropertyNames.TargetFramework, ""), (PropertyNames.TargetFrameworks, "netcoreapp2.1;net461")))
{
await workspace.OpenProjectAsync(projectFilePath);
// Assert that two projects have been loaded, one for each TFM.
Assert.Equal(2, workspace.CurrentSolution.ProjectIds.Count);
Assert.Contains(workspace.CurrentSolution.Projects, p => p.Name == "Library(netcoreapp2.1)");
Assert.Contains(workspace.CurrentSolution.Projects, p => p.Name == "Library(net461)");
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.CodeAnalysis.UnitTests.TestFiles;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.MSBuild.UnitTests
{
public class NetCoreTests : MSBuildWorkspaceTestBase
{
private readonly TempDirectory _nugetCacheDir;
public NetCoreTests()
{
_nugetCacheDir = SolutionDirectory.CreateDirectory(".packages");
}
private void RunDotNet(string arguments)
{
Assert.NotNull(DotNetCoreSdk.ExePath);
var environmentVariables = new Dictionary<string, string>()
{
["NUGET_PACKAGES"] = _nugetCacheDir.Path
};
var restoreResult = ProcessUtilities.Run(
DotNetCoreSdk.ExePath, arguments,
workingDirectory: SolutionDirectory.Path,
additionalEnvironmentVars: environmentVariables);
Assert.True(restoreResult.ExitCode == 0, $"{DotNetCoreSdk.ExePath} failed with exit code {restoreResult.ExitCode}: {restoreResult.Output}");
}
private void DotNetRestore(string solutionOrProjectFileName)
{
var arguments = $@"msbuild ""{solutionOrProjectFileName}"" /t:restore /bl:{Path.Combine(SolutionDirectory.Path, "restore.binlog")}";
RunDotNet(arguments);
}
private void DotNetBuild(string solutionOrProjectFileName, string configuration = null)
{
var arguments = $@"msbuild ""{solutionOrProjectFileName}"" /bl:{Path.Combine(SolutionDirectory.Path, "build.binlog")}";
if (configuration != null)
{
arguments += $" /p:Configuration={configuration}";
}
RunDotNet(arguments);
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_NetCoreApp2()
{
CreateFiles(GetNetCoreApp2Files());
var projectFilePath = GetSolutionFileName("Project.csproj");
DotNetRestore("Project.csproj");
using (var workspace = CreateMSBuildWorkspace())
{
var project = await workspace.OpenProjectAsync(projectFilePath);
// Assert that there is a single project loaded.
Assert.Single(workspace.CurrentSolution.ProjectIds);
// Assert that the project does not have any diagnostics in Program.cs
var document = project.Documents.First(d => d.Name == "Program.cs");
var semanticModel = await document.GetSemanticModelAsync();
var diagnostics = semanticModel.GetDiagnostics();
Assert.Empty(diagnostics);
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProjectTwice_NetCoreApp2AndLibrary()
{
CreateFiles(GetNetCoreApp2AndLibraryFiles());
var projectFilePath = GetSolutionFileName(@"Project\Project.csproj");
var libraryFilePath = GetSolutionFileName(@"Library\Library.csproj");
DotNetRestore(@"Project\Project.csproj");
using var workspace = CreateMSBuildWorkspace();
var libraryProject = await workspace.OpenProjectAsync(libraryFilePath);
// Assert that there is a single project loaded.
Assert.Single(workspace.CurrentSolution.ProjectIds);
// Assert that the project does not have any diagnostics in Class1.cs
var document = libraryProject.Documents.First(d => d.Name == "Class1.cs");
var semanticModel = await document.GetSemanticModelAsync();
var diagnostics = semanticModel.GetDiagnostics();
Assert.Empty(diagnostics);
var project = await workspace.OpenProjectAsync(projectFilePath);
// Assert that there are only two projects opened.
Assert.Equal(2, workspace.CurrentSolution.ProjectIds.Count);
// Assert that there is a project reference between Project.csproj and Library.csproj
var projectReference = Assert.Single(project.ProjectReferences);
var projectRefId = projectReference.ProjectId;
Assert.Equal(libraryProject.Id, projectRefId);
Assert.Equal(libraryProject.FilePath, workspace.CurrentSolution.GetProject(projectRefId).FilePath);
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProjectTwice_NetCoreApp2AndTwoLibraries()
{
CreateFiles(GetNetCoreApp2AndTwoLibrariesFiles());
var projectFilePath = GetSolutionFileName(@"Project\Project.csproj");
var library1FilePath = GetSolutionFileName(@"Library1\Library1.csproj");
var library2FilePath = GetSolutionFileName(@"Library2\Library2.csproj");
DotNetRestore(@"Project\Project.csproj");
DotNetRestore(@"Library2\Library2.csproj");
using (var workspace = CreateMSBuildWorkspace())
{
var project = await workspace.OpenProjectAsync(projectFilePath);
// Assert that there is are two projects loaded (Project.csproj references Library1.csproj).
Assert.Equal(2, workspace.CurrentSolution.ProjectIds.Count);
// Assert that the project does not have any diagnostics in Program.cs
var document = project.Documents.First(d => d.Name == "Program.cs");
var semanticModel = await document.GetSemanticModelAsync();
var diagnostics = semanticModel.GetDiagnostics();
Assert.Empty(diagnostics);
var library2 = await workspace.OpenProjectAsync(library2FilePath);
// Assert that there are now three projects loaded (Library2.csproj also references Library1.csproj)
Assert.Equal(3, workspace.CurrentSolution.ProjectIds.Count);
// Assert that there is a project reference between Project.csproj and Library1.csproj
AssertSingleProjectReference(project, library1FilePath);
// Assert that there is a project reference between Library2.csproj and Library1.csproj
AssertSingleProjectReference(library2, library1FilePath);
}
static void AssertSingleProjectReference(Project project, string projectRefFilePath)
{
var projectReference = Assert.Single(project.ProjectReferences);
var projectRefId = projectReference.ProjectId;
Assert.Equal(projectRefFilePath, project.Solution.GetProject(projectRefId).FilePath);
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_NetCoreMultiTFM()
{
CreateFiles(GetNetCoreMultiTFMFiles());
var projectFilePath = GetSolutionFileName("Project.csproj");
DotNetRestore("Project.csproj");
using (var workspace = CreateMSBuildWorkspace())
{
await workspace.OpenProjectAsync(projectFilePath);
// Assert that three projects have been loaded, one for each TFM.
Assert.Equal(3, workspace.CurrentSolution.ProjectIds.Count);
var projectPaths = new HashSet<string>();
var outputFilePaths = new HashSet<string>();
foreach (var project in workspace.CurrentSolution.Projects)
{
projectPaths.Add(project.FilePath);
outputFilePaths.Add(project.OutputFilePath);
}
// Assert that the three projects share the same file path
Assert.Single(projectPaths);
// Assert that the three projects have different output file paths
Assert.Equal(3, outputFilePaths.Count);
// Assert that none of the projects have any diagnostics in Program.cs
foreach (var project in workspace.CurrentSolution.Projects)
{
var document = project.Documents.First(d => d.Name == "Program.cs");
var semanticModel = await document.GetSemanticModelAsync();
var diagnostics = semanticModel.GetDiagnostics();
Assert.Empty(diagnostics);
}
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_NetCoreMultiTFM_ExtensionWithConditionOnTFM()
{
CreateFiles(GetNetCoreMultiTFMFiles_ExtensionWithConditionOnTFM());
var projectFilePath = GetSolutionFileName("Project.csproj");
DotNetRestore("Project.csproj");
using (var workspace = CreateMSBuildWorkspace())
{
await workspace.OpenProjectAsync(projectFilePath);
// Assert that three projects have been loaded, one for each TFM.
Assert.Equal(3, workspace.CurrentSolution.ProjectIds.Count);
// Assert the TFM is accessible from project extensions.
// The test project extension sets the default namespace based on the TFM.
foreach (var project in workspace.CurrentSolution.Projects)
{
switch (project.Name)
{
case "Project(netcoreapp2.1)":
Assert.Equal("Project.NetCore", project.DefaultNamespace);
break;
case "Project(netstandard2.0)":
Assert.Equal("Project.NetStandard", project.DefaultNamespace);
break;
case "Project(net461)":
Assert.Equal("Project.NetFramework", project.DefaultNamespace);
break;
default:
Assert.True(false, $"Unexpected project: {project.Name}");
break;
}
}
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_NetCoreMultiTFM_ProjectReference()
{
CreateFiles(GetNetCoreMultiTFMFiles_ProjectReference());
// Restoring for Project.csproj should also restore Library.csproj
DotNetRestore(@"Project\Project.csproj");
var projectFilePath = GetSolutionFileName(@"Project\Project.csproj");
await AssertNetCoreMultiTFMProject(projectFilePath);
}
private static async Task AssertNetCoreMultiTFMProject(string projectFilePath)
{
using (var workspace = CreateMSBuildWorkspace())
{
await workspace.OpenProjectAsync(projectFilePath);
// Assert that four projects have been loaded, one for each TFM.
Assert.Equal(4, workspace.CurrentSolution.ProjectIds.Count);
var projectPaths = new HashSet<string>();
var outputFilePaths = new HashSet<string>();
foreach (var project in workspace.CurrentSolution.Projects)
{
projectPaths.Add(project.FilePath);
outputFilePaths.Add(project.OutputFilePath);
}
// Assert that there are two project file path among the four projects
Assert.Equal(2, projectPaths.Count);
// Assert that the four projects each have different output file paths
Assert.Equal(4, outputFilePaths.Count);
var expectedNames = new HashSet<string>()
{
"Library(netstandard2",
"Library(net461)",
"Project(netcoreapp2",
"Project(net461)"
};
var actualNames = new HashSet<string>();
foreach (var project in workspace.CurrentSolution.Projects)
{
var dotIndex = project.Name.IndexOf('.');
var projectName = dotIndex >= 0
? project.Name.Substring(0, dotIndex)
: project.Name;
actualNames.Add(projectName);
var fileName = PathUtilities.GetFileName(project.FilePath);
Document document;
switch (fileName)
{
case "Project.csproj":
document = project.Documents.First(d => d.Name == "Program.cs");
break;
case "Library.csproj":
document = project.Documents.First(d => d.Name == "Class1.cs");
break;
default:
Assert.True(false, $"Encountered unexpected project: {project.FilePath}");
return;
}
// Assert that none of the projects have any diagnostics in their primary .cs file.
var semanticModel = await document.GetSemanticModelAsync();
var diagnostics = semanticModel.GetDiagnostics();
Assert.Empty(diagnostics);
}
Assert.True(actualNames.SetEquals(expectedNames), $"Project names differ!{Environment.NewLine}Actual: {{{actualNames.Join(",")}}}{Environment.NewLine}Expected: {{{expectedNames.Join(",")}}}");
// Verify that the projects reference the correct TFMs
var projects = workspace.CurrentSolution.Projects.Where(p => p.FilePath.EndsWith("Project.csproj"));
foreach (var project in projects)
{
var projectReference = Assert.Single(project.ProjectReferences);
var referencedProject = workspace.CurrentSolution.GetProject(projectReference.ProjectId);
if (project.OutputFilePath.Contains("netcoreapp2"))
{
Assert.Contains("netstandard2", referencedProject.OutputFilePath);
}
else if (project.OutputFilePath.Contains("net461"))
{
Assert.Contains("net461", referencedProject.OutputFilePath);
}
else
{
Assert.True(false, "OutputFilePath with expected TFM not found.");
}
}
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable), AlwaysSkip = "https://github.com/dotnet/roslyn/issues/41917")]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenSolution_NetCoreMultiTFMWithProjectReferenceToFSharp()
{
CreateFiles(GetNetCoreMultiTFMFiles_ProjectReferenceToFSharp());
var solutionFilePath = GetSolutionFileName("Solution.sln");
DotNetRestore("Solution.sln");
using (var workspace = CreateMSBuildWorkspace())
{
var solution = await workspace.OpenSolutionAsync(solutionFilePath);
var projects = solution.Projects.ToArray();
Assert.Equal(2, projects.Length);
foreach (var project in projects)
{
Assert.StartsWith("csharplib", project.Name);
Assert.Empty(project.ProjectReferences);
Assert.Single(project.AllProjectReferences);
}
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_ReferenceConfigurationSpecificMetadata()
{
var files = GetBaseFiles()
.WithFile(@"Solution.sln", Resources.SolutionFiles.Issue30174_Solution)
.WithFile(@"InspectedLibrary\InspectedLibrary.csproj", Resources.ProjectFiles.CSharp.Issue30174_InspectedLibrary)
.WithFile(@"InspectedLibrary\InspectedClass.cs", Resources.SourceFiles.CSharp.Issue30174_InspectedClass)
.WithFile(@"ReferencedLibrary\ReferencedLibrary.csproj", Resources.ProjectFiles.CSharp.Issue30174_ReferencedLibrary)
.WithFile(@"ReferencedLibrary\SomeMetadataAttribute.cs", Resources.SourceFiles.CSharp.Issue30174_SomeMetadataAttribute);
CreateFiles(files);
DotNetRestore("Solution.sln");
DotNetBuild("Solution.sln", configuration: "Release");
var projectFilePath = GetSolutionFileName(@"InspectedLibrary\InspectedLibrary.csproj");
using (var workspace = CreateMSBuildWorkspace(("Configuration", "Release")))
{
workspace.LoadMetadataForReferencedProjects = true;
var project = await workspace.OpenProjectAsync(projectFilePath);
Assert.Empty(project.ProjectReferences);
Assert.Empty(workspace.Diagnostics);
var compilation = await project.GetCompilationAsync();
}
}
[ConditionalFact(typeof(VisualStudioMSBuildInstalled), typeof(DotNetCoreSdk.IsAvailable))]
[Trait(Traits.Feature, Traits.Features.MSBuildWorkspace)]
[Trait(Traits.Feature, Traits.Features.NetCore)]
public async Task TestOpenProject_OverrideTFM()
{
CreateFiles(GetNetCoreApp2AndLibraryFiles());
var projectFilePath = GetSolutionFileName(@"Library\Library.csproj");
DotNetRestore(@"Library\Library.csproj");
// Override the TFM properties defined in the file
using (var workspace = CreateMSBuildWorkspace((PropertyNames.TargetFramework, ""), (PropertyNames.TargetFrameworks, "netcoreapp2.1;net461")))
{
await workspace.OpenProjectAsync(projectFilePath);
// Assert that two projects have been loaded, one for each TFM.
Assert.Equal(2, workspace.CurrentSolution.ProjectIds.Count);
Assert.Contains(workspace.CurrentSolution.Projects, p => p.Name == "Library(netcoreapp2.1)");
Assert.Contains(workspace.CurrentSolution.Projects, p => p.Name == "Library(net461)");
}
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Test/Semantic/Semantics/ScriptTestFixtures.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities
{
public static class ScriptTestFixtures
{
internal static MetadataReference HostRef = MetadataReference.CreateFromAssemblyInternal(typeof(ScriptTestFixtures).GetTypeInfo().Assembly);
public class B
{
public int x = 1, w = 4;
}
public class C : B, I
{
public static readonly int StaticField = 123;
public int Y => 2;
public string N { get; set; } = "2";
public int Z() => 3;
public override int GetHashCode() => 123;
}
public interface I
{
string N { get; set; }
int Z();
}
private class PrivateClass : I
{
public string N { get; set; } = null;
public int Z() => 3;
}
public class B2
{
public int x = 1, w = 4;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CSharp.Test.Utilities
{
public static class ScriptTestFixtures
{
internal static MetadataReference HostRef = MetadataReference.CreateFromAssemblyInternal(typeof(ScriptTestFixtures).GetTypeInfo().Assembly);
public class B
{
public int x = 1, w = 4;
}
public class C : B, I
{
public static readonly int StaticField = 123;
public int Y => 2;
public string N { get; set; } = "2";
public int Z() => 3;
public override int GetHashCode() => 123;
}
public interface I
{
string N { get; set; }
int Z();
}
private class PrivateClass : I
{
public string N { get; set; } = null;
public int Z() => 3;
}
public class B2
{
public int x = 1, w = 4;
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Tools/ExternalAccess/FSharp/Editor/FindUsages/IFSharpFindUsagesService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.FindUsages
{
internal interface IFSharpFindUsagesService
{
/// <summary>
/// Finds the references for the symbol at the specific position in the document,
/// pushing the results into the context instance.
/// </summary>
Task FindReferencesAsync(Document document, int position, IFSharpFindUsagesContext context);
/// <summary>
/// Finds the implementations for the symbol at the specific position in the document,
/// pushing the results into the context instance.
/// </summary>
Task FindImplementationsAsync(Document document, int position, IFSharpFindUsagesContext context);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor.FindUsages
{
internal interface IFSharpFindUsagesService
{
/// <summary>
/// Finds the references for the symbol at the specific position in the document,
/// pushing the results into the context instance.
/// </summary>
Task FindReferencesAsync(Document document, int position, IFSharpFindUsagesContext context);
/// <summary>
/// Finds the implementations for the symbol at the specific position in the document,
/// pushing the results into the context instance.
/// </summary>
Task FindImplementationsAsync(Document document, int position, IFSharpFindUsagesContext context);
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/SyntaxFacts/ExternalSourceInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal struct ExternalSourceInfo
{
public readonly int? StartLine;
public readonly bool Ends;
public ExternalSourceInfo(int? startLine, bool ends)
{
this.StartLine = startLine;
this.Ends = ends;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal struct ExternalSourceInfo
{
public readonly int? StartLine;
public readonly bool Ends;
public ExternalSourceInfo(int? startLine, bool ends)
{
this.StartLine = startLine;
this.Ends = ends;
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/VisualBasicTest/Classification/AbstractVisualBasicClassifierTests.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
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Classification
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Classification
Public MustInherit Class AbstractVisualBasicClassifierTests
Inherits AbstractClassifierTests
Protected Shared Function CreateWorkspace(code As String, testHost As TestHost) As TestWorkspace
Return TestWorkspace.CreateVisualBasic(code, composition:=EditorTestCompositions.EditorFeatures.WithTestHostParts(testHost))
End Function
Protected Overrides Function DefaultTestAsync(code As String, allCode As String, testHost As TestHost, expected() As FormattedClassification) As Task
Return TestAsync(code, allCode, testHost, parseOptions:=Nothing, expected)
End Function
Protected Overrides Function WrapInClass(className As String, code As String) As String
Return _
$"Class {className}
{code}
End Class"
End Function
Protected Overrides Function WrapInExpression(code As String) As String
Return _
$"Class C
Sub M()
dim q = {code}
End Sub
End Class"
End Function
Protected Overrides Function WrapInMethod(className As String, methodName As String, code As String) As String
Return _
$"Class {className}
Sub {methodName}()
{code}
End Sub
End Class"
End Function
Protected Overrides Function WrapInNamespace(code As String) As String
Return _
$"Namespace N
{code}
End Namespace"
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
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Classification
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Remote.Testing
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Classification
Public MustInherit Class AbstractVisualBasicClassifierTests
Inherits AbstractClassifierTests
Protected Shared Function CreateWorkspace(code As String, testHost As TestHost) As TestWorkspace
Return TestWorkspace.CreateVisualBasic(code, composition:=EditorTestCompositions.EditorFeatures.WithTestHostParts(testHost))
End Function
Protected Overrides Function DefaultTestAsync(code As String, allCode As String, testHost As TestHost, expected() As FormattedClassification) As Task
Return TestAsync(code, allCode, testHost, parseOptions:=Nothing, expected)
End Function
Protected Overrides Function WrapInClass(className As String, code As String) As String
Return _
$"Class {className}
{code}
End Class"
End Function
Protected Overrides Function WrapInExpression(code As String) As String
Return _
$"Class C
Sub M()
dim q = {code}
End Sub
End Class"
End Function
Protected Overrides Function WrapInMethod(className As String, methodName As String, code As String) As String
Return _
$"Class {className}
Sub {methodName}()
{code}
End Sub
End Class"
End Function
Protected Overrides Function WrapInNamespace(code As String) As String
Return _
$"Namespace N
{code}
End Namespace"
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Features/VisualBasic/Portable/CodeFixes/AddMissingReference/VisualBasicAddMissingReferenceCodeFixProvider.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 System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.AddMissingReference
Imports Microsoft.CodeAnalysis.CodeFixes
Namespace Microsoft.CodeAnalysis.VisualBasic.AddMissingReference
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.AddMissingReference), [Shared]>
<ExtensionOrder(After:=PredefinedCodeFixProviderNames.SimplifyNames)>
Friend Class VisualBasicAddMissingReferenceCodeFixProvider
Inherits AbstractAddMissingReferenceCodeFixProvider
Friend Const BC30005 As String = "BC30005" ' ERR_UnreferencedAssemblyEvent3
Friend Const BC30652 As String = "BC30652" ' ERR_UnreferencedAssembly3
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) =
ImmutableArray.Create(BC30005, BC30652)
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 System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.AddMissingReference
Imports Microsoft.CodeAnalysis.CodeFixes
Namespace Microsoft.CodeAnalysis.VisualBasic.AddMissingReference
<ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.AddMissingReference), [Shared]>
<ExtensionOrder(After:=PredefinedCodeFixProviderNames.SimplifyNames)>
Friend Class VisualBasicAddMissingReferenceCodeFixProvider
Inherits AbstractAddMissingReferenceCodeFixProvider
Friend Const BC30005 As String = "BC30005" ' ERR_UnreferencedAssemblyEvent3
Friend Const BC30652 As String = "BC30652" ' ERR_UnreferencedAssembly3
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) =
ImmutableArray.Create(BC30005, BC30652)
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForPropertiesHelper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
internal class UseExpressionBodyForPropertiesHelper :
UseExpressionBodyHelper<PropertyDeclarationSyntax>
{
public static readonly UseExpressionBodyForPropertiesHelper Instance = new();
private UseExpressionBodyForPropertiesHelper()
: base(IDEDiagnosticIds.UseExpressionBodyForPropertiesDiagnosticId,
EnforceOnBuildValues.UseExpressionBodyForProperties,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_properties), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_properties), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
CSharpCodeStyleOptions.PreferExpressionBodiedProperties,
ImmutableArray.Create(SyntaxKind.PropertyDeclaration))
{
}
protected override BlockSyntax GetBody(PropertyDeclarationSyntax declaration)
=> GetBodyFromSingleGetAccessor(declaration.AccessorList);
protected override ArrowExpressionClauseSyntax GetExpressionBody(PropertyDeclarationSyntax declaration)
=> declaration.ExpressionBody;
protected override SyntaxToken GetSemicolonToken(PropertyDeclarationSyntax declaration)
=> declaration.SemicolonToken;
protected override PropertyDeclarationSyntax WithSemicolonToken(PropertyDeclarationSyntax declaration, SyntaxToken token)
=> declaration.WithSemicolonToken(token);
protected override PropertyDeclarationSyntax WithExpressionBody(PropertyDeclarationSyntax declaration, ArrowExpressionClauseSyntax expressionBody)
=> declaration.WithExpressionBody(expressionBody);
protected override PropertyDeclarationSyntax WithAccessorList(PropertyDeclarationSyntax declaration, AccessorListSyntax accessorListSyntax)
=> declaration.WithAccessorList(accessorListSyntax);
protected override PropertyDeclarationSyntax WithBody(PropertyDeclarationSyntax declaration, BlockSyntax body)
{
if (body == null)
{
return declaration.WithAccessorList(null);
}
throw new InvalidOperationException();
}
protected override PropertyDeclarationSyntax WithGenerateBody(SemanticModel semanticModel, PropertyDeclarationSyntax declaration)
=> WithAccessorList(semanticModel, declaration);
protected override bool CreateReturnStatementForExpression(SemanticModel semanticModel, PropertyDeclarationSyntax declaration) => true;
protected override bool TryConvertToExpressionBody(
PropertyDeclarationSyntax declaration, ParseOptions options,
ExpressionBodyPreference conversionPreference,
out ArrowExpressionClauseSyntax arrowExpression,
out SyntaxToken semicolonToken)
{
return TryConvertToExpressionBodyForBaseProperty(
declaration, options, conversionPreference,
out arrowExpression, out semicolonToken);
}
protected override Location GetDiagnosticLocation(PropertyDeclarationSyntax declaration)
{
var body = GetBody(declaration);
if (body != null)
{
return base.GetDiagnosticLocation(declaration);
}
var getAccessor = GetSingleGetAccessor(declaration.AccessorList);
return getAccessor.ExpressionBody.GetLocation();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody
{
internal class UseExpressionBodyForPropertiesHelper :
UseExpressionBodyHelper<PropertyDeclarationSyntax>
{
public static readonly UseExpressionBodyForPropertiesHelper Instance = new();
private UseExpressionBodyForPropertiesHelper()
: base(IDEDiagnosticIds.UseExpressionBodyForPropertiesDiagnosticId,
EnforceOnBuildValues.UseExpressionBodyForProperties,
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_properties), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_properties), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)),
CSharpCodeStyleOptions.PreferExpressionBodiedProperties,
ImmutableArray.Create(SyntaxKind.PropertyDeclaration))
{
}
protected override BlockSyntax GetBody(PropertyDeclarationSyntax declaration)
=> GetBodyFromSingleGetAccessor(declaration.AccessorList);
protected override ArrowExpressionClauseSyntax GetExpressionBody(PropertyDeclarationSyntax declaration)
=> declaration.ExpressionBody;
protected override SyntaxToken GetSemicolonToken(PropertyDeclarationSyntax declaration)
=> declaration.SemicolonToken;
protected override PropertyDeclarationSyntax WithSemicolonToken(PropertyDeclarationSyntax declaration, SyntaxToken token)
=> declaration.WithSemicolonToken(token);
protected override PropertyDeclarationSyntax WithExpressionBody(PropertyDeclarationSyntax declaration, ArrowExpressionClauseSyntax expressionBody)
=> declaration.WithExpressionBody(expressionBody);
protected override PropertyDeclarationSyntax WithAccessorList(PropertyDeclarationSyntax declaration, AccessorListSyntax accessorListSyntax)
=> declaration.WithAccessorList(accessorListSyntax);
protected override PropertyDeclarationSyntax WithBody(PropertyDeclarationSyntax declaration, BlockSyntax body)
{
if (body == null)
{
return declaration.WithAccessorList(null);
}
throw new InvalidOperationException();
}
protected override PropertyDeclarationSyntax WithGenerateBody(SemanticModel semanticModel, PropertyDeclarationSyntax declaration)
=> WithAccessorList(semanticModel, declaration);
protected override bool CreateReturnStatementForExpression(SemanticModel semanticModel, PropertyDeclarationSyntax declaration) => true;
protected override bool TryConvertToExpressionBody(
PropertyDeclarationSyntax declaration, ParseOptions options,
ExpressionBodyPreference conversionPreference,
out ArrowExpressionClauseSyntax arrowExpression,
out SyntaxToken semicolonToken)
{
return TryConvertToExpressionBodyForBaseProperty(
declaration, options, conversionPreference,
out arrowExpression, out semicolonToken);
}
protected override Location GetDiagnosticLocation(PropertyDeclarationSyntax declaration)
{
var body = GetBody(declaration);
if (body != null)
{
return base.GetDiagnosticLocation(declaration);
}
var getAccessor = GetSingleGetAccessor(declaration.AccessorList);
return getAccessor.ExpressionBody.GetLocation();
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/VisualBasic/Test/IOperation/AssemblyAttributes.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 Xunit
| ' Licensed to the .NET Foundation under one or more 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 Xunit
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/Core/Portable/Workspace/Host/EventListener/IEventListenerStoppable.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// provide a way for <see cref="IEventListener"/> to mark it as stoppable
///
/// for example, if the service <see cref="IEventListener"/> is used for is a disposable
/// service, the service can call Stop when the service go away
/// </summary>
internal interface IEventListenerStoppable
{
void StopListening(Workspace workspace);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Host
{
/// <summary>
/// provide a way for <see cref="IEventListener"/> to mark it as stoppable
///
/// for example, if the service <see cref="IEventListener"/> is used for is a disposable
/// service, the service can call Stop when the service go away
/// </summary>
internal interface IEventListenerStoppable
{
void StopListening(Workspace workspace);
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/Core/Portable/Shared/Extensions/ILanguageServiceProviderExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class ILanguageServiceProviderExtensions
{
public static IEnumerable<Lazy<T, TMetadata>> SelectMatchingExtensions<T, TMetadata>(
this HostLanguageServices serviceProvider,
IEnumerable<Lazy<T, TMetadata>>? items)
where TMetadata : ILanguageMetadata
{
if (items == null)
{
return SpecializedCollections.EmptyEnumerable<Lazy<T, TMetadata>>();
}
return items.Where(lazy => lazy.Metadata.Language == serviceProvider.Language);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class ILanguageServiceProviderExtensions
{
public static IEnumerable<Lazy<T, TMetadata>> SelectMatchingExtensions<T, TMetadata>(
this HostLanguageServices serviceProvider,
IEnumerable<Lazy<T, TMetadata>>? items)
where TMetadata : ILanguageMetadata
{
if (items == null)
{
return SpecializedCollections.EmptyEnumerable<Lazy<T, TMetadata>>();
}
return items.Where(lazy => lazy.Metadata.Language == serviceProvider.Language);
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/PE/LoadCustomModifiers.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports CompilationCreationTestHelpers
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Microsoft.CodeAnalysis.CSharp
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE
Public Class LoadCustomModifiers : Inherits BasicTestBase
<Fact>
Public Sub Test1()
Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences(
{
TestResources.SymbolsTests.CustomModifiers.Modifiers,
TestMetadata.ResourcesNet40.mscorlib
})
Dim modifiersModule = assemblies(0).Modules(0)
Dim modifiers = modifiersModule.GlobalNamespace.GetTypeMembers("Modifiers").Single()
Dim f0 = modifiers.GetMembers("F0").OfType(Of FieldSymbol)().Single()
Assert.Equal(1, f0.CustomModifiers.Length)
Dim f0Mod = f0.CustomModifiers(0)
Assert.True(f0Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", f0Mod.Modifier.ToTestDisplayString())
Dim m1 As MethodSymbol = modifiers.GetMembers("F1").OfType(Of MethodSymbol)().Single()
Dim p1 As ParameterSymbol = m1.Parameters(0)
Dim p2 As ParameterSymbol = modifiers.GetMembers("F2").OfType(Of MethodSymbol)().Single().Parameters(0)
Dim p4 As ParameterSymbol = modifiers.GetMembers("F4").OfType(Of MethodSymbol)().Single().Parameters(0)
Dim m5 As MethodSymbol = modifiers.GetMembers("F5").OfType(Of MethodSymbol)().Single()
Dim p5 As ParameterSymbol = m5.Parameters(0)
Dim p6 As ParameterSymbol = modifiers.GetMembers("F6").OfType(Of MethodSymbol)().Single().Parameters(0)
Dim m7 As MethodSymbol = modifiers.GetMembers("F7").OfType(Of MethodSymbol)().Single()
Assert.Equal(0, m1.ReturnTypeCustomModifiers.Length)
Assert.Equal(1, p1.CustomModifiers.Length)
Dim p1Mod = p1.CustomModifiers(0)
Assert.True(p1Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", p1Mod.Modifier.ToTestDisplayString())
Assert.Equal(2, p2.CustomModifiers.Length)
For Each p2Mod In p2.CustomModifiers
Assert.True(p2Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", p2Mod.Modifier.ToTestDisplayString())
Next
Assert.Equal("p As System.Int32 modopt(System.Int32) modopt(System.Runtime.CompilerServices.IsConst) modopt(System.Runtime.CompilerServices.IsConst)", modifiers.GetMembers("F3").OfType(Of MethodSymbol)().Single().Parameters(0).ToTestDisplayString())
Assert.Equal("p As System.Int32 modreq(System.Runtime.CompilerServices.IsConst) modopt(System.Runtime.CompilerServices.IsConst)", p4.ToTestDisplayString())
Assert.True(p4.HasUnsupportedMetadata)
Assert.True(p4.ContainingSymbol.HasUnsupportedMetadata)
Assert.True(m5.IsSub)
Assert.Equal(1, m5.ReturnTypeCustomModifiers.Length)
Dim m5Mod = m5.ReturnTypeCustomModifiers(0)
Assert.True(m5Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", m5Mod.Modifier.ToTestDisplayString())
Assert.Equal(0, p5.CustomModifiers.Length)
Dim p5Type As ArrayTypeSymbol = DirectCast(p5.Type, ArrayTypeSymbol)
Assert.Equal("System.Int32", p5Type.ElementType.ToTestDisplayString())
Assert.Equal(1, p5Type.CustomModifiers.Length)
Dim p5TypeMod = p5Type.CustomModifiers(0)
Assert.True(p5TypeMod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", p5TypeMod.Modifier.ToTestDisplayString())
Assert.Equal(0, p6.CustomModifiers.Length)
Dim p6Type As TypeSymbol = p6.Type
Assert.IsType(Of PointerTypeSymbol)(p6Type)
Assert.Equal(ERRID.ERR_UnsupportedType1, p6Type.GetUseSiteErrorInfo().Code)
Assert.False(m7.IsSub)
Assert.Equal(1, m7.ReturnTypeCustomModifiers.Length)
Dim m7Mod = m7.ReturnTypeCustomModifiers(0)
Assert.True(m7Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", m7Mod.Modifier.ToTestDisplayString())
End Sub
<Fact>
Public Sub UnmanagedConstraint_RejectedSymbol_OnClass()
Dim reference = CreateCSharpCompilation("
public class TestRef<T> where T : unmanaged
{
}", parseOptions:=New CSharpParseOptions(CSharp.LanguageVersion.Latest)).EmitToImageReference()
Dim source =
<compilation>
<file>
Class Test
Shared Sub Main()
Dim x = New TestRef(Of String)()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, references:={reference})
AssertTheseDiagnostics(compilation, <expected>
BC30649: '' is an unsupported type.
Dim x = New TestRef(Of String)()
~~~~~~
BC32044: Type argument 'String' does not inherit from or implement the constraint type '?'.
Dim x = New TestRef(Of String)()
~~~~~~
BC32105: Type argument 'String' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim x = New TestRef(Of String)()
~~~~~~
</expected>)
Dim badTypeParameter = compilation.GetTypeByMetadataName("TestRef`1").TypeParameters.Single()
Assert.True(badTypeParameter.HasValueTypeConstraint)
End Sub
<Fact>
Public Sub UnmanagedConstraint_RejectedSymbol_OnMethod()
Dim reference = CreateCSharpCompilation("
public class TestRef
{
public void M<T>() where T : unmanaged
{
}
}", parseOptions:=New CSharpParseOptions(CSharp.LanguageVersion.Latest)).EmitToImageReference()
Dim source =
<compilation>
<file>
Class Test
Shared Sub Main()
Dim x = New TestRef()
x.M(Of String)()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, references:={reference})
AssertTheseDiagnostics(compilation, <expected>
BC30649: '' is an unsupported type.
x.M(Of String)()
~~~~~~~~~~~~~~~~
</expected>)
Dim badTypeParameter = compilation.GetTypeByMetadataName("TestRef").GetMethod("M").TypeParameters.Single()
Assert.True(badTypeParameter.HasValueTypeConstraint)
End Sub
<Fact>
Public Sub UnmanagedConstraint_RejectedSymbol_OnDelegate()
Dim reference = CreateCSharpCompilation("
public delegate T D<T>() where T : unmanaged;
", parseOptions:=New CSharpParseOptions(CSharp.LanguageVersion.Latest)).EmitToImageReference()
Dim source =
<compilation>
<file>
Class Test
Shared Sub Main(del As D(Of String))
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, references:={reference})
AssertTheseDiagnostics(compilation, <expected>
BC30649: '' is an unsupported type.
Shared Sub Main(del As D(Of String))
~~~
BC32044: Type argument 'String' does not inherit from or implement the constraint type '?'.
Shared Sub Main(del As D(Of String))
~~~
BC32105: Type argument 'String' does not satisfy the 'Structure' constraint for type parameter 'T'.
Shared Sub Main(del As D(Of String))
~~~
</expected>)
Dim badTypeParameter = compilation.GetTypeByMetadataName("D`1").TypeParameters.Single()
Assert.True(badTypeParameter.HasValueTypeConstraint)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports CompilationCreationTestHelpers
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Microsoft.CodeAnalysis.CSharp
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata.PE
Public Class LoadCustomModifiers : Inherits BasicTestBase
<Fact>
Public Sub Test1()
Dim assemblies = MetadataTestHelpers.GetSymbolsForReferences(
{
TestResources.SymbolsTests.CustomModifiers.Modifiers,
TestMetadata.ResourcesNet40.mscorlib
})
Dim modifiersModule = assemblies(0).Modules(0)
Dim modifiers = modifiersModule.GlobalNamespace.GetTypeMembers("Modifiers").Single()
Dim f0 = modifiers.GetMembers("F0").OfType(Of FieldSymbol)().Single()
Assert.Equal(1, f0.CustomModifiers.Length)
Dim f0Mod = f0.CustomModifiers(0)
Assert.True(f0Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", f0Mod.Modifier.ToTestDisplayString())
Dim m1 As MethodSymbol = modifiers.GetMembers("F1").OfType(Of MethodSymbol)().Single()
Dim p1 As ParameterSymbol = m1.Parameters(0)
Dim p2 As ParameterSymbol = modifiers.GetMembers("F2").OfType(Of MethodSymbol)().Single().Parameters(0)
Dim p4 As ParameterSymbol = modifiers.GetMembers("F4").OfType(Of MethodSymbol)().Single().Parameters(0)
Dim m5 As MethodSymbol = modifiers.GetMembers("F5").OfType(Of MethodSymbol)().Single()
Dim p5 As ParameterSymbol = m5.Parameters(0)
Dim p6 As ParameterSymbol = modifiers.GetMembers("F6").OfType(Of MethodSymbol)().Single().Parameters(0)
Dim m7 As MethodSymbol = modifiers.GetMembers("F7").OfType(Of MethodSymbol)().Single()
Assert.Equal(0, m1.ReturnTypeCustomModifiers.Length)
Assert.Equal(1, p1.CustomModifiers.Length)
Dim p1Mod = p1.CustomModifiers(0)
Assert.True(p1Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", p1Mod.Modifier.ToTestDisplayString())
Assert.Equal(2, p2.CustomModifiers.Length)
For Each p2Mod In p2.CustomModifiers
Assert.True(p2Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", p2Mod.Modifier.ToTestDisplayString())
Next
Assert.Equal("p As System.Int32 modopt(System.Int32) modopt(System.Runtime.CompilerServices.IsConst) modopt(System.Runtime.CompilerServices.IsConst)", modifiers.GetMembers("F3").OfType(Of MethodSymbol)().Single().Parameters(0).ToTestDisplayString())
Assert.Equal("p As System.Int32 modreq(System.Runtime.CompilerServices.IsConst) modopt(System.Runtime.CompilerServices.IsConst)", p4.ToTestDisplayString())
Assert.True(p4.HasUnsupportedMetadata)
Assert.True(p4.ContainingSymbol.HasUnsupportedMetadata)
Assert.True(m5.IsSub)
Assert.Equal(1, m5.ReturnTypeCustomModifiers.Length)
Dim m5Mod = m5.ReturnTypeCustomModifiers(0)
Assert.True(m5Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", m5Mod.Modifier.ToTestDisplayString())
Assert.Equal(0, p5.CustomModifiers.Length)
Dim p5Type As ArrayTypeSymbol = DirectCast(p5.Type, ArrayTypeSymbol)
Assert.Equal("System.Int32", p5Type.ElementType.ToTestDisplayString())
Assert.Equal(1, p5Type.CustomModifiers.Length)
Dim p5TypeMod = p5Type.CustomModifiers(0)
Assert.True(p5TypeMod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", p5TypeMod.Modifier.ToTestDisplayString())
Assert.Equal(0, p6.CustomModifiers.Length)
Dim p6Type As TypeSymbol = p6.Type
Assert.IsType(Of PointerTypeSymbol)(p6Type)
Assert.Equal(ERRID.ERR_UnsupportedType1, p6Type.GetUseSiteErrorInfo().Code)
Assert.False(m7.IsSub)
Assert.Equal(1, m7.ReturnTypeCustomModifiers.Length)
Dim m7Mod = m7.ReturnTypeCustomModifiers(0)
Assert.True(m7Mod.IsOptional)
Assert.Equal("System.Runtime.CompilerServices.IsConst", m7Mod.Modifier.ToTestDisplayString())
End Sub
<Fact>
Public Sub UnmanagedConstraint_RejectedSymbol_OnClass()
Dim reference = CreateCSharpCompilation("
public class TestRef<T> where T : unmanaged
{
}", parseOptions:=New CSharpParseOptions(CSharp.LanguageVersion.Latest)).EmitToImageReference()
Dim source =
<compilation>
<file>
Class Test
Shared Sub Main()
Dim x = New TestRef(Of String)()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, references:={reference})
AssertTheseDiagnostics(compilation, <expected>
BC30649: '' is an unsupported type.
Dim x = New TestRef(Of String)()
~~~~~~
BC32044: Type argument 'String' does not inherit from or implement the constraint type '?'.
Dim x = New TestRef(Of String)()
~~~~~~
BC32105: Type argument 'String' does not satisfy the 'Structure' constraint for type parameter 'T'.
Dim x = New TestRef(Of String)()
~~~~~~
</expected>)
Dim badTypeParameter = compilation.GetTypeByMetadataName("TestRef`1").TypeParameters.Single()
Assert.True(badTypeParameter.HasValueTypeConstraint)
End Sub
<Fact>
Public Sub UnmanagedConstraint_RejectedSymbol_OnMethod()
Dim reference = CreateCSharpCompilation("
public class TestRef
{
public void M<T>() where T : unmanaged
{
}
}", parseOptions:=New CSharpParseOptions(CSharp.LanguageVersion.Latest)).EmitToImageReference()
Dim source =
<compilation>
<file>
Class Test
Shared Sub Main()
Dim x = New TestRef()
x.M(Of String)()
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, references:={reference})
AssertTheseDiagnostics(compilation, <expected>
BC30649: '' is an unsupported type.
x.M(Of String)()
~~~~~~~~~~~~~~~~
</expected>)
Dim badTypeParameter = compilation.GetTypeByMetadataName("TestRef").GetMethod("M").TypeParameters.Single()
Assert.True(badTypeParameter.HasValueTypeConstraint)
End Sub
<Fact>
Public Sub UnmanagedConstraint_RejectedSymbol_OnDelegate()
Dim reference = CreateCSharpCompilation("
public delegate T D<T>() where T : unmanaged;
", parseOptions:=New CSharpParseOptions(CSharp.LanguageVersion.Latest)).EmitToImageReference()
Dim source =
<compilation>
<file>
Class Test
Shared Sub Main(del As D(Of String))
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib45AndVBRuntime(source, references:={reference})
AssertTheseDiagnostics(compilation, <expected>
BC30649: '' is an unsupported type.
Shared Sub Main(del As D(Of String))
~~~
BC32044: Type argument 'String' does not inherit from or implement the constraint type '?'.
Shared Sub Main(del As D(Of String))
~~~
BC32105: Type argument 'String' does not satisfy the 'Structure' constraint for type parameter 'T'.
Shared Sub Main(del As D(Of String))
~~~
</expected>)
Dim badTypeParameter = compilation.GetTypeByMetadataName("D`1").TypeParameters.Single()
Assert.True(badTypeParameter.HasValueTypeConstraint)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Test/Emit/CodeGen/PropertyTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class PropertyTests : EmitMetadataTestBase
{
[Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[CompilerTrait(CompilerFeature.ExpressionBody)]
public void ExpressionBodedProperty()
{
var source = @"
class C
{
public int x;
public int X
{
set => x = value;
get => x;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(compilation);
verifier.VerifyIL("C.X.get", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ret
}
");
verifier.VerifyIL("C.X.set", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int C.x""
IL_0007: ret
}
");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class PropertyTests : EmitMetadataTestBase
{
[Fact, WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")]
[CompilerTrait(CompilerFeature.ExpressionBody)]
public void ExpressionBodedProperty()
{
var source = @"
class C
{
public int x;
public int X
{
set => x = value;
get => x;
}
}";
var compilation = CreateCompilation(source, options: TestOptions.DebugDll);
var verifier = CompileAndVerify(compilation);
verifier.VerifyIL("C.X.get", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ret
}
");
verifier.VerifyIL("C.X.set", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld ""int C.x""
IL_0007: ret
}
");
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
/// <summary>
/// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test.
/// </summary>
public class EditAndContinueTests : EditAndContinueTestBase
{
private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers)
{
var currentGenerationReader = readers.Last();
foreach (var typeRefHandle in currentGenerationReader.TypeReferences)
{
var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle);
yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}";
}
}
[Fact]
public void DeltaHeapsStartWithEmptyItem()
{
var source0 =
@"class C
{
static string F() { return null; }
}";
var source1 =
@"class C
{
static string F() { return ""a""; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var s = MetadataTokens.StringHandle(0);
Assert.Equal("", reader1.GetString(s));
var b = MetadataTokens.BlobHandle(0);
Assert.Equal(0, reader1.GetBlobBytes(b).Length);
var us = MetadataTokens.UserStringHandle(0);
Assert.Equal("", reader1.GetUserString(us));
}
[Fact]
public void Delta_AssemblyDefTable()
{
var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }";
var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
// AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed:
Assert.True(md0.MetadataReader.IsAssembly);
Assert.False(diff1.GetMetadata().Reader.IsAssembly);
}
[Fact]
public void SemanticErrors_MethodBody()
{
var source0 = MarkedSource(@"
class C
{
static void E()
{
int x = 1;
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void E()
{
int x = Unknown(2);
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(2);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Semantic errors are reported only for the bodies of members being emitted.
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (6,17): error CS0103: The name 'Unknown' does not exist in the current context
// int x = Unknown(2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17));
var diffGood = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffGood.EmitResult.Diagnostics.Verify();
diffGood.VerifyIL(@"C.G", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ret
}
");
}
[Fact]
public void SemanticErrors_Declaration()
{
var source0 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(1);
}
}
");
var source1 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(2);
}
}
class Bad : Bad
{
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// All declaration errors are reported regardless of what member do we emit.
diff.EmitResult.Diagnostics.Verify(
// (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad'
// class Bad : Bad
Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7));
}
[Fact]
public void ModifyMethod()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_RenameParameter()
{
var source0 =
@"class C
{
static string F(int a) { return a.ToString(); }
}";
var source1 =
@"class C
{
static string F(int x) { return x.ToString(); }
}";
var source2 =
@"class C
{
static string F(int b) { return b.ToString(); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb));
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor");
CheckNames(reader0, reader0.GetParameterDefNames(), "a");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetParameterDefNames(), "x");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(1, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.StandAloneSig));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), "ToString");
CheckNames(readers, reader2.GetParameterDefNames(), "b");
CheckEncLogDefinitions(reader2,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(1, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(3, TableIndex.StandAloneSig));
}
[CompilerTrait(CompilerFeature.Tuples)]
[Fact]
public void ModifyMethod_WithTuples()
{
var source0 =
@"class C
{
static void Main() { }
static (int, int) F() { return (1, 2); }
}";
var source1 =
@"class C
{
static void Main() { }
static (int, int) F() { return (2, 3); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_WithAttributes1()
{
using var _ = new EditAndContinueTest(options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20)
.AddGeneration(
source: @"
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}",
validator: g =>
{
g.VerifyTypeDefNames("<Module>", "C");
g.VerifyMethodDefNames("Main", "F", ".ctor");
g.VerifyMemberRefNames(/*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
g.VerifyTableSize(TableIndex.CustomAttribute, 4);
})
.AddGeneration(
source: @"
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}",
edits: new[] { Edit(SemanticEditKind.Update, c => c.GetMember("C.F")) },
validator: g =>
{
g.VerifyTypeDefNames();
g.VerifyMethodDefNames("F");
g.VerifyMemberRefNames( /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
g.VerifyTableSize(TableIndex.CustomAttribute, 1);
g.VerifyEncLog(new[]
{
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 4, so updating existing CustomAttribute
});
g.VerifyEncMap(new[]
{
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef)
});
})
// Add attribute to method, and to class
.AddGeneration(
source: @"
[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}",
edits: new[] {
Edit(SemanticEditKind.Update, c => c.GetMember("C")),
Edit(SemanticEditKind.Update, c => c.GetMember("C.F"))
},
validator: g =>
{
g.VerifyTypeDefNames("C");
g.VerifyMethodDefNames("F");
g.VerifyMemberRefNames( /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
g.VerifyTableSize(TableIndex.CustomAttribute, 3);
g.VerifyEncLog(new[] {
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 6 adding a new CustomAttribute
});
g.VerifyEncMap(new[] {
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(2, TableIndex.TypeDef),
Handle(2, TableIndex.MethodDef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(10, TableIndex.MemberRef),
Handle(11, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef)
});
})
// Add attribute before existing attributes
.AddGeneration(
source: @"
[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}",
edits: new[] {
Edit(SemanticEditKind.Update, c => c.GetMember("C.F"))
},
validator: g =>
{
g.VerifyTypeDefNames();
g.VerifyMethodDefNames("F");
g.VerifyMemberRefNames( /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
g.VerifyTableSize(TableIndex.CustomAttribute, 3);
g.VerifyEncLog(new[] {
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted
});
g.VerifyEncMap(new[] {
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(19, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(12, TableIndex.MemberRef),
Handle(13, TableIndex.MemberRef),
Handle(14, TableIndex.MemberRef),
Handle(15, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef)
});
})
.Verify();
}
[Fact]
public void ModifyMethod_WithAttributes2()
{
var source0 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A"")]
static string A() { return null; }
}
";
var source1 =
@"
[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")]
static string A() { return null; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0_1 = compilation0.GetMember<MethodSymbol>("C.F");
var method0_2 = compilation0.GetMember<MethodSymbol>("D.A");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1_1 = compilation1.GetMember<MethodSymbol>("C.F");
var method1_2 = compilation1.GetMember<MethodSymbol>("D.A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1),
SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "A");
CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes1()
{
var source0 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var source2 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader2,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes2()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var source2 = source0; // Remove the attribute we just added
var source3 = source1; // Add the attribute back again
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation1.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames());
CheckAttributes(reader2,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
var method3 = compilation3.GetMember<MethodSymbol>("C.F");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader3,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row
CheckEncMap(reader3,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef));
}
[WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")]
[Fact]
public void PartialMethod()
{
var source =
@"partial class C
{
static partial void M1();
static partial void M2();
static partial void M3();
static partial void M1() { }
static partial void M2() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor");
var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
var methods = diff1.TestData.GetMethodsByName();
Assert.Equal(1, methods.Count);
Assert.True(methods.ContainsKey("C.M2()"));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "M2");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Method_WithAttributes_Add()
{
var source0 =
@"class C
{
static void Main() { }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_ParameterAttributes()
{
var source0 =
@"class C
{
static void Main() { }
static string F(string input, int a) { return input; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; }
static void G(string input) { }
}";
var source2 =
@"class C
{
static void Main() { }
static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; }
static void G([System.ComponentModel.Description(""input"")]string input) { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var methodF0 = compilation0.GetMember<MethodSymbol>("C.F");
var methodF1 = compilation1.GetMember<MethodSymbol>("C.F");
var methodG1 = compilation1.GetMember<MethodSymbol>("C.G");
var methodG2 = compilation2.GetMember<MethodSymbol>("C.G");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
CheckNames(reader0, reader0.GetParameterDefNames(), "input", "a");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, methodF0, methodF1),
SemanticEdit.Create(SemanticEditKind.Insert, null, methodG1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "G");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor");
CheckNames(readers, reader1.GetParameterDefNames(), "input", "a", "input");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.Param), Handle(5, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), // New method, G
Row(1, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param
Row(2, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), // New param on method, G
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Support for the above
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param),
Handle(5, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, methodG1, methodG2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "G");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor");
CheckNames(readers, reader2.GetParameterDefNames(), "input");
CheckAttributes(reader2,
new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef)));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param, from the first delta
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(4, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(6, TableIndex.MemberRef),
Handle(5, TableIndex.CustomAttribute),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyDelegateInvokeMethod_AddAttributes()
{
var source0 = @"
class A : System.Attribute { }
delegate void D(int x);
";
var source1 = @"
class A : System.Attribute { }
delegate void D([A]int x);
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var invoke0 = compilation0.GetMember<MethodSymbol>("D.Invoke");
var beginInvoke0 = compilation0.GetMember<MethodSymbol>("D.BeginInvoke");
var invoke1 = compilation1.GetMember<MethodSymbol>("D.Invoke");
var beginInvoke1 = compilation1.GetMember<MethodSymbol>("D.BeginInvoke");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, invoke0, invoke1),
SemanticEdit.Create(SemanticEditKind.Update, beginInvoke0, beginInvoke1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetMethodDefNames(), "Invoke", "BeginInvoke");
CheckNames(readers, reader1.GetParameterDefNames(), "x", "x", "callback", "object");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(4, TableIndex.Param), Handle(1, TableIndex.MethodDef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Updating existing parameter defs
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Adding new custom attribute rows
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param),
Handle(6, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(2, TableIndex.AssemblyRef));
}
/// <summary>
/// Add a method that requires entries in the ParameterDefs table.
/// Specifically, normal parameters or return types with attributes.
/// Add the method in the first edit, then modify the method in the second.
/// </summary>
[Fact]
public void Method_WithParameterAttributes_AddThenUpdate()
{
var source0 =
@"class A : System.Attribute { }
class C
{
}";
var source1 =
@"class A : System.Attribute { }
class C
{
[return:A]static object F(int arg = 1) => arg;
}";
var source2 =
@"class A : System.Attribute { }
class C
{
[return:A]static object F(int arg = 1) => null;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetParameterDefNames(), "", "arg");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(1, TableIndex.Constant, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(1, TableIndex.Constant),
Handle(4, TableIndex.CustomAttribute));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetParameterDefNames(), "", "arg");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C");
CheckNames(readers, diff2.EmitResult.UpdatedMethods, "F");
CheckEncLogDefinitions(reader2,
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), // C.F2
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.Constant, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(2, TableIndex.Constant),
Handle(4, TableIndex.CustomAttribute));
}
[Fact]
public void Method_WithEmbeddedAttributes_AndThenUpdate()
{
var source0 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
class C
{
static void Main() { }
}
}
";
var source1 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main()
{
Id(in G());
}
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 1 }[0];
}
}";
var source2 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
}
}";
var source3 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
readonly ref readonly string?[]? F() => throw null;
}
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main");
var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id");
var g1 = compilation1.GetMember<MethodSymbol>("N.C.G");
var g2 = compilation2.GetMember<MethodSymbol>("N.C.G");
var h2 = compilation2.GetMember<MethodSymbol>("N.C.H");
var f3 = compilation3.GetMember<MethodSymbol>("N.C.F");
// Verify full metadata contains expected rows.
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, id1),
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute}");
diff1.VerifyIL("N.C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: nop
IL_0001: call ""ref readonly int N.C.G()""
IL_0006: call ""ref readonly int N.C.Id(in int)""
IL_000b: pop
IL_000c: ret
}
");
diff1.VerifyIL("N.C.Id", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
");
diff1.VerifyIL("N.C.G", @"
{
// Code size 17 (0x11)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: newarr ""int""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: stelem.i4
IL_000a: ldc.i4.0
IL_000b: ldelema ""int""
IL_0010: ret
}
");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader0 = md0.MetadataReader;
var reader1 = md1.Reader;
var readers = new List<MetadataReader>() { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute");
CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g1, g2),
SemanticEdit.Create(SemanticEditKind.Insert, null, h2)));
// synthesized member for nullable annotations added:
diff2.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
// note: NullableAttribute has 2 ctors, NullableContextAttribute has one
CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute");
CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H");
// two new TypeDefs emitted for the attributes:
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute
Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(6, TableIndex.TypeDef),
Handle(7, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(2, TableIndex.Field),
Handle(7, TableIndex.MethodDef),
Handle(8, TableIndex.MethodDef),
Handle(9, TableIndex.MethodDef),
Handle(10, TableIndex.MethodDef),
Handle(11, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(6, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(12, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(3, TableIndex.AssemblyRef));
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3)));
// no change in synthesized members:
diff3.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
// no new type defs:
CheckNames(readers, reader3.GetTypeDefFullNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void Field_Add()
{
var source0 =
@"class C
{
string F = ""F"";
}";
var source1 =
@"class C
{
string F = ""F"";
string G = ""G"";
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetFieldDefNames(), "F");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var method1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "G");
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Property_Accessor_Update()
{
var source0 =
@"class C
{
object P { get { return 1; } }
}";
var source1 =
@"class C
{
object P { get { return 2; } }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P");
var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetPropertyDefNames(), "P");
CheckNames(readers, reader1.GetMethodDefNames(), "get_P");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Property_Add()
{
var source0 = @"
class C
{
}
";
var source1 = @"
class C
{
object R { get { return null; } }
}
";
var source2 = @"
class C
{
object R { get { return null; } }
object Q { get; set; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var r1 = compilation1.GetMember<PropertySymbol>("C.R");
var q2 = compilation2.GetMember<PropertySymbol>("C.Q");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetPropertyDefNames(), "R");
CheckNames(readers, reader1.GetMethodDefNames(), "get_R");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.MethodDef),
Handle(1, TableIndex.StandAloneSig),
Handle(1, TableIndex.PropertyMap),
Handle(1, TableIndex.Property),
Handle(1, TableIndex.MethodSemantics));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, q2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField");
CheckNames(readers, reader2.GetPropertyDefNames(), "Q");
CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(1, TableIndex.Field),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(2, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(3, TableIndex.MethodSemantics));
}
[Fact]
public void Event_Add()
{
var source0 = @"
class C
{
}";
var source1 = @"
class C
{
event System.Action E;
}";
var source2 = @"
class C
{
event System.Action E;
event System.Action G;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var e1 = compilation1.GetMember<EventSymbol>("C.E");
var g2 = compilation2.GetMember<EventSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, e1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "E");
CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(1, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(1, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(1, TableIndex.EventMap),
Handle(1, TableIndex.Event),
Handle(1, TableIndex.MethodSemantics),
Handle(2, TableIndex.MethodSemantics));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "G");
CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.Field),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(3, TableIndex.MethodSemantics),
Handle(4, TableIndex.MethodSemantics));
}
[WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")]
[Fact]
public void EventFields()
{
var source0 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 1;
}
}
");
var source1 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 10;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 21 (0x15)
.maxstack 3
.locals init (int V_0)
IL_0000: nop
IL_0001: ldsfld ""System.EventHandler C.handler""
IL_0006: ldnull
IL_0007: ldnull
IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)""
IL_000d: nop
IL_000e: ldc.i4.s 10
IL_0010: stloc.0
IL_0011: br.s IL_0013
IL_0013: ldloc.0
IL_0014: ret
}
");
}
[Fact]
public void UpdateType_AddAttributes()
{
var source0 = @"
class C
{
}";
var source1 = @"
[System.ComponentModel.Description(""C"")]
class C
{
}";
var source2 = @"
[System.ComponentModel.Description(""C"")]
[System.ObsoleteAttribute]
class C
{
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C");
Assert.Equal(2, reader2.CustomAttributes.Count);
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute));
}
[Fact]
public void ReplaceType()
{
var source0 = @"
class C
{
void F(int x) {}
}
";
var source1 = @"
class C
{
void F(int x, int y) { }
}";
var source2 = @"
class C
{
void F(int x, int y) { System.Console.WriteLine(1); }
}";
var source3 = @"
[System.Obsolete]
class C
{
void F(int x, int y) { System.Console.WriteLine(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var c3 = compilation3.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
var f3 = c3.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C#1");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param));
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C#2");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2");
CheckEncLogDefinitions(reader2,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param));
// This update is an EnC update - even reloadable types are update in-place
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, c2, c3),
SemanticEdit.Create(SemanticEditKind.Update, f2, f3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames(), "C#2");
CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2");
CheckEncLogDefinitions(reader3,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader3,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute));
}
[Fact]
public void EventFields_Attributes()
{
var source0 = MarkedSource(@"
using System;
class C
{
static event EventHandler E;
}
");
var source1 = MarkedSource(@"
using System;
class C
{
[System.Obsolete]
static event EventHandler E;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var event0 = compilation0.GetMember<EventSymbol>("C.E");
var event1 = compilation1.GetMember<EventSymbol>("C.E");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "add_E", "remove_E", ".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, event0, event1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames());
CheckNames(readers, reader1.GetEventDefNames(), "E");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(10, TableIndex.MemberRef)));
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.Event, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(8, TableIndex.CustomAttribute),
Handle(1, TableIndex.Event),
Handle(3, TableIndex.MethodSemantics),
Handle(4, TableIndex.MethodSemantics));
}
[Fact]
public void ReplaceType_AsyncLambda()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
void F(int x) { Task.Run(async() => {}); }
}
";
var source1 = @"
using System.Threading.Tasks;
class C
{
void F(bool y) { Task.Run(async() => {}); }
}
";
var source2 = @"
using System.Threading.Tasks;
class C
{
void F(uint z) { Task.Run(async() => {}); }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c", "<<F>b__0_0>d");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
// A new nested type <>c is generated in C#1
CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "<>c", "<<F>b__0#1_0#1>d");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "<>c", "<<F>b__0#1_0#1>d");
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
// A new nested type <>c is generated in C#2
CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "<>c", "<<F>b__0#2_0#2>d");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "<>c", "<<F>b__0#2_0#2>d");
}
[Fact]
public void ReplaceType_AsyncLambda_InNestedType()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
class D
{
void F(int x) { Task.Run(async() => {}); }
}
}
";
var source1 = @"
using System.Threading.Tasks;
class C
{
class D
{
void F(bool y) { Task.Run(async() => {}); }
}
}
";
var source2 = @"
using System.Threading.Tasks;
class C
{
class D
{
void F(uint z) { Task.Run(async() => {}); }
}
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D", "<>c", "<<F>b__0_0>d");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
// A new nested type <>c is generated in C#1
CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "D", "<>c", "<<F>b__0#1_0#1>d");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "D", "<>c", "<<F>b__0#1_0#1>d");
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
// A new nested type <>c is generated in C#2
CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "D", "<>c", "<<F>b__0#2_0#2>d");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "D", "<>c", "<<F>b__0#2_0#2>d");
}
[Fact]
public void AddNestedTypeAndMembers()
{
var source0 =
@"class A
{
class B { }
static object F()
{
return new B();
}
}";
var source1 =
@"class A
{
class B { }
class C
{
class D { }
static object F;
internal static object G()
{
return F;
}
}
static object F()
{
return C.G();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C");
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C", "D");
CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor");
CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D");
Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(3, TableIndex.NestedClass));
}
/// <summary>
/// Nested types should be emitted in the
/// same order as full emit.
/// </summary>
[Fact]
public void AddNestedTypesOrder()
{
var source0 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
}";
var source1 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
class B3
{
class C3 { }
}
class B4
{
class C4 { }
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2");
Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4");
Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass));
}
[Fact]
public void AddNestedGenericType()
{
var source0 =
@"class A
{
class B<T>
{
}
static object F()
{
return null;
}
}";
var source1 =
@"class A
{
class B<T>
{
internal class C<U>
{
internal object F<V>() where V : T, new()
{
return new C<V>();
}
}
}
static object F()
{
return new B<A>.C<B<object>>().F<A>();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1");
CheckNames(readers, reader1.GetTypeDefNames(), "C`1");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.TypeSpec),
Handle(2, TableIndex.TypeSpec),
Handle(3, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(2, TableIndex.GenericParam),
Handle(3, TableIndex.GenericParam),
Handle(4, TableIndex.GenericParam),
Handle(1, TableIndex.MethodSpec),
Handle(1, TableIndex.GenericParamConstraint));
}
[Fact]
[WorkItem(54939, "https://github.com/dotnet/roslyn/issues/54939")]
public void AddNamespace()
{
var source0 =
@"
class C
{
static void Main() { }
}";
var source1 =
@"
namespace N1.N2
{
class D { public static void F() { } }
}
class C
{
static void Main() => N1.N2.D.F();
}";
var source2 =
@"
namespace N1.N2
{
class D { public static void F() { } }
namespace M1.M2
{
class E { public static void G() { } }
}
}
class C
{
static void Main() => N1.N2.M1.M2.E.G();
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var main0 = compilation0.GetMember<MethodSymbol>("C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("C.Main");
var main2 = compilation2.GetMember<MethodSymbol>("C.Main");
var d1 = compilation1.GetMember<NamedTypeSymbol>("N1.N2.D");
var e2 = compilation2.GetMember<NamedTypeSymbol>("N1.N2.M1.M2.E");
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, d1)));
diff1.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N1.N2.D.F()""
IL_0005: nop
IL_0006: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main1, main2),
SemanticEdit.Create(SemanticEditKind.Insert, null, e2)));
diff2.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N1.N2.M1.M2.E.G()""
IL_0005: nop
IL_0006: ret
}");
}
[Fact]
public void ModifyExplicitImplementation()
{
var source =
@"interface I
{
void M();
}
class C : I
{
void I.M() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddThenModifyExplicitImplementation()
{
var source0 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
}";
var source1 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
void I.M() { }
}";
var source2 = source1;
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(2, TableIndex.MethodImpl),
Handle(2, TableIndex.AssemblyRef));
var generation1 = diff1.NextGeneration;
var diff2 = compilation2.EmitDifference(
generation1,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetMethodDefNames(), "I.M");
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(7, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(3, TableIndex.AssemblyRef));
}
[WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")]
[Fact]
public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation()
{
var source = @"
interface I
{
void M();
}
class C : I
{
public C()
{
}
void I.M() { }
}
";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddAndModifyInterfaceMembers()
{
var source0 = @"
using System;
interface I
{
}";
var source1 = @"
using System;
interface I
{
static int X = 10;
static event Action Y;
static void M() { }
void N() { }
static int P { get => 1; set { } }
int Q { get => 1; set { } }
static event Action E { add { } remove { } }
event Action F { add { } remove { } }
interface J { }
}";
var source2 = @"
using System;
interface I
{
static int X = 2;
static event Action Y;
static I() { X--; }
static void M() { X++; }
void N() { X++; }
static int P { get => 3; set { X++; } }
int Q { get => 3; set { X++; } }
static event Action E { add { X++; } remove { X++; } }
event Action F { add { X++; } remove { X++; } }
interface J { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var x1 = compilation1.GetMember<FieldSymbol>("I.X");
var y1 = compilation1.GetMember<EventSymbol>("I.Y");
var m1 = compilation1.GetMember<MethodSymbol>("I.M");
var n1 = compilation1.GetMember<MethodSymbol>("I.N");
var p1 = compilation1.GetMember<PropertySymbol>("I.P");
var q1 = compilation1.GetMember<PropertySymbol>("I.Q");
var e1 = compilation1.GetMember<EventSymbol>("I.E");
var f1 = compilation1.GetMember<EventSymbol>("I.F");
var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J");
var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P");
var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P");
var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q");
var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q");
var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E");
var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E");
var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F");
var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F");
var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var x2 = compilation2.GetMember<FieldSymbol>("I.X");
var m2 = compilation2.GetMember<MethodSymbol>("I.M");
var n2 = compilation2.GetMember<MethodSymbol>("I.N");
var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P");
var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P");
var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q");
var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q");
var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E");
var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E");
var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F");
var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F");
var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, x1),
SemanticEdit.Create(SemanticEditKind.Insert, null, y1),
SemanticEdit.Create(SemanticEditKind.Insert, null, m1),
SemanticEdit.Create(SemanticEditKind.Insert, null, n1),
SemanticEdit.Create(SemanticEditKind.Insert, null, p1),
SemanticEdit.Create(SemanticEditKind.Insert, null, q1),
SemanticEdit.Create(SemanticEditKind.Insert, null, e1),
SemanticEdit.Create(SemanticEditKind.Insert, null, f1),
SemanticEdit.Create(SemanticEditKind.Insert, null, j1),
SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J");
CheckNames(readers, reader1.GetTypeDefNames(), "J");
CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y");
CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, x1, x2),
SemanticEdit.Create(SemanticEditKind.Update, m1, m2),
SemanticEdit.Create(SemanticEditKind.Update, n1, n2),
SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2),
SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2),
SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2),
SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2),
SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2),
SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2),
SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2),
SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2),
SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "X");
CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(3, TableIndex.Event, EditAndContinueOperation.Default),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
diff2.VerifyIL(@"
{
// Code size 14 (0xe)
.maxstack 8
IL_0000: nop
IL_0001: ldsfld 0x04000001
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: stsfld 0x04000001
IL_000d: ret
}
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.3
IL_0001: ret
}
{
// Code size 20 (0x14)
.maxstack 8
IL_0000: ldc.i4.2
IL_0001: stsfld 0x04000001
IL_0006: nop
IL_0007: ldsfld 0x04000001
IL_000c: ldc.i4.1
IL_000d: sub
IL_000e: stsfld 0x04000001
IL_0013: ret
}
");
}
[Fact]
public void AddAttributeReferences()
{
var source0 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static object F1;
[A] static object P1 { get { return null; } }
[B] static event D E1;
}
delegate void D();
";
var source1 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static void M2<[A]T>() { }
[B] static object F1;
[A] static object F2;
[A] static object P1 { get { return null; } }
[B] static object P2 { get { return null; } }
[B] static event D E1;
[A] static event D E2;
}
delegate void D();
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(12, TableIndex.MethodDef),
Handle(13, TableIndex.MethodDef),
Handle(14, TableIndex.MethodDef),
Handle(15, TableIndex.MethodDef),
Handle(8, TableIndex.Param),
Handle(9, TableIndex.Param),
Handle(7, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(18, TableIndex.CustomAttribute),
Handle(19, TableIndex.CustomAttribute),
Handle(20, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(2, TableIndex.Property),
Handle(4, TableIndex.MethodSemantics),
Handle(5, TableIndex.MethodSemantics),
Handle(6, TableIndex.MethodSemantics),
Handle(2, TableIndex.GenericParam));
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)));
}
/// <summary>
/// [assembly: ...] and [module: ...] attributes should
/// not be included in delta metadata.
/// </summary>
[Fact]
public void AssemblyAndModuleAttributeReferences()
{
var source0 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
}";
var source1 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var readers = new[] { reader0, md1.Reader };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, md1.Reader.GetTypeDefNames());
CheckNames(readers, md1.Reader.GetMethodDefNames(), "M");
CheckEncLog(md1.Reader,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M
CheckEncMap(md1.Reader,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void OtherReferences()
{
var source0 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
}
}";
var source1 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
object o;
o = typeof(D);
o = F;
o = P;
E += null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C");
CheckNames(reader0, reader0.GetEventDefNames(), "E");
CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor");
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
// Emit delta metadata.
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetEventDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M");
CheckNames(readers, reader1.GetPropertyDefNames());
}
[Fact]
public void ArrayInitializer()
{
var source0 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3 };
}
}");
var source1 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3, 4 };
}
}");
var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll);
var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs"));
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M"))));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL(
@"{
// Code size 25 (0x19)
.maxstack 4
IL_0000: nop
IL_0001: ldc.i4.4
IL_0002: newarr 0x0100000D
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.4
IL_0016: stelem.i4
IL_0017: stloc.0
IL_0018: ret
}");
diff1.VerifyPdb(new[] { 0x06000001 },
@"<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" />
</files>
<methods>
<method token=""0x6000001"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x19"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void PInvokeModuleRefAndImplMap()
{
var source0 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
}";
var source1 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
[DllImport(""msvcrt.dll"")]
public static extern int puts(string s);
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.ImplMap));
}
/// <summary>
/// ClassLayout and FieldLayout tables.
/// </summary>
[Fact]
public void ClassAndFieldLayout()
{
var source0 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}";
var source1 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}
[StructLayout(LayoutKind.Explicit, Pack=4)]
class B
{
[FieldOffset(0)]internal short F;
[FieldOffset(4)]internal short G;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default),
Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default),
Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.ClassLayout),
Handle(3, TableIndex.FieldLayout),
Handle(4, TableIndex.FieldLayout),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void NamespacesAndOverloads()
{
var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source:
@"class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
}
}
}");
var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2");
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var compilation1 = compilation0.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
}
}
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2])));
diff1.VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
}");
var compilation2 = compilation1.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
M1(c);
}
}
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"),
compilation2.GetMember<MethodSymbol>("M.C.M2"))));
diff2.VerifyIL(
@"{
// Code size 26 (0x1a)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: call 0x06000002
IL_0008: nop
IL_0009: ldarg.0
IL_000a: ldarg.2
IL_000b: call 0x06000003
IL_0010: nop
IL_0011: ldarg.0
IL_0012: ldarg.3
IL_0013: call 0x06000007
IL_0018: nop
IL_0019: ret
}");
}
[Fact]
public void TypesAndOverloads()
{
const string source =
@"using System;
struct A<T>
{
internal class B<U> { }
}
class B { }
class C
{
static void M(A<B>.B<object> a)
{
M(a);
M((A<B>.B<B>)null);
}
static void M(A<B>.B<B> a)
{
M(a);
M((A<B>.B<object>)null);
}
static void M(A<B> a)
{
M(a);
M((A<B>?)a);
}
static void M(Nullable<A<B>> a)
{
M(a);
M(a.Value);
}
unsafe static void M(int* p)
{
M(p);
M((byte*)p);
}
unsafe static void M(byte* p)
{
M(p);
M((int*)p);
}
static void M(B[][] b)
{
M(b);
M((object[][])b);
}
static void M(object[][] b)
{
M(b);
M((B[][])b);
}
static void M(A<B[]>.B<object> b)
{
M(b);
M((A<B[, ,]>.B<object>)null);
}
static void M(A<B[, ,]>.B<object> b)
{
M(b);
M((A<B[]>.B<object>)null);
}
static void M(dynamic d)
{
M(d);
M((dynamic[])d);
}
static void M(dynamic[] d)
{
M(d);
M((dynamic)d);
}
static void M<T>(A<int>.B<T> t) where T : B
{
M(t);
M((A<double>.B<int>)null);
}
static void M<T>(A<double>.B<T> t) where T : struct
{
M(t);
M((A<int>.B<B>)null);
}
}";
var options = TestOptions.UnsafeDebugDll;
var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef });
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var n = compilation0.GetMembers("C.M").Length;
Assert.Equal(14, n);
//static void M(A<B>.B<object> a)
//{
// M(a);
// M((A<B>.B<B>)null);
//}
var compilation1 = compilation0.WithSource(source);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0])));
diff1.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B>.B<B> a)
//{
// M(a);
// M((A<B>.B<object>)null);
//}
var compilation2 = compilation1.WithSource(source);
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1])));
diff2.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000003
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000002
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B> a)
//{
// M(a);
// M((A<B>?)a);
//}
var compilation3 = compilation2.WithSource(source);
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2])));
diff3.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000004
IL_0007: nop
IL_0008: ldarg.0
IL_0009: newobj 0x0A000016
IL_000e: call 0x06000005
IL_0013: nop
IL_0014: ret
}");
//static void M(Nullable<A<B>> a)
//{
// M(a);
// M(a.Value);
//}
var compilation4 = compilation3.WithSource(source);
var diff4 = compilation4.EmitDifference(
diff3.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3])));
diff4.VerifyIL(
@"{
// Code size 22 (0x16)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000005
IL_0007: nop
IL_0008: ldarga.s V_0
IL_000a: call 0x0A000017
IL_000f: call 0x06000004
IL_0014: nop
IL_0015: ret
}");
//unsafe static void M(int* p)
//{
// M(p);
// M((byte*)p);
//}
var compilation5 = compilation4.WithSource(source);
var diff5 = compilation5.EmitDifference(
diff4.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4])));
diff5.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000006
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000007
IL_000e: nop
IL_000f: ret
}");
//unsafe static void M(byte* p)
//{
// M(p);
// M((int*)p);
//}
var compilation6 = compilation5.WithSource(source);
var diff6 = compilation6.EmitDifference(
diff5.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5])));
diff6.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000007
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000006
IL_000e: nop
IL_000f: ret
}");
//static void M(B[][] b)
//{
// M(b);
// M((object[][])b);
//}
var compilation7 = compilation6.WithSource(source);
var diff7 = compilation7.EmitDifference(
diff6.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6])));
diff7.VerifyIL(
@"{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000008
IL_0007: nop
IL_0008: ldarg.0
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: call 0x06000009
IL_0010: nop
IL_0011: ret
}");
//static void M(object[][] b)
//{
// M(b);
// M((B[][])b);
//}
var compilation8 = compilation7.WithSource(source);
var diff8 = compilation8.EmitDifference(
diff7.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7])));
diff8.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000009
IL_0007: nop
IL_0008: ldarg.0
IL_0009: castclass 0x1B00000A
IL_000e: call 0x06000008
IL_0013: nop
IL_0014: ret
}");
//static void M(A<B[]>.B<object> b)
//{
// M(b);
// M((A<B[,,]>.B<object>)null);
//}
var compilation9 = compilation8.WithSource(source);
var diff9 = compilation9.EmitDifference(
diff8.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8])));
diff9.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000A
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000B
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B[,,]>.B<object> b)
//{
// M(b);
// M((A<B[]>.B<object>)null);
//}
var compilation10 = compilation9.WithSource(source);
var diff10 = compilation10.EmitDifference(
diff9.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9])));
diff10.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000B
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000A
IL_000e: nop
IL_000f: ret
}");
// TODO: dynamic
#if false
//static void M(dynamic d)
//{
// M(d);
// M((dynamic[])d);
//}
previousMethod = compilation.GetMembers("C.M")[10];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(dynamic[] d)
//{
// M(d);
// M((dynamic)d);
//}
previousMethod = compilation.GetMembers("C.M")[11];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
#endif
//static void M<T>(A<int>.B<T> t) where T : B
//{
// M(t);
// M((A<double>.B<int>)null);
//}
var compilation11 = compilation10.WithSource(source);
var diff11 = compilation11.EmitDifference(
diff10.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12])));
diff11.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000005
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000006
IL_000e: nop
IL_000f: ret
}");
//static void M<T>(A<double>.B<T> t) where T : struct
//{
// M(t);
// M((A<int>.B<B>)null);
//}
var compilation12 = compilation11.WithSource(source);
var diff12 = compilation12.EmitDifference(
diff11.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13])));
diff12.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000007
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000008
IL_000e: nop
IL_000f: ret
}");
}
[Fact]
public void Struct_ImplementSynthesizedConstructor()
{
var source0 =
@"
struct S
{
int a = 1;
int b;
}
";
var source1 =
@"
struct S
{
int a = 1;
int b;
public S()
{
b = 2;
}
}
";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var ctor0 = compilation0.GetMember<MethodSymbol>("S..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("S..ctor");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
// Verify full metadata contains expected rows.
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "S");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
/// <summary>
/// Types should be retained in deleted locals
/// for correct alignment of remaining locals.
/// </summary>
[Fact]
public void DeletedValueTypeLocal()
{
var source0 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var x = new S1(1, 2);
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var source1 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.Main");
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
testData0.GetMethodData("C.Main").VerifyIL(
@"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (S1 V_0, //x
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: call ""S1..ctor(int, int)""
IL_000a: ldloca.s V_1
IL_000c: ldc.i4.3
IL_000d: call ""S2..ctor(int)""
IL_0012: ldloc.1
IL_0013: ldfld ""int S2.C""
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: nop
IL_001e: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main",
@"{
// Code size 22 (0x16)
.maxstack 2
.locals init ([unchanged] V_0,
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_1
IL_0003: ldc.i4.3
IL_0004: call ""S2..ctor(int)""
IL_0009: ldloc.1
IL_000a: ldfld ""int S2.C""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}");
}
/// <summary>
/// Instance and static constructors synthesized for
/// PrivateImplementationDetails should not be
/// generated for delta.
/// </summary>
[Fact]
public void PrivateImplementationDetails()
{
var source =
@"class C
{
static int[] F = new int[] { 1, 2, 3 };
int[] G = new int[] { 4, 5, 6 };
int M(int index)
{
return F[index] + G[index];
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var reader0 = md0.MetadataReader;
var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames());
Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)));
}
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 22 (0x16)
.maxstack 3
.locals init ([int] V_0,
int V_1)
IL_0000: nop
IL_0001: ldsfld ""int[] C.F""
IL_0006: ldarg.1
IL_0007: ldelem.i4
IL_0008: ldarg.0
IL_0009: ldfld ""int[] C.G""
IL_000e: ldarg.1
IL_000f: ldelem.i4
IL_0010: add
IL_0011: stloc.1
IL_0012: br.s IL_0014
IL_0014: ldloc.1
IL_0015: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromMetadata()
{
var source0 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[0]);
}
}";
var source1 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[1]);
}
}";
var source2 =
@"class C
{
static void M()
{
int[] a = { 4, 5, 6, 7, 8, 9, 10 };
System.Console.WriteLine(a[1]);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE"));
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
methodData0.VerifyIL(
@" {
// Code size 29 (0x1d)
.maxstack 3
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ldc.i4.0
IL_0015: ldelem.i4
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: nop
IL_001c: ret
}
");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"{
// Code size 30 (0x1e)
.maxstack 4
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldc.i4.1
IL_0016: ldelem.i4
IL_0017: call ""void System.Console.WriteLine(int)""
IL_001c: nop
IL_001d: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 48 (0x30)
.maxstack 4
.locals init ([unchanged] V_0,
int[] V_1) //a
IL_0000: nop
IL_0001: ldc.i4.7
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.4
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.5
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.6
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.7
IL_0016: stelem.i4
IL_0017: dup
IL_0018: ldc.i4.4
IL_0019: ldc.i4.8
IL_001a: stelem.i4
IL_001b: dup
IL_001c: ldc.i4.5
IL_001d: ldc.i4.s 9
IL_001f: stelem.i4
IL_0020: dup
IL_0021: ldc.i4.6
IL_0022: ldc.i4.s 10
IL_0024: stelem.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: ldelem.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromSource()
{
// PrivateImplementationDetails not needed initially.
var source0 =
@"class C
{
static object F1() { return null; }
static object F2() { return null; }
static object F3() { return null; }
static object F4() { return null; }
}";
var source1 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return null; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var source2 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return new[] { 13, 14, 15 }; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4"))));
diff1.VerifyIL("C.F1",
@"{
// Code size 24 (0x18)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: ldloc.0
IL_0017: ret
}");
diff1.VerifyIL("C.F4",
@"{
// Code size 25 (0x19)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.7
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.8
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.s 9
IL_0013: stelem.i4
IL_0014: stloc.0
IL_0015: br.s IL_0017
IL_0017: ldloc.0
IL_0018: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3"))));
diff2.VerifyIL("C.F1",
@"{
// Code size 49 (0x31)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: brtrue.s IL_002c
IL_0016: pop
IL_0017: ldc.i4.3
IL_0018: newarr ""int""
IL_001d: dup
IL_001e: ldc.i4.0
IL_001f: ldc.i4.s 10
IL_0021: stelem.i4
IL_0022: dup
IL_0023: ldc.i4.1
IL_0024: ldc.i4.s 11
IL_0026: stelem.i4
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: ldc.i4.s 12
IL_002b: stelem.i4
IL_002c: stloc.0
IL_002d: br.s IL_002f
IL_002f: ldloc.0
IL_0030: ret
}");
diff2.VerifyIL("C.F3",
@"{
// Code size 27 (0x1b)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.s 13
IL_000b: stelem.i4
IL_000c: dup
IL_000d: ldc.i4.1
IL_000e: ldc.i4.s 14
IL_0010: stelem.i4
IL_0011: dup
IL_0012: ldc.i4.2
IL_0013: ldc.i4.s 15
IL_0015: stelem.i4
IL_0016: stloc.0
IL_0017: br.s IL_0019
IL_0019: ldloc.0
IL_001a: ret
}");
}
/// <summary>
/// Should not generate method for string switch since
/// the CLR only allows adding private members.
/// </summary>
[WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")]
[Fact]
public void PrivateImplementationDetails_ComputeStringHash()
{
var source =
@"class C
{
static int F(string s)
{
switch (s)
{
case ""1"": return 1;
case ""2"": return 2;
case ""3"": return 3;
case ""4"": return 4;
case ""5"": return 5;
case ""6"": return 6;
case ""7"": return 7;
default: return 0;
}
}
}";
const string ComputeStringHashName = "ComputeStringHash";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.F");
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
// Should have generated call to ComputeStringHash and
// added the method to <PrivateImplementationDetails>.
var actualIL0 = methodData0.GetMethodIL();
Assert.True(actualIL0.Contains(ComputeStringHashName));
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Should not have generated call to ComputeStringHash nor
// added the method to <PrivateImplementationDetails>.
var actualIL1 = diff1.GetMethodIL("C.F");
Assert.False(actualIL1.Contains(ComputeStringHashName));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetMethodDefNames(), "F");
}
/// <summary>
/// Unique ids should not conflict with ids
/// from previous generation.
/// </summary>
[WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")]
public void UniqueIds()
{
var source0 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
System.Func<int> g = () => 2;
return (b ? f : g)();
}
}";
var source1 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
return f();
}
}";
var source2 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> g = () => 2;
return g();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1])));
diff1.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //f
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__5()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1])));
diff2.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //g
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__7()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
}
/// <summary>
/// Avoid adding references from method bodies
/// other than the changed methods.
/// </summary>
[Fact]
public void ReferencesInIL()
{
var source0 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.WriteLine(2); }
}";
var source1 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.Write(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.G");
var method1 = compilation1.GetMember<MethodSymbol>("C.G");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(
SemanticEditKind.Update,
method0,
method1,
GetEquivalentNodesMap(method1, method0),
preserveLocalVariables: true)));
// "Write" should be included in string table, but "WriteLine" should not.
Assert.True(diff1.MetadataDelta.IsIncluded("Write"));
Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine"));
}
/// <summary>
/// Local slots must be preserved based on signature.
/// </summary>
[Fact]
public void PreserveLocalSlots()
{
var source0 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
A<B> y = F();
object z = F();
M(x);
M(y);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" };
var source1 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
B z = F();
A<B> y = F();
object w = F();
M(w);
M(y);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source2 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source3 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object c = F();
object b = F();
M(c);
M(b);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("B.M");
var methodN = compilation0.GetMember<MethodSymbol>("B.N");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo());
#region Gen1
var method1 = compilation1.GetMember<MethodSymbol>("B.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL(
@"{
// Code size 36 (0x24)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.3
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: call 0x06000002
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: call 0x06000003
IL_001b: nop
IL_001c: ldloc.1
IL_001d: call 0x06000003
IL_0022: nop
IL_0023: ret
}");
diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" />
<entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x24"">
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen2
var method2 = compilation2.GetMember<MethodSymbol>("B.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL(
@"{
// Code size 30 (0x1e)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.s V_5
IL_0008: call 0x06000002
IL_000d: stloc.3
IL_000e: ldloc.s V_5
IL_0010: call 0x06000003
IL_0015: nop
IL_0016: ldloc.3
IL_0017: call 0x06000003
IL_001c: nop
IL_001d: ret
}");
diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" />
<entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" />
<entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1e"">
<local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen3
// Modify different method. (Previous generations
// have not referenced method.)
method2 = compilation2.GetMember<MethodSymbol>("B.N");
var method3 = compilation3.GetMember<MethodSymbol>("B.N");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL(
@"{
// Code size 28 (0x1c)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.2
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: ldloc.2
IL_000e: call 0x06000003
IL_0013: nop
IL_0014: ldloc.1
IL_0015: call 0x06000003
IL_001a: nop
IL_001b: ret
}");
diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000004"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
}
/// <summary>
/// Preserve locals for method added after initial compilation.
/// </summary>
[Fact]
public void PreserveLocalSlots_NewMethod()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void M()
{
var a = new object();
var b = string.Empty;
}
}";
var source2 =
@"class C
{
static void M()
{
var a = 1;
var b = string.Empty;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true)));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 10 (0xa)
.maxstack 1
.locals init ([object] V_0,
string V_1, //b
int V_2) //a
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldsfld ""string string.Empty""
IL_0008: stloc.1
IL_0009: ret
}");
diff2.VerifyPdb(new[] { 0x06000002 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000002"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" />
<entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Local types should be retained, even if the local is no longer
/// used by the method body, since there may be existing
/// references to that slot, in a Watch window for instance.
/// </summary>
[WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")]
[Fact]
public void PreserveLocalTypes()
{
var source0 =
@"class C
{
static void Main()
{
var x = true;
var y = x;
System.Console.WriteLine(y);
}
}";
var source1 =
@"class C
{
static void Main()
{
var x = ""A"";
var y = x;
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main", @"
{
// Code size 17 (0x11)
.maxstack 1
.locals init ([bool] V_0,
[bool] V_1,
string V_2, //x
string V_3) //y
IL_0000: nop
IL_0001: ldstr ""A""
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: stloc.3
IL_0009: ldloc.3
IL_000a: call ""void System.Console.WriteLine(string)""
IL_000f: nop
IL_0010: ret
}");
}
/// <summary>
/// Preserve locals if SemanticEdit.PreserveLocalVariables is set.
/// </summary>
[Fact]
public void PreserveLocalVariablesFlag()
{
var source =
@"class C
{
static System.IDisposable F() { return null; }
static void M()
{
using (F()) { }
using (var x = F()) { }
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1a = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false)));
diff1a.VerifyIL("C.M", @"
{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}
");
var diff1b = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true)));
diff1b.VerifyIL("C.M",
@"{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}");
}
[WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")]
[Fact]
public void ChangeLocalType()
{
var source0 =
@"enum E { }
class C
{
static void M1()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in one method to type added.
var source1 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in another method.
var source2 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in same method.
var source3 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(A);
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M1");
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M2");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M2",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method3 = compilation3.GetMember<MethodSymbol>("C.M2");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL("C.M2",
@"{
// Code size 18 (0x12)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[unchanged] V_2,
A V_3, //x
A V_4, //y
A V_5) //z
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldnull
IL_0007: stloc.s V_5
IL_0009: ldloc.s V_4
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Update()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 1 }</N:0>;
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</N:0>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md1 = diff1.GetMetadata();
AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader }));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
[Fact]
public void AnonymousTypes_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</N:0>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
/// <summary>
/// Reuse existing anonymous types.
/// </summary>
[WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")]
[Fact]
public void AnonymousTypes()
{
var source0 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = x.A;
var z = new { };
}
}
}";
var source1 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = new { A = x.A };
var z = new { };
}
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var m0 = compilation0.GetMember<MethodSymbol>("M.B.M");
var m1 = compilation1.GetMember<MethodSymbol>("M.B.M");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider());
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type
diff1.VerifyIL("M.B.M", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (<>f__AnonymousType1<int, int> V_0, //x
[int] V_1,
<>f__AnonymousType2 V_2, //z
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: ldc.i4.4
IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get""
IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_0014: stloc.3
IL_0015: newobj ""<>f__AnonymousType2..ctor()""
IL_001a: stloc.2
IL_001b: ret
}");
}
/// <summary>
/// Anonymous type names with module ids
/// and gaps in indices.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")]
[WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")]
public void AnonymousTypes_OtherTypeNames()
{
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
// Valid signature, although not sequential index
.class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
.field public !'<B>j__TPar' B
}
// Invalid signature, unexpected type parameter names
.class '<>f__AnonymousType1'<A, B> extends object
{
.field public !A A
.field public !B B
}
// Module id, duplicate index
.class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
}
// Module id
.class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object
{
.field public !'<B>j__TPar' B
}
.class public C extends object
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F()
{
ldnull
ret
}
}";
var source0 =
@"class C
{
static object F()
{
return 0;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 1 };
var y = new { A = x.A };
return y;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
diff1.VerifyIL("C.F",
@"{
// Code size 31 (0x1f)
.maxstack 2
.locals init (<>f__AnonymousType2<object, int> V_0, //x
<>f__AnonymousType3<object> V_1, //y
object V_2)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: ldc.i4.1
IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get""
IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)""
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: stloc.2
IL_001b: br.s IL_001d
IL_001d: ldloc.2
IL_001e: ret
}");
}
/// <summary>
/// Update method with anonymous type that was
/// not directly referenced in previous generation.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration()
{
var source0 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x;
}
}");
var source1 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x + 1;
}
}");
var source2 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 2 }</N:2>;
return x.A;
}
}");
var source3 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 3 }</N:2>;
return y.B;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var compilation3 = compilation2.WithSource(source3.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var method0 = compilation0.GetMember<MethodSymbol>("B.G");
var method1 = compilation1.GetMember<MethodSymbol>("B.G");
var method2 = compilation2.GetMember<MethodSymbol>("B.G");
var method3 = compilation3.GetMember<MethodSymbol>("B.G");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types
diff1.VerifyIL("B.G", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (int V_0, //x
[object] V_1,
object V_2)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.1
IL_0005: add
IL_0006: box ""int""
IL_000b: stloc.2
IL_000c: br.s IL_000e
IL_000e: ldloc.2
IL_000f: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type
diff2.VerifyIL("B.G", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
object V_5)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.2
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.3
IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get""
IL_001a: stloc.s V_5
IL_001c: br.s IL_001e
IL_001e: ldloc.s V_5
IL_0020: ret
}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types
diff3.VerifyIL("B.G", @"
{
// Code size 39 (0x27)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
[object] V_5,
object V_6)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.3
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get""
IL_001b: box ""int""
IL_0020: stloc.s V_6
IL_0022: br.s IL_0024
IL_0024: ldloc.s V_6
IL_0026: ret
}");
}
/// <summary>
/// Update another method (without directly referencing
/// anonymous type) after updating method with anonymous type.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration_2()
{
var source0 =
@"class C
{
static object F()
{
var x = new { A = 1 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x + 1;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = new { A = (object)null };
var y = new { A = 'a', B = 'b' };
return x;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch
{
"F" => testData0.GetMethodData("C.F").GetEncDebugInfo(),
"G" => testData0.GetMethodData("C.G").GetEncDebugInfo(),
_ => default,
});
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames()); // no additional types
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true)));
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
CheckNames(readers, reader3.GetTypeDefNames()); // no additional types
}
/// <summary>
/// Local from previous generation is of an anonymous
/// type not available in next generation.
/// </summary>
[Fact]
public void AnonymousTypes_AddThenDelete()
{
var source0 =
@"class C
{
object A;
static object F()
{
var x = new C();
var y = x.A;
return y;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object() };
var y = x.A;
return y;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 2 };
var y = x.A;
y = new { B = new object() }.B;
return y;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 3 };
var y = x.A;
return y;
}
}";
var source4 =
@"class C
{
static object F()
{
var x = new { B = 4, A = new object() };
var y = x.A;
return y;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var compilation4 = compilation3.WithSource(source4);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type
diff1.VerifyIL("C.F", @"
{
// Code size 27 (0x1b)
.maxstack 1
.locals init ([unchanged] V_0,
object V_1, //y
[object] V_2,
<>f__AnonymousType0<object> V_3, //x
object V_4)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)""
IL_000b: stloc.3
IL_000c: ldloc.3
IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get""
IL_0012: stloc.1
IL_0013: ldloc.1
IL_0014: stloc.s V_4
IL_0016: br.s IL_0018
IL_0018: ldloc.s V_4
IL_001a: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
}
[Fact]
public void AnonymousTypes_DifferentCase()
{
var source0 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { A = 1, B = 2 }</N:0>;
var <N:1>y = new { a = 3, b = 4 }</N:1>;
}
}");
var source1 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { AB = 3 }</N:1>;
}
}");
var source2 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { Ab = 5 }</N:1>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var m0 = compilation0.GetMember<MethodSymbol>("C.M");
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1");
// the first two slots can't be reused since the type changed
diff1.VerifyIL("C.M",
@"{
// Code size 17 (0x11)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.3
IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_000f: stloc.3
IL_0010: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1");
// we can reuse slot for "x", it's type haven't changed
diff2.VerifyIL("C.M",
@"{
// Code size 18 (0x12)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
[unchanged] V_3,
<>f__AnonymousType4<int> V_4) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.5
IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)""
IL_000f: stloc.s V_4
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Nested1()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: ret
}
";
v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Nested2()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: ret
}
";
v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Query1()
{
var source0 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
<N:3>select new { Value = a, Length = a.Length }</N:3></N:4>;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value</N:8>;
args = args.Concat(newArgs).ToArray();
System.Diagnostics.Debugger.Break();
result.ToString();
}
}
");
var source1 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null };
for (int i = 0; i < 10; i++)
{
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby a.Length ascending, a descending
<N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>;
var linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
(total, curr) => new { Head = curr.Value, Tail = (dynamic)total });
var str = linked?.Tail?.Head;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value + value</N:8>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1) //newArgs
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>o__0#1: {<>p__0}",
"C: {<>o__0#1, <>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}",
"<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1, //newArgs
<>f__AnonymousType5<dynamic, dynamic> V_2, //list
int V_3, //i
<>f__AnonymousType5<string, dynamic> V_4, //linked
object V_5, //str
<>f__AnonymousType5<string, dynamic> V_6,
object V_7,
bool V_8)
");
}
[Fact]
public void AnonymousTypes_Dynamic1()
{
var template = @"
using System;
class C
{
public void F()
{
var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>;
Console.WriteLine(x.B + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var baselineIL0 = @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}
";
v0.VerifyIL("C.F", baselineIL0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
var baselineIL = @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: ldc.i4.<<VALUE>>
IL_0010: add
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: nop
IL_0017: ret
}
";
diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2"));
}
/// <summary>
/// Should not re-use locals if the method metadata
/// signature is unsupported.
/// </summary>
[WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")]
public void LocalType_UnsupportedSignatureContent()
{
// Equivalent to C#, but with extra local and required modifier on
// expected local. Used to generate initial (unsupported) metadata.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method private static object F()
{
ldnull
ret
}
.method private static void M1()
{
.locals init ([0] object other, [1] object modreq(int32) o)
call object C::F()
stloc.1
ldloc.1
call void C::M2(object)
ret
}
.method private static void M2(object o)
{
ret
}
}";
var source =
@"class C
{
static object F()
{
return null;
}
static void M1()
{
object o = F();
M2(o);
}
static void M2(object o)
{
}
}";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 15 (0xf)
.maxstack 1
.locals init (object V_0) //o
IL_0000: nop
IL_0001: call ""object C.F()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call ""void C.M2(object)""
IL_000d: nop
IL_000e: ret
}");
}
/// <summary>
/// Should not re-use locals with custom modifiers.
/// </summary>
[WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")]
public void LocalType_CustomModifiers()
{
// Equivalent method signature to C#, but
// with optional modifier on locals.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class public C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F(class [mscorlib]System.IDisposable d)
{
.locals init ([0] class C modopt(int32) c,
[1] class [mscorlib]System.IDisposable modopt(object),
[2] bool V_2,
[3] object V_3)
ldnull
ret
}
}";
var source =
@"class C
{
static object F(System.IDisposable d)
{
C c;
using (d)
{
c = (C)d;
}
return c;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
moduleMetadata0,
m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[bool] V_2,
[object] V_3,
C V_4, //c
System.IDisposable V_5,
object V_6)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: stloc.s V_5
.try
{
-IL_0004: nop
-IL_0005: ldarg.0
IL_0006: castclass ""C""
IL_000b: stloc.s V_4
-IL_000d: nop
IL_000e: leave.s IL_001d
}
finally
{
~IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_001c
IL_0014: ldloc.s V_5
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: nop
IL_001c: endfinally
}
-IL_001d: ldloc.s V_4
IL_001f: stloc.s V_6
IL_0021: br.s IL_0023
-IL_0023: ldloc.s V_6
IL_0025: ret
}", methodToken: diff1.EmitResult.UpdatedMethods.Single());
}
/// <summary>
/// Temporaries for locals used within a single
/// statement should not be preserved.
/// </summary>
[Fact]
public void TemporaryLocals_Other()
{
// Use increment as an example of a compiler generated
// temporary that does not span multiple statements.
var source =
@"class C
{
int P { get; set; }
static int M()
{
var c = new C();
return c.P++;
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (C V_0, //c
[int] V_1,
[int] V_2,
int V_3,
int V_4)
IL_0000: nop
IL_0001: newobj ""C..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: dup
IL_0009: callvirt ""int C.P.get""
IL_000e: stloc.3
IL_000f: ldloc.3
IL_0010: ldc.i4.1
IL_0011: add
IL_0012: callvirt ""void C.P.set""
IL_0017: nop
IL_0018: ldloc.3
IL_0019: stloc.s V_4
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_4
IL_001f: ret
}");
}
/// <summary>
/// Local names array (from PDB) may have fewer slots than method
/// signature (from metadata) when the trailing slots are unnamed.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270()
{
var source =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
testData0.GetMethodData("C.M").VerifyIL(@"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
}
/// <summary>
/// Similar to above test but with no named locals in original.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270_NoNamedLocals()
{
// Equivalent to C#, but with unnamed locals.
// Used to generate initial metadata.
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
.assembly '<<GeneratedFileName>>' { }
.class C extends object
{
.method private static class [netstandard]System.IDisposable F()
{
ldnull
ret
}
.method private static void M()
{
.locals init ([0] object, [1] object)
ret
}
}";
var source0 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
}
}";
var source1 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init ([object] V_0,
[object] V_1,
System.IDisposable V_2) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.2
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.2
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.2
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}
");
}
[Fact]
public void TemporaryLocals_ReferencedType()
{
var source =
@"class C
{
static object F()
{
return null;
}
static void M()
{
var x = new System.Collections.Generic.HashSet<int>();
x.Add(1);
}
}";
var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var modMeta = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
modMeta,
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (System.Collections.Generic.HashSet<int> V_0) //x
IL_0000: nop
IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)""
IL_000e: pop
IL_000f: ret
}
");
}
[WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")]
[WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")]
[Fact]
public void DynamicOperations()
{
var source =
@"class A
{
static object F = null;
object x = ((dynamic)F) + 1;
static A()
{
((dynamic)F).F();
}
A() { }
static void M(object o)
{
((dynamic)o).x = 1;
}
static void N(A o)
{
o.x = 1;
}
}
class B
{
static object F = null;
static object G = ((dynamic)F).F();
object x = ((dynamic)F) + 1;
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef });
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
// Source method with dynamic operations.
var methodData0 = testData0.GetMethodData("A.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("A.M");
var method1 = compilation1.GetMember<MethodSymbol>("A.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Source method with no dynamic operations.
methodData0 = testData0.GetMethodData("A.N");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A.N");
method1 = compilation1.GetMember<MethodSymbol>("A.N");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..ctor");
method1 = compilation1.GetMember<MethodSymbol>("A..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..cctor");
method1 = compilation1.GetMember<MethodSymbol>("A..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..ctor");
method1 = compilation1.GetMember<MethodSymbol>("B..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..cctor");
method1 = compilation1.GetMember<MethodSymbol>("B..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
}
[Fact]
public void DynamicLocals()
{
var template = @"
using System;
class C
{
public void F()
{
dynamic <N:0>x = 1</N:0>;
Console.WriteLine((int)x + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F", @"
{
// Code size 82 (0x52)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: call ""void System.Console.WriteLine(int)""
IL_0050: nop
IL_0051: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>o__0#1}",
"C.<>o__0#1: {<>p__0}");
diff1.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.1
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>o__0#2, <>o__0#1}",
"C.<>o__0#1: {<>p__0}",
"C.<>o__0#2: {<>p__0}");
diff2.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.2
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
}
[Fact]
public void ExceptionFilters()
{
var source0 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
}
}
");
var source1 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
Console.WriteLine(1);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 90 (0x5a)
.maxstack 2
.locals init (System.IO.IOException V_0, //e
bool V_1,
System.Exception V_2, //e
bool V_3)
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: newobj ""System.InvalidOperationException..ctor()""
IL_0007: throw
}
filter
{
IL_0008: isinst ""System.IO.IOException""
IL_000d: dup
IL_000e: brtrue.s IL_0014
IL_0010: pop
IL_0011: ldc.i4.0
IL_0012: br.s IL_0020
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: call ""bool C.G(System.Exception)""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldc.i4.0
IL_001e: cgt.un
IL_0020: endfilter
} // end filter
{ // handler
IL_0022: pop
IL_0023: nop
IL_0024: call ""void System.Console.WriteLine()""
IL_0029: nop
IL_002a: nop
IL_002b: leave.s IL_0052
}
filter
{
IL_002d: isinst ""System.Exception""
IL_0032: dup
IL_0033: brtrue.s IL_0039
IL_0035: pop
IL_0036: ldc.i4.0
IL_0037: br.s IL_0045
IL_0039: stloc.2
IL_003a: ldloc.2
IL_003b: call ""bool C.G(System.Exception)""
IL_0040: stloc.3
IL_0041: ldloc.3
IL_0042: ldc.i4.0
IL_0043: cgt.un
IL_0045: endfilter
} // end filter
{ // handler
IL_0047: pop
IL_0048: nop
IL_0049: call ""void System.Console.WriteLine()""
IL_004e: nop
IL_004f: nop
IL_0050: leave.s IL_0052
}
IL_0052: ldc.i4.1
IL_0053: call ""void System.Console.WriteLine(int)""
IL_0058: nop
IL_0059: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void MethodSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(2);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
[WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void LocalSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(null);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(x);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,16): warning CS0219: The variable 'y' is assigned but its value is never used
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"),
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
/// <summary>
/// Disallow edits that require NoPIA references.
/// </summary>
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIAReferences()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")]
public interface IA
{
void M();
int P { get; }
event Action E;
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")]
public interface IB
{
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")]
public interface IC
{
}
public struct S
{
public object F;
}";
var source0 =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
var o = default(IA);
o.M();
M2(o.P);
o.E += M1;
M2(C<IA>.F);
M2(new S());
}
static void M2(object o)
{
}
}";
var source1A = source0;
var source1B =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
M2(null);
}
static void M2(object o)
{
}
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1A = compilation0.WithSource(source1A);
var compilation1B = compilation0.WithSource(source1B);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var method1B = compilation1B.GetMember<MethodSymbol>("C.M1");
var method1A = compilation1A.GetMember<MethodSymbol>("C.M1");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C<T>.M1");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
// Disallow edits that require NoPIA references.
var diff1A = compilation1A.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true)));
diff1A.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA"));
// Allow edits that do not require NoPIA references,
// even if the previous code included references.
var diff1B = compilation1B.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true)));
diff1B.VerifyIL("C<T>.M1",
@"{
// Code size 9 (0x9)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1)
IL_0000: nop
IL_0001: ldnull
IL_0002: call ""void C<T>.M2(object)""
IL_0007: nop
IL_0008: ret
}");
using var md1 = diff1B.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
}
[WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIATypeInNamespace()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")]
namespace N
{
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")]
public interface IA
{
}
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")]
public interface IB
{
}";
var source =
@"class C<T>
{
static void M(object o)
{
M(C<N.IA>.E.X);
M(C<IB>.E.X);
}
enum E { X }
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB"));
diff1.VerifyIL("C<T>.M",
@"{
// Code size 26 (0x1a)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: box ""C<N.IA>.E""
IL_0007: call ""void C<T>.M(object)""
IL_000c: nop
IL_000d: ldc.i4.0
IL_000e: box ""C<IB>.E""
IL_0013: call ""void C<T>.M(object)""
IL_0018: nop
IL_0019: ret
}");
}
/// <summary>
/// Should use TypeDef rather than TypeRef for unrecognized
/// local of a type defined in the original assembly.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfTypeFromAssembly()
{
var source =
@"class E : System.Exception
{
}
class C
{
static void M()
{
try
{
}
catch (E e)
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeRefNames(), "Object");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL("C.M", @"
{
// Code size 11 (0xb)
.maxstack 1
.locals init (E V_0) //e
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: nop
IL_0003: leave.s IL_000a
}
catch E
{
IL_0005: stloc.0
IL_0006: nop
IL_0007: nop
IL_0008: leave.s IL_000a
}
IL_000a: ret
}");
}
/// <summary>
/// Similar to above test but with anonymous type
/// added in subsequent generation.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfAnonymousTypeFromAssembly()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source2 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
return null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var method1G = compilation1.GetMember<MethodSymbol>("C.G");
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var method2G = compilation2.GetMember<MethodSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
// Use empty LocalVariableNameProvider for original locals and
// use preserveLocalVariables: true for the edit so that existing
// locals are retained even though all are unrecognized.
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1");
CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider");
// Change method updated in generation 1.
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetTypeRefNames(), "Object");
// Change method unchanged since generation 0.
var diff2G = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true)));
}
[Fact]
public void BrokenOutputStreams()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
badStream,
ilStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
badStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[Fact]
public void BrokenPortablePdbStream()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb));
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void Main() { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))),
testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() });
diff1.EmitResult.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message"));
Assert.False(diff1.EmitResult.Success);
}
[WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")]
[Fact]
public void BlobContainsInvalidValues()
{
var source0 =
@"class C
{
static void F()
{
string goo = ""abc"";
}
}";
var source1 =
@"class C
{
static void F()
{
float goo = 10;
}
}";
var source2 =
@"class C
{
static void F()
{
bool goo = true;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
var handle = MetadataTokens.BlobHandle(1);
byte[] value0 = reader0.GetBlobBytes(handle);
Assert.Equal("20-01-01-08", BitConverter.ToString(value0));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
byte[] value1 = reader1.GetBlobBytes(handle);
Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
byte[] value2 = reader2.GetBlobBytes(handle);
Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly1()
{
var sourceA0 = @"
public class A
{
}
";
var sourceA1 = @"
public class A
{
public void M() { System.Console.WriteLine(1);}
}
public class X {}
";
var sourceB0 = @"
public class B
{
public static void F() { }
}";
var sourceB1 = @"
public class B
{
public static void F() { new A().M(); }
}
public class Y : X { }
";
var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA");
var compilationA1 = compilationA0.WithSource(sourceA1);
var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var bytesA0 = compilationA0.EmitToArray();
var bytesB0 = compilationB0.EmitToArray();
var mdA0 = ModuleMetadata.CreateFromImage(bytesA0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider);
var mA1 = compilationA1.GetMember<MethodSymbol>("A.M");
var mX1 = compilationA1.GetMember<TypeSymbol>("X");
var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() };
var diffA1 = compilationA1.EmitDifference(
generationA0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, mA1),
SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)),
allAddedSymbols);
diffA1.EmitResult.Diagnostics.Verify();
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))),
allAddedSymbols);
diffB1.EmitResult.Diagnostics.Verify(
// (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public class X {}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14),
// (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public void M() { System.Console.WriteLine(1);}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly2()
{
var sourceA = @"
public class A
{
public void M() { }
}";
var sourceB0 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var sourceB1 = @"
public class B
{
public static void F() { var a = new A(); a.M(); }
}";
var sourceB2 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA");
var aRef = compilationA.ToMetadataReference();
var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB");
var compilationB1 = compilationB0.WithSource(sourceB1);
var compilationB2 = compilationB1.WithSource(sourceB2);
var testDataB0 = new CompilationTestData();
var bytesB0 = compilationB0.EmitToArray(testData: testDataB0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider());
var f0 = compilationB0.GetMember<MethodSymbol>("B.F");
var f1 = compilationB1.GetMember<MethodSymbol>("B.F");
var f2 = compilationB2.GetMember<MethodSymbol>("B.F");
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
diffB1.VerifyIL("B.F", @"
{
// Code size 15 (0xf)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: callvirt ""void A.M()""
IL_000d: nop
IL_000e: ret
}
");
var diffB2 = compilationB2.EmitDifference(
diffB1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true)));
diffB2.VerifyIL("B.F", @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)]
public void UniqueSynthesizedNames_DynamicSiteContainer()
{
var source0 = @"
public class C
{
public static void F(dynamic d) { d.Goo(); }
}";
var source1 = @"
public class C
{
public static void F(dynamic d) { d.Bar(); }
}";
var source2 = @"
public class C
{
public static void F(dynamic d, byte b) { d.Bar(); }
public static void F(dynamic d) { d.Bar(); }
}";
var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp,
options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
diff2.EmitResult.Diagnostics.Verify();
var reader0 = md0.MetadataReader;
var reader1 = diff1.GetMetadata().Reader;
var reader2 = diff2.GetMetadata().Reader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0");
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2");
}
[WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")]
[Fact]
public void ManyGenerations()
{
var source =
@"class C
{{
static int F() {{ return {0}; }}
}}";
var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll);
var bytes0 = compilation0.EmitToArray();
var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
for (int i = 2; i <= 50; i++)
{
var compilation1 = compilation0.WithSource(String.Format(source, i));
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
compilation0 = compilation1;
method0 = method1;
generation0 = diff1.NextGeneration;
}
}
[WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")]
[Fact]
public void PdbReadingErrors()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle =>
{
throw new InvalidDataException("Bad PDB!");
});
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''.
Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14));
}
[Fact]
public void PdbReadingErrors_PassThruExceptions()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle =>
{
throw new ArgumentOutOfRangeException();
});
// the compiler should't swallow any exceptions but InvalidDataException
Assert.Throws<ArgumentOutOfRangeException>(() =>
compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))));
}
[Fact]
public void PatternVariable_TypeChange()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 46 (0x2e)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3, //i
bool V_4,
int V_5)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""bool""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""bool""
IL_000f: stloc.3
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.s V_4
IL_0016: ldloc.s V_4
IL_0018: brfalse.s IL_0026
IL_001a: nop
IL_001b: ldloc.3
IL_001c: brtrue.s IL_0021
IL_001e: ldc.i4.0
IL_001f: br.s IL_0022
IL_0021: ldc.i4.1
IL_0022: stloc.s V_5
IL_0024: br.s IL_002b
IL_0026: ldc.i4.0
IL_0027: stloc.s V_5
IL_0029: br.s IL_002b
IL_002b: ldloc.s V_5
IL_002d: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[bool] V_4,
[int] V_5,
int V_6, //j
bool V_7,
int V_8)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_6
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_7
IL_0017: ldloc.s V_7
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_6
IL_001e: stloc.s V_8
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_8
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_8
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_DeleteInsert()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int) { return 1; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3,
int V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: ldnull
IL_0008: cgt.un
IL_000a: stloc.3
IL_000b: ldloc.3
IL_000c: brfalse.s IL_0014
IL_000e: nop
IL_000f: ldc.i4.1
IL_0010: stloc.s V_4
IL_0012: br.s IL_0019
IL_0014: ldc.i4.0
IL_0015: stloc.s V_4
IL_0017: br.s IL_0019
IL_0019: ldloc.s V_4
IL_001b: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[int] V_4,
int V_5, //i
bool V_6,
int V_7)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_5
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_6
IL_0017: ldloc.s V_6
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_5
IL_001e: stloc.s V_7
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_7
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_7
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(bool x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; }
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { }
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.1
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.1
IL_0015: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 15 (0xf)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: call ""Base..ctor(bool)""
IL_000c: nop
IL_000d: nop
IL_000e: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.2
IL_0015: ret
}
");
}
[Fact]
public void PatternVariable_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>;
}");
var source1 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.1
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 24 (0x18)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: stfld ""bool C.field""
IL_0010: ldarg.0
IL_0011: call ""object..ctor()""
IL_0016: nop
IL_0017: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.2
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void PatternVariable_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.1
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 7 (0x7)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ceq
IL_0006: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.2
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
}
[Fact]
public void Tuple_Parenthesized()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 51 (0x33)
.maxstack 4
.locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x
int V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)""
IL_0010: ldloc.0
IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1""
IL_0016: ldloc.0
IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0021: add
IL_0022: ldloc.0
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_002d: add
IL_002e: stloc.1
IL_002f: br.s IL_0031
IL_0031: ldloc.1
IL_0032: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init ([unchanged] V_0,
[int] V_1,
System.ValueTuple<int, int, int> V_2, //x
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_2
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)""
IL_000b: ldloc.2
IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1""
IL_0011: ldloc.2
IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2""
IL_0017: add
IL_0018: ldloc.2
IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3""
IL_001e: add
IL_001f: stloc.3
IL_0020: br.s IL_0022
IL_0022: ldloc.3
IL_0023: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init ([unchanged] V_0,
[int] V_1,
[unchanged] V_2,
[int] V_3,
System.ValueTuple<int, int> V_4, //x
int V_5)
IL_0000: nop
IL_0001: ldloca.s V_4
IL_0003: ldc.i4.1
IL_0004: ldc.i4.3
IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000a: ldloc.s V_4
IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0011: ldloc.s V_4
IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0018: add
IL_0019: stloc.s V_5
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_5
IL_001f: ret
}
");
}
[Fact]
public void Tuple_Decomposition()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2, //z
int V_3)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldc.i4.3
IL_0006: stloc.2
IL_0007: ldloc.0
IL_0008: ldloc.1
IL_0009: add
IL_000a: ldloc.2
IL_000b: add
IL_000c: stloc.3
IL_000d: br.s IL_000f
IL_000f: ldloc.3
IL_0010: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.3
IL_0004: stloc.2
IL_0005: ldloc.0
IL_0006: ldloc.2
IL_0007: add
IL_0008: stloc.s V_4
IL_000a: br.s IL_000c
IL_000c: ldloc.s V_4
IL_000e: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
[int] V_4,
int V_5, //y
int V_6)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.s V_5
IL_0006: ldc.i4.3
IL_0007: stloc.2
IL_0008: ldloc.0
IL_0009: ldloc.s V_5
IL_000b: add
IL_000c: ldloc.2
IL_000d: add
IL_000e: stloc.s V_6
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_6
IL_0014: ret
}
");
}
[Fact]
public void ForeachStatement()
{
var source0 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x);
}
}
}");
var source1 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var source2 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0,
int V_1,
int V_2, //x
bool V_3, //y
double V_4, //z
System.ValueTuple<bool, double> V_5)
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.0
IL_0008: ldc.i4.0
IL_0009: stloc.1
IL_000a: br.s IL_003f
IL_000c: ldloc.0
IL_000d: ldloc.1
IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0013: dup
IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0019: stloc.s V_5
IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0020: stloc.2
IL_0021: ldloc.s V_5
IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_0028: stloc.3
IL_0029: ldloc.s V_5
IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0030: stloc.s V_4
IL_0032: nop
IL_0033: ldloc.2
IL_0034: call ""void System.Console.WriteLine(int)""
IL_0039: nop
IL_003a: nop
IL_003b: ldloc.1
IL_003c: ldc.i4.1
IL_003d: add
IL_003e: stloc.1
IL_003f: ldloc.1
IL_0040: ldloc.0
IL_0041: ldlen
IL_0042: conv.i4
IL_0043: blt.s IL_000c
IL_0045: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.G", @"
{
// Code size 78 (0x4e)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
bool V_3, //y
double V_4, //z
[unchanged] V_5,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6,
int V_7,
System.ValueTuple<bool, double> V_8)
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_6
IL_0009: ldc.i4.0
IL_000a: stloc.s V_7
IL_000c: br.s IL_0045
IL_000e: ldloc.s V_6
IL_0010: ldloc.s V_7
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_001d: stloc.s V_8
IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0024: stloc.2
IL_0025: ldloc.s V_8
IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_002c: stloc.3
IL_002d: ldloc.s V_8
IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0034: stloc.s V_4
IL_0036: nop
IL_0037: ldloc.2
IL_0038: call ""void System.Console.WriteLine(int)""
IL_003d: nop
IL_003e: nop
IL_003f: ldloc.s V_7
IL_0041: ldc.i4.1
IL_0042: add
IL_0043: stloc.s V_7
IL_0045: ldloc.s V_7
IL_0047: ldloc.s V_6
IL_0049: ldlen
IL_004a: conv.i4
IL_004b: blt.s IL_000e
IL_004d: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 61 (0x3d)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
[bool] V_3,
[unchanged] V_4,
[unchanged] V_5,
[unchanged] V_6,
[int] V_7,
[unchanged] V_8,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9,
int V_10,
System.ValueTuple<bool, double> V_11) //yz
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_9
IL_0009: ldc.i4.0
IL_000a: stloc.s V_10
IL_000c: br.s IL_0034
IL_000e: ldloc.s V_9
IL_0010: ldloc.s V_10
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_001d: stloc.2
IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0023: stloc.s V_11
IL_0025: nop
IL_0026: ldloc.2
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: nop
IL_002d: nop
IL_002e: ldloc.s V_10
IL_0030: ldc.i4.1
IL_0031: add
IL_0032: stloc.s V_10
IL_0034: ldloc.s V_10
IL_0036: ldloc.s V_9
IL_0038: ldlen
IL_0039: conv.i4
IL_003a: blt.s IL_000e
IL_003c: ret
}
");
}
[Fact]
public void OutVar()
{
var source0 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; }
}");
var source1 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.2
IL_000f: br.s IL_0011
IL_0011: ldloc.2
IL_0012: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //z
[int] V_2,
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.3
IL_000f: br.s IL_0011
IL_0011: ldloc.3
IL_0012: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
[int] V_2,
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.s V_4
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_4
IL_0014: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); }
static int M(out int x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x) { }
static int M(out int x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.1
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 18 (0x12)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: call ""Base..ctor(int)""
IL_000f: nop
IL_0010: nop
IL_0011: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.2
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer_WithLambda()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0");
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0");
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InMethodBody_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method");
var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method");
var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.1
IL_0025: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff1.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
int V_2) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.2
IL_0025: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff2.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
[int] V_2,
int V_3) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.3
IL_0025: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>);
static int M(out int x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x;
static int M(out int x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 23 (0x17)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: stfld ""int C.field""
IL_000f: ldarg.0
IL_0010: call ""object..ctor()""
IL_0015: nop
IL_0016: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
}
[Fact]
public void OutVar_InFieldInitializer_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_1
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_2
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
}
[Fact]
public void OutVar_InQuery_WithLambda()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InSwitchExpression()
{
var source0 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i switch
{
0 => 0,
_ => 1
};
}
static object N(out int x) { x = 1; return null; }
}");
var source1 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i + N(out var x) switch
{
0 => 0,
_ => 1
};
}
static int N(out int x) { x = 1; return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.G");
var n1 = compilation1.GetMember<MethodSymbol>("Program.G");
var n2 = compilation2.GetMember<MethodSymbol>("Program.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.G(int)", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init (int V_0,
object V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000e
IL_000a: ldc.i4.0
IL_000b: stloc.0
IL_000c: br.s IL_0012
IL_000e: ldc.i4.1
IL_000f: stloc.0
IL_0010: br.s IL_0012
IL_0012: ldc.i4.1
IL_0013: brtrue.s IL_0016
IL_0015: nop
IL_0016: ldloc.0
IL_0017: box ""int""
IL_001c: stloc.1
IL_001d: br.s IL_001f
IL_001f: ldloc.1
IL_0020: ret
}
");
v0.VerifyIL("Program.N(out int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (object V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.1
IL_0003: stind.i4
IL_0004: ldnull
IL_0005: stloc.0
IL_0006: br.s IL_0008
IL_0008: ldloc.0
IL_0009: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers();
diff1.VerifyIL("Program.G(int)", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init ([int] V_0,
[object] V_1,
int V_2, //x
int V_3,
int V_4,
int V_5,
object V_6)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloca.s V_2
IL_0005: call ""int Program.N(out int)""
IL_000a: stloc.s V_5
IL_000c: ldc.i4.1
IL_000d: brtrue.s IL_0010
IL_000f: nop
IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_0016
IL_0014: br.s IL_001b
IL_0016: ldc.i4.0
IL_0017: stloc.s V_4
IL_0019: br.s IL_0020
IL_001b: ldc.i4.1
IL_001c: stloc.s V_4
IL_001e: br.s IL_0020
IL_0020: ldc.i4.1
IL_0021: brtrue.s IL_0024
IL_0023: nop
IL_0024: ldloc.3
IL_0025: ldloc.s V_4
IL_0027: add
IL_0028: box ""int""
IL_002d: stloc.s V_6
IL_002f: br.s IL_0031
IL_0031: ldloc.s V_6
IL_0033: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers();
diff2.VerifyIL("Program.G(int)", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[int] V_2,
[int] V_3,
[int] V_4,
[int] V_5,
[object] V_6,
int V_7,
object V_8)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000f
IL_000a: ldc.i4.0
IL_000b: stloc.s V_7
IL_000d: br.s IL_0014
IL_000f: ldc.i4.1
IL_0010: stloc.s V_7
IL_0012: br.s IL_0014
IL_0014: ldc.i4.1
IL_0015: brtrue.s IL_0018
IL_0017: nop
IL_0018: ldloc.s V_7
IL_001a: box ""int""
IL_001f: stloc.s V_8
IL_0021: br.s IL_0023
IL_0023: ldloc.s V_8
IL_0025: ret
}
");
}
[Fact]
public void AddUsing_AmbiguousCode()
{
var source0 = MarkedSource(@"
using System.Threading;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
}");
var source1 = MarkedSource(@"
using System.Threading;
using System.Timers;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
static void G()
{
System.Console.WriteLine(new TimersDescriptionAttribute(""""));
}
}");
var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Pretend there was an update to C.E to ensure we haven't invalidated the test
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer'
// var t = new Timer(s => System.Console.WriteLine(s));
Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21));
// Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff.EmitResult.Diagnostics.Verify();
diff.VerifyIL(@"C.G", @"
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldstr """"
IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)""
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}
");
}
[Fact]
public void Records_AddWellKnownMember()
{
var source0 =
@"
#nullable enable
namespace N
{
record R(int X)
{
}
}
";
var source1 =
@"
#nullable enable
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
// Verify full metadata contains expected rows.
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R");
CheckNames(reader0, reader0.GetMethodDefNames(),
/* EmbeddedAttribute */".ctor",
/* NullableAttribute */ ".ctor",
/* NullableContextAttribute */".ctor",
/* IsExternalInit */".ctor",
/* R: */
".ctor",
"get_EqualityContract",
"get_X",
"set_X",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), // R.PrintMembers
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(20, TableIndex.TypeRef),
Handle(21, TableIndex.TypeRef),
Handle(22, TableIndex.TypeRef),
Handle(10, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Records_RemoveWellKnownMember()
{
var source0 =
@"
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var source1 =
@"
namespace N
{
record R(int X)
{
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
}
[Fact]
public void TopLevelStatement_Update()
{
var source0 = @"
using System;
Console.WriteLine(""Hello"");
";
var source1 = @"
using System;
Console.WriteLine(""Hello World"");
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$");
var method1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "Program");
CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine", /*Program.*/".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$");
CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), // Synthesized Main method
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void LambdaParameterToDiscard()
{
var source0 = MarkedSource(@"
using System;
class C
{
void M()
{
var x = new Func<int, int, int>(<N:0>(a, b) => a + b + 1</N:0>);
Console.WriteLine(x(1, 2));
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void M()
{
var x = new Func<int, int, int>(<N:0>(_, _) => 10</N:0>);
Console.WriteLine(x(1, 2));
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// There should be no diagnostics from rude edits
diff.EmitResult.Diagnostics.Verify();
diff.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <M>b__0_0}");
diff.VerifyIL("C.M",
@"
{
// Code size 48 (0x30)
.maxstack 3
.locals init ([unchanged] V_0,
System.Func<int, int, int> V_1) //x
IL_0000: nop
IL_0001: ldsfld ""System.Func<int, int, int> C.<>c.<>9__0_0""
IL_0006: dup
IL_0007: brtrue.s IL_0020
IL_0009: pop
IL_000a: ldsfld ""C.<>c C.<>c.<>9""
IL_000f: ldftn ""int C.<>c.<M>b__0_0(int, int)""
IL_0015: newobj ""System.Func<int, int, int>..ctor(object, System.IntPtr)""
IL_001a: dup
IL_001b: stsfld ""System.Func<int, int, int> C.<>c.<>9__0_0""
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldc.i4.1
IL_0023: ldc.i4.2
IL_0024: callvirt ""int System.Func<int, int, int>.Invoke(int, int)""
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ret
}");
diff.VerifyIL("C.<>c.<M>b__0_0(int, int)", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldc.i4.s 10
IL_0002: ret
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
/// <summary>
/// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test.
/// </summary>
public class EditAndContinueTests : EditAndContinueTestBase
{
private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers)
{
var currentGenerationReader = readers.Last();
foreach (var typeRefHandle in currentGenerationReader.TypeReferences)
{
var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle);
yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}";
}
}
[Fact]
public void DeltaHeapsStartWithEmptyItem()
{
var source0 =
@"class C
{
static string F() { return null; }
}";
var source1 =
@"class C
{
static string F() { return ""a""; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var s = MetadataTokens.StringHandle(0);
Assert.Equal("", reader1.GetString(s));
var b = MetadataTokens.BlobHandle(0);
Assert.Equal(0, reader1.GetBlobBytes(b).Length);
var us = MetadataTokens.UserStringHandle(0);
Assert.Equal("", reader1.GetUserString(us));
}
[Fact]
public void Delta_AssemblyDefTable()
{
var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }";
var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
// AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed:
Assert.True(md0.MetadataReader.IsAssembly);
Assert.False(diff1.GetMetadata().Reader.IsAssembly);
}
[Fact]
public void SemanticErrors_MethodBody()
{
var source0 = MarkedSource(@"
class C
{
static void E()
{
int x = 1;
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void E()
{
int x = Unknown(2);
System.Console.WriteLine(x);
}
static void G()
{
System.Console.WriteLine(2);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Semantic errors are reported only for the bodies of members being emitted.
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (6,17): error CS0103: The name 'Unknown' does not exist in the current context
// int x = Unknown(2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17));
var diffGood = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffGood.EmitResult.Diagnostics.Verify();
diffGood.VerifyIL(@"C.G", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ret
}
");
}
[Fact]
public void SemanticErrors_Declaration()
{
var source0 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(1);
}
}
");
var source1 = MarkedSource(@"
class C
{
static void G()
{
System.Console.WriteLine(2);
}
}
class Bad : Bad
{
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var g0 = compilation0.GetMember<MethodSymbol>("C.G");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// All declaration errors are reported regardless of what member do we emit.
diff.EmitResult.Diagnostics.Verify(
// (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad'
// class Bad : Bad
Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7));
}
[Fact]
public void ModifyMethod()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_RenameParameter()
{
var source0 =
@"class C
{
static string F(int a) { return a.ToString(); }
}";
var source1 =
@"class C
{
static string F(int x) { return x.ToString(); }
}";
var source2 =
@"class C
{
static string F(int b) { return b.ToString(); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb));
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor");
CheckNames(reader0, reader0.GetParameterDefNames(), "a");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetParameterDefNames(), "x");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(1, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.StandAloneSig));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), "ToString");
CheckNames(readers, reader2.GetParameterDefNames(), "b");
CheckEncLogDefinitions(reader2,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(1, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(3, TableIndex.StandAloneSig));
}
[CompilerTrait(CompilerFeature.Tuples)]
[Fact]
public void ModifyMethod_WithTuples()
{
var source0 =
@"class C
{
static void Main() { }
static (int, int) F() { return (1, 2); }
}";
var source1 =
@"class C
{
static void Main() { }
static (int, int) F() { return (2, 3); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_WithAttributes1()
{
using var _ = new EditAndContinueTest(options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20)
.AddGeneration(
source: @"
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}",
validator: g =>
{
g.VerifyTypeDefNames("<Module>", "C");
g.VerifyMethodDefNames("Main", "F", ".ctor");
g.VerifyMemberRefNames(/*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
g.VerifyTableSize(TableIndex.CustomAttribute, 4);
})
.AddGeneration(
source: @"
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}",
edits: new[] { Edit(SemanticEditKind.Update, c => c.GetMember("C.F")) },
validator: g =>
{
g.VerifyTypeDefNames();
g.VerifyMethodDefNames("F");
g.VerifyMemberRefNames( /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
g.VerifyTableSize(TableIndex.CustomAttribute, 1);
g.VerifyEncLog(new[]
{
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 4, so updating existing CustomAttribute
});
g.VerifyEncMap(new[]
{
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef)
});
})
// Add attribute to method, and to class
.AddGeneration(
source: @"
[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}",
edits: new[] {
Edit(SemanticEditKind.Update, c => c.GetMember("C")),
Edit(SemanticEditKind.Update, c => c.GetMember("C.F"))
},
validator: g =>
{
g.VerifyTypeDefNames("C");
g.VerifyMethodDefNames("F");
g.VerifyMemberRefNames( /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
g.VerifyTableSize(TableIndex.CustomAttribute, 3);
g.VerifyEncLog(new[] {
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 6 adding a new CustomAttribute
});
g.VerifyEncMap(new[] {
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(2, TableIndex.TypeDef),
Handle(2, TableIndex.MethodDef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(10, TableIndex.MemberRef),
Handle(11, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef)
});
})
// Add attribute before existing attributes
.AddGeneration(
source: @"
[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")]
static string F() { return string.Empty; }
}",
edits: new[] {
Edit(SemanticEditKind.Update, c => c.GetMember("C.F"))
},
validator: g =>
{
g.VerifyTypeDefNames();
g.VerifyMethodDefNames("F");
g.VerifyMemberRefNames( /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty");
g.VerifyTableSize(TableIndex.CustomAttribute, 3);
g.VerifyEncLog(new[] {
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default) // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted
});
g.VerifyEncMap(new[] {
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(19, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(12, TableIndex.MemberRef),
Handle(13, TableIndex.MemberRef),
Handle(14, TableIndex.MemberRef),
Handle(15, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef)
});
})
.Verify();
}
[Fact]
public void ModifyMethod_WithAttributes2()
{
var source0 =
@"[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A"")]
static string A() { return null; }
}
";
var source1 =
@"
[System.ComponentModel.Browsable(false)]
class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")]
static string F() { return null; }
}
[System.ComponentModel.Browsable(false)]
class D
{
[System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")]
static string A() { return null; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0_1 = compilation0.GetMember<MethodSymbol>("C.F");
var method0_2 = compilation0.GetMember<MethodSymbol>("D.A");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1_1 = compilation1.GetMember<MethodSymbol>("C.F");
var method1_2 = compilation1.GetMember<MethodSymbol>("D.A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1),
SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "A");
CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes1()
{
var source0 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F() { return string.Empty; }
}";
var source2 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader2,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_DeleteAttributes2()
{
var source0 =
@"class C
{
static void Main() { }
static string F() { return null; }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var source2 = source0; // Remove the attribute we just added
var source3 = source1; // Add the attribute back again
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation1.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetMemberRefNames());
CheckAttributes(reader2,
new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute
CheckEncMap(reader2,
Handle(9, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(3, TableIndex.AssemblyRef));
var method3 = compilation3.GetMember<MethodSymbol>("C.F");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
CheckAttributes(reader3,
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)));
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row
CheckEncMap(reader3,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(4, TableIndex.StandAloneSig),
Handle(4, TableIndex.AssemblyRef));
}
[WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")]
[Fact]
public void PartialMethod()
{
var source =
@"partial class C
{
static partial void M1();
static partial void M2();
static partial void M3();
static partial void M1() { }
static partial void M2() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor");
var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart;
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
var methods = diff1.TestData.GetMethodsByName();
Assert.Equal(1, methods.Count);
Assert.True(methods.ContainsKey("C.M2()"));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "M2");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Method_WithAttributes_Add()
{
var source0 =
@"class C
{
static void Main() { }
}";
var source1 =
@"class C
{
static void Main() { }
[System.ComponentModel.Description(""The F method"")]
static string F() { return string.Empty; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyMethod_ParameterAttributes()
{
var source0 =
@"class C
{
static void Main() { }
static string F(string input, int a) { return input; }
}";
var source1 =
@"class C
{
static void Main() { }
static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; }
static void G(string input) { }
}";
var source2 =
@"class C
{
static void Main() { }
static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; }
static void G([System.ComponentModel.Description(""input"")]string input) { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var methodF0 = compilation0.GetMember<MethodSymbol>("C.F");
var methodF1 = compilation1.GetMember<MethodSymbol>("C.F");
var methodG1 = compilation1.GetMember<MethodSymbol>("C.G");
var methodG2 = compilation2.GetMember<MethodSymbol>("C.G");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor");
CheckNames(reader0, reader0.GetParameterDefNames(), "input", "a");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, methodF0, methodF1),
SemanticEdit.Create(SemanticEditKind.Insert, null, methodG1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F", "G");
CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor");
CheckNames(readers, reader1.GetParameterDefNames(), "input", "a", "input");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.Param), Handle(5, TableIndex.MemberRef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), // New method, G
Row(1, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param
Row(2, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), // New param on method, G
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Support for the above
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param),
Handle(5, TableIndex.MemberRef),
Handle(4, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, methodG1, methodG2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "G");
CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor");
CheckNames(readers, reader2.GetParameterDefNames(), "input");
CheckAttributes(reader2,
new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef)));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param, from the first delta
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(4, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(6, TableIndex.MemberRef),
Handle(5, TableIndex.CustomAttribute),
Handle(3, TableIndex.AssemblyRef));
}
[Fact]
public void ModifyDelegateInvokeMethod_AddAttributes()
{
var source0 = @"
class A : System.Attribute { }
delegate void D(int x);
";
var source1 = @"
class A : System.Attribute { }
delegate void D([A]int x);
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var invoke0 = compilation0.GetMember<MethodSymbol>("D.Invoke");
var beginInvoke0 = compilation0.GetMember<MethodSymbol>("D.BeginInvoke");
var invoke1 = compilation1.GetMember<MethodSymbol>("D.Invoke");
var beginInvoke1 = compilation1.GetMember<MethodSymbol>("D.BeginInvoke");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, invoke0, invoke1),
SemanticEdit.Create(SemanticEditKind.Update, beginInvoke0, beginInvoke1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetMethodDefNames(), "Invoke", "BeginInvoke");
CheckNames(readers, reader1.GetParameterDefNames(), "x", "x", "callback", "object");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(4, TableIndex.Param), Handle(1, TableIndex.MethodDef)));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Updating existing parameter defs
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Adding new custom attribute rows
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(10, TableIndex.TypeRef),
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param),
Handle(6, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(2, TableIndex.AssemblyRef));
}
/// <summary>
/// Add a method that requires entries in the ParameterDefs table.
/// Specifically, normal parameters or return types with attributes.
/// Add the method in the first edit, then modify the method in the second.
/// </summary>
[Fact]
public void Method_WithParameterAttributes_AddThenUpdate()
{
var source0 =
@"class A : System.Attribute { }
class C
{
}";
var source1 =
@"class A : System.Attribute { }
class C
{
[return:A]static object F(int arg = 1) => arg;
}";
var source2 =
@"class A : System.Attribute { }
class C
{
[return:A]static object F(int arg = 1) => null;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "F");
CheckNames(readers, reader1.GetParameterDefNames(), "", "arg");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(1, TableIndex.Constant, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(1, TableIndex.Constant),
Handle(4, TableIndex.CustomAttribute));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetMethodDefNames(), "F");
CheckNames(readers, reader2.GetParameterDefNames(), "", "arg");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C");
CheckNames(readers, diff2.EmitResult.UpdatedMethods, "F");
CheckEncLogDefinitions(reader2,
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), // C.F2
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.Constant, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(2, TableIndex.Constant),
Handle(4, TableIndex.CustomAttribute));
}
[Fact]
public void Method_WithEmbeddedAttributes_AndThenUpdate()
{
var source0 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
class C
{
static void Main() { }
}
}
";
var source1 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main()
{
Id(in G());
}
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 1 }[0];
}
}";
var source2 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
}
}";
var source3 =
@"
namespace System.Runtime.CompilerServices { class X { } }
namespace N
{
struct C
{
static void Main() { Id(in G()); }
static ref readonly int Id(in int x) => ref x;
static ref readonly int G() => ref new int[1] { 2 }[0];
static void H(string? s) {}
readonly ref readonly string?[]? F() => throw null;
}
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main");
var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id");
var g1 = compilation1.GetMember<MethodSymbol>("N.C.G");
var g2 = compilation2.GetMember<MethodSymbol>("N.C.G");
var h2 = compilation2.GetMember<MethodSymbol>("N.C.H");
var f3 = compilation3.GetMember<MethodSymbol>("N.C.F");
// Verify full metadata contains expected rows.
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, id1),
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute}");
diff1.VerifyIL("N.C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: nop
IL_0001: call ""ref readonly int N.C.G()""
IL_0006: call ""ref readonly int N.C.Id(in int)""
IL_000b: pop
IL_000c: ret
}
");
diff1.VerifyIL("N.C.Id", @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
");
diff1.VerifyIL("N.C.G", @"
{
// Code size 17 (0x11)
.maxstack 4
IL_0000: ldc.i4.1
IL_0001: newarr ""int""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: stelem.i4
IL_000a: ldc.i4.0
IL_000b: ldelema ""int""
IL_0010: ret
}
");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader0 = md0.MetadataReader;
var reader1 = md1.Reader;
var readers = new List<MetadataReader>() { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute");
CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, g1, g2),
SemanticEdit.Create(SemanticEditKind.Insert, null, h2)));
// synthesized member for nullable annotations added:
diff2.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
// note: NullableAttribute has 2 ctors, NullableContextAttribute has one
CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute");
CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H");
// two new TypeDefs emitted for the attributes:
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute
Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(11, TableIndex.TypeRef),
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(14, TableIndex.TypeRef),
Handle(15, TableIndex.TypeRef),
Handle(16, TableIndex.TypeRef),
Handle(17, TableIndex.TypeRef),
Handle(18, TableIndex.TypeRef),
Handle(6, TableIndex.TypeDef),
Handle(7, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(2, TableIndex.Field),
Handle(7, TableIndex.MethodDef),
Handle(8, TableIndex.MethodDef),
Handle(9, TableIndex.MethodDef),
Handle(10, TableIndex.MethodDef),
Handle(11, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(9, TableIndex.MemberRef),
Handle(6, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(12, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(3, TableIndex.AssemblyRef));
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3)));
// no change in synthesized members:
diff3.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
// no new type defs:
CheckNames(readers, reader3.GetTypeDefFullNames());
CheckNames(readers, reader3.GetMethodDefNames(), "F");
CheckEncLog(reader3,
Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void Field_Add()
{
var source0 =
@"class C
{
string F = ""F"";
}";
var source1 =
@"class C
{
string F = ""F"";
string G = ""G"";
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetFieldDefNames(), "F");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var method1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "G");
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Property_Accessor_Update()
{
var source0 =
@"class C
{
object P { get { return 1; } }
}";
var source1 =
@"class C
{
object P { get { return 2; } }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P");
var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetPropertyDefNames(), "P");
CheckNames(readers, reader1.GetMethodDefNames(), "get_P");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(8, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Property_Add()
{
var source0 = @"
class C
{
}
";
var source1 = @"
class C
{
object R { get { return null; } }
}
";
var source2 = @"
class C
{
object R { get { return null; } }
object Q { get; set; }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var r1 = compilation1.GetMember<PropertySymbol>("C.R");
var q2 = compilation2.GetMember<PropertySymbol>("C.Q");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetPropertyDefNames(), "R");
CheckNames(readers, reader1.GetMethodDefNames(), "get_R");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.MethodDef),
Handle(1, TableIndex.StandAloneSig),
Handle(1, TableIndex.PropertyMap),
Handle(1, TableIndex.Property),
Handle(1, TableIndex.MethodSemantics));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, q2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField");
CheckNames(readers, reader2.GetPropertyDefNames(), "Q");
CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(1, TableIndex.Field),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(2, TableIndex.Property),
Handle(2, TableIndex.MethodSemantics),
Handle(3, TableIndex.MethodSemantics));
}
[Fact]
public void Event_Add()
{
var source0 = @"
class C
{
}";
var source1 = @"
class C
{
event System.Action E;
}";
var source2 = @"
class C
{
event System.Action E;
event System.Action G;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var e1 = compilation1.GetMember<EventSymbol>("C.E");
var g2 = compilation2.GetMember<EventSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
// gen 1
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, e1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetFieldDefNames(), "E");
CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(1, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(1, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute),
Handle(6, TableIndex.CustomAttribute),
Handle(7, TableIndex.CustomAttribute),
Handle(1, TableIndex.StandAloneSig),
Handle(1, TableIndex.EventMap),
Handle(1, TableIndex.Event),
Handle(1, TableIndex.MethodSemantics),
Handle(2, TableIndex.MethodSemantics));
// gen 2
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "G");
CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G");
CheckNames(readers, diff1.EmitResult.UpdatedMethods);
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(2, TableIndex.Field, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.Field),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(4, TableIndex.Param),
Handle(8, TableIndex.CustomAttribute),
Handle(9, TableIndex.CustomAttribute),
Handle(10, TableIndex.CustomAttribute),
Handle(11, TableIndex.CustomAttribute),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(3, TableIndex.MethodSemantics),
Handle(4, TableIndex.MethodSemantics));
}
[WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")]
[Fact]
public void EventFields()
{
var source0 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 1;
}
}
");
var source1 = MarkedSource(@"
using System;
class C
{
static event EventHandler handler;
static int F()
{
handler(null, null);
return 10;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 21 (0x15)
.maxstack 3
.locals init (int V_0)
IL_0000: nop
IL_0001: ldsfld ""System.EventHandler C.handler""
IL_0006: ldnull
IL_0007: ldnull
IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)""
IL_000d: nop
IL_000e: ldc.i4.s 10
IL_0010: stloc.0
IL_0011: br.s IL_0013
IL_0013: ldloc.0
IL_0014: ret
}
");
}
[Fact]
public void UpdateType_AddAttributes()
{
var source0 = @"
class C
{
}";
var source1 = @"
[System.ComponentModel.Description(""C"")]
class C
{
}";
var source2 = @"
[System.ComponentModel.Description(""C"")]
[System.ObsoleteAttribute]
class C
{
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
Assert.Equal(3, reader0.CustomAttributes.Count);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C");
Assert.Equal(1, reader1.CustomAttributes.Count);
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C");
Assert.Equal(2, reader2.CustomAttributes.Count);
CheckEncLogDefinitions(reader2,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(2, TableIndex.TypeDef),
Handle(4, TableIndex.CustomAttribute),
Handle(5, TableIndex.CustomAttribute));
}
[Fact]
public void ReplaceType()
{
var source0 = @"
class C
{
void F(int x) {}
}
";
var source1 = @"
class C
{
void F(int x, int y) { }
}";
var source2 = @"
class C
{
void F(int x, int y) { System.Console.WriteLine(1); }
}";
var source3 = @"
[System.Obsolete]
class C
{
void F(int x, int y) { System.Console.WriteLine(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var c3 = compilation3.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
var f3 = c3.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C#1");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(2, TableIndex.Param),
Handle(3, TableIndex.Param));
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, reader2.GetTypeDefNames(), "C#2");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2");
CheckEncLogDefinitions(reader2,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(5, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader2,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param));
// This update is an EnC update - even reloadable types are update in-place
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, c2, c3),
SemanticEdit.Create(SemanticEditKind.Update, f2, f3)));
// Verify delta metadata contains expected rows.
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers = new[] { reader0, reader1, reader2, reader3 };
CheckNames(readers, reader3.GetTypeDefNames(), "C#2");
CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2");
CheckEncLogDefinitions(reader3,
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader3,
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.MethodDef),
Handle(4, TableIndex.Param),
Handle(5, TableIndex.Param),
Handle(4, TableIndex.CustomAttribute));
}
[Fact]
public void EventFields_Attributes()
{
var source0 = MarkedSource(@"
using System;
class C
{
static event EventHandler E;
}
");
var source1 = MarkedSource(@"
using System;
class C
{
[System.Obsolete]
static event EventHandler E;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var event0 = compilation0.GetMember<EventSymbol>("C.E");
var event1 = compilation1.GetMember<EventSymbol>("C.E");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "add_E", "remove_E", ".ctor");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, event0, event1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames());
CheckNames(readers, reader1.GetEventDefNames(), "E");
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(10, TableIndex.MemberRef)));
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.Event, EditAndContinueOperation.Default),
Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(8, TableIndex.CustomAttribute),
Handle(1, TableIndex.Event),
Handle(3, TableIndex.MethodSemantics),
Handle(4, TableIndex.MethodSemantics));
}
[Fact]
public void ReplaceType_AsyncLambda()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
void F(int x) { Task.Run(async() => {}); }
}
";
var source1 = @"
using System.Threading.Tasks;
class C
{
void F(bool y) { Task.Run(async() => {}); }
}
";
var source2 = @"
using System.Threading.Tasks;
class C
{
void F(uint z) { Task.Run(async() => {}); }
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c", "<<F>b__0_0>d");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
// A new nested type <>c is generated in C#1
CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "<>c", "<<F>b__0#1_0#1>d");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "<>c", "<<F>b__0#1_0#1>d");
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
// A new nested type <>c is generated in C#2
CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "<>c", "<<F>b__0#2_0#2>d");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "<>c", "<<F>b__0#2_0#2>d");
}
[Fact]
public void ReplaceType_AsyncLambda_InNestedType()
{
var source0 = @"
using System.Threading.Tasks;
class C
{
class D
{
void F(int x) { Task.Run(async() => {}); }
}
}
";
var source1 = @"
using System.Threading.Tasks;
class C
{
class D
{
void F(bool y) { Task.Run(async() => {}); }
}
}
";
var source2 = @"
using System.Threading.Tasks;
class C
{
class D
{
void F(uint z) { Task.Run(async() => {}); }
}
}
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var c0 = compilation0.GetMember<NamedTypeSymbol>("C");
var c1 = compilation1.GetMember<NamedTypeSymbol>("C");
var c2 = compilation2.GetMember<NamedTypeSymbol>("C");
var f2 = c2.GetMember<MethodSymbol>("F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D", "<>c", "<<F>b__0_0>d");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
// A new nested type <>c is generated in C#1
CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "D", "<>c", "<<F>b__0#1_0#1>d");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "D", "<>c", "<<F>b__0#1_0#1>d");
// This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one.
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Replace, null, c2)));
// Verify delta metadata contains expected rows.
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
// A new nested type <>c is generated in C#2
CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "D", "<>c", "<<F>b__0#2_0#2>d");
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "D", "<>c", "<<F>b__0#2_0#2>d");
}
[Fact]
public void AddNestedTypeAndMembers()
{
var source0 =
@"class A
{
class B { }
static object F()
{
return new B();
}
}";
var source1 =
@"class A
{
class B { }
class C
{
class D { }
static object F;
internal static object G()
{
return F;
}
}
static object F()
{
return C.G();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C");
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "C", "D");
CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor");
CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F");
CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D");
Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(5, TableIndex.TypeDef),
Handle(1, TableIndex.Field),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(6, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(3, TableIndex.NestedClass));
}
/// <summary>
/// Nested types should be emitted in the
/// same order as full emit.
/// </summary>
[Fact]
public void AddNestedTypesOrder()
{
var source0 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
}";
var source1 =
@"class A
{
class B1
{
class C1 { }
}
class B2
{
class C2 { }
}
class B3
{
class C3 { }
}
class B4
{
class C4 { }
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2");
Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4");
Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass));
}
[Fact]
public void AddNestedGenericType()
{
var source0 =
@"class A
{
class B<T>
{
}
static object F()
{
return null;
}
}";
var source1 =
@"class A
{
class B<T>
{
internal class C<U>
{
internal object F<V>() where V : T, new()
{
return new C<V>();
}
}
}
static object F()
{
return new B<A>.C<B<object>>().F<A>();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("A.F");
var f1 = compilation1.GetMember<MethodSymbol>("A.F");
var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1");
Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, c1),
SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1");
CheckNames(readers, reader1.GetTypeDefNames(), "C`1");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default),
Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(4, TableIndex.TypeDef),
Handle(1, TableIndex.MethodDef),
Handle(4, TableIndex.MethodDef),
Handle(5, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(6, TableIndex.MemberRef),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(2, TableIndex.StandAloneSig),
Handle(1, TableIndex.TypeSpec),
Handle(2, TableIndex.TypeSpec),
Handle(3, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef),
Handle(2, TableIndex.NestedClass),
Handle(2, TableIndex.GenericParam),
Handle(3, TableIndex.GenericParam),
Handle(4, TableIndex.GenericParam),
Handle(1, TableIndex.MethodSpec),
Handle(1, TableIndex.GenericParamConstraint));
}
[Fact]
[WorkItem(54939, "https://github.com/dotnet/roslyn/issues/54939")]
public void AddNamespace()
{
var source0 =
@"
class C
{
static void Main() { }
}";
var source1 =
@"
namespace N1.N2
{
class D { public static void F() { } }
}
class C
{
static void Main() => N1.N2.D.F();
}";
var source2 =
@"
namespace N1.N2
{
class D { public static void F() { } }
namespace M1.M2
{
class E { public static void G() { } }
}
}
class C
{
static void Main() => N1.N2.M1.M2.E.G();
}";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var main0 = compilation0.GetMember<MethodSymbol>("C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("C.Main");
var main2 = compilation2.GetMember<MethodSymbol>("C.Main");
var d1 = compilation1.GetMember<NamedTypeSymbol>("N1.N2.D");
var e2 = compilation2.GetMember<NamedTypeSymbol>("N1.N2.M1.M2.E");
using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray());
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main0, main1),
SemanticEdit.Create(SemanticEditKind.Insert, null, d1)));
diff1.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N1.N2.D.F()""
IL_0005: nop
IL_0006: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main1, main2),
SemanticEdit.Create(SemanticEditKind.Insert, null, e2)));
diff2.VerifyIL("C.Main", @"
{
// Code size 7 (0x7)
.maxstack 0
IL_0000: call ""void N1.N2.M1.M2.E.G()""
IL_0005: nop
IL_0006: ret
}");
}
[Fact]
public void ModifyExplicitImplementation()
{
var source =
@"interface I
{
void M();
}
class C : I
{
void I.M() { }
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddThenModifyExplicitImplementation()
{
var source0 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
}";
var source1 =
@"interface I
{
void M();
}
class A : I
{
void I.M() { }
}
class B : I
{
public void M() { }
void I.M() { }
}";
var source2 = source1;
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation0.WithSource(source2);
var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetMethodDefNames(), "I.M");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(2, TableIndex.MethodImpl),
Handle(2, TableIndex.AssemblyRef));
var generation1 = diff1.NextGeneration;
var diff2 = compilation2.EmitDifference(
generation1,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
EncValidation.VerifyModuleMvid(2, reader1, reader2);
CheckNames(readers, reader2.GetMethodDefNames(), "I.M");
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader2,
Handle(7, TableIndex.TypeRef),
Handle(6, TableIndex.MethodDef),
Handle(3, TableIndex.AssemblyRef));
}
[WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")]
[Fact]
public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation()
{
var source = @"
interface I
{
void M();
}
class C : I
{
public C()
{
}
void I.M() { }
}
";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
using var block1 = diff1.GetMetadata();
var reader1 = block1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void AddAndModifyInterfaceMembers()
{
var source0 = @"
using System;
interface I
{
}";
var source1 = @"
using System;
interface I
{
static int X = 10;
static event Action Y;
static void M() { }
void N() { }
static int P { get => 1; set { } }
int Q { get => 1; set { } }
static event Action E { add { } remove { } }
event Action F { add { } remove { } }
interface J { }
}";
var source2 = @"
using System;
interface I
{
static int X = 2;
static event Action Y;
static I() { X--; }
static void M() { X++; }
void N() { X++; }
static int P { get => 3; set { X++; } }
int Q { get => 3; set { X++; } }
static event Action E { add { X++; } remove { X++; } }
event Action F { add { X++; } remove { X++; } }
interface J { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var x1 = compilation1.GetMember<FieldSymbol>("I.X");
var y1 = compilation1.GetMember<EventSymbol>("I.Y");
var m1 = compilation1.GetMember<MethodSymbol>("I.M");
var n1 = compilation1.GetMember<MethodSymbol>("I.N");
var p1 = compilation1.GetMember<PropertySymbol>("I.P");
var q1 = compilation1.GetMember<PropertySymbol>("I.Q");
var e1 = compilation1.GetMember<EventSymbol>("I.E");
var f1 = compilation1.GetMember<EventSymbol>("I.F");
var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J");
var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P");
var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P");
var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q");
var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q");
var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E");
var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E");
var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F");
var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F");
var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var x2 = compilation2.GetMember<FieldSymbol>("I.X");
var m2 = compilation2.GetMember<MethodSymbol>("I.M");
var n2 = compilation2.GetMember<MethodSymbol>("I.N");
var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P");
var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P");
var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q");
var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q");
var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E");
var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E");
var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F");
var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F");
var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single();
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, x1),
SemanticEdit.Create(SemanticEditKind.Insert, null, y1),
SemanticEdit.Create(SemanticEditKind.Insert, null, m1),
SemanticEdit.Create(SemanticEditKind.Insert, null, n1),
SemanticEdit.Create(SemanticEditKind.Insert, null, p1),
SemanticEdit.Create(SemanticEditKind.Insert, null, q1),
SemanticEdit.Create(SemanticEditKind.Insert, null, e1),
SemanticEdit.Create(SemanticEditKind.Insert, null, f1),
SemanticEdit.Create(SemanticEditKind.Insert, null, j1),
SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J");
CheckNames(readers, reader1.GetTypeDefNames(), "J");
CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y");
CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, x1, x2),
SemanticEdit.Create(SemanticEditKind.Update, m1, m2),
SemanticEdit.Create(SemanticEditKind.Update, n1, n2),
SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2),
SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2),
SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2),
SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2),
SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2),
SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2),
SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2),
SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2),
SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetFieldDefNames(), "X");
CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor");
Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass));
CheckEncLog(reader2,
Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(3, TableIndex.Event, EditAndContinueOperation.Default),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Property, EditAndContinueOperation.Default),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default));
diff2.VerifyIL(@"
{
// Code size 14 (0xe)
.maxstack 8
IL_0000: nop
IL_0001: ldsfld 0x04000001
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: stsfld 0x04000001
IL_000d: ret
}
{
// Code size 2 (0x2)
.maxstack 8
IL_0000: ldc.i4.3
IL_0001: ret
}
{
// Code size 20 (0x14)
.maxstack 8
IL_0000: ldc.i4.2
IL_0001: stsfld 0x04000001
IL_0006: nop
IL_0007: ldsfld 0x04000001
IL_000c: ldc.i4.1
IL_000d: sub
IL_000e: stsfld 0x04000001
IL_0013: ret
}
");
}
[Fact]
public void AddAttributeReferences()
{
var source0 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static object F1;
[A] static object P1 { get { return null; } }
[B] static event D E1;
}
delegate void D();
";
var source1 =
@"class A : System.Attribute { }
class B : System.Attribute { }
class C
{
[A] static void M1<[B]T>() { }
[B] static void M2<[A]T>() { }
[B] static object F1;
[A] static object F2;
[A] static object P1 { get { return null; } }
[B] static object P2 { get { return null; } }
[B] static event D E1;
[A] static event D E2;
}
delegate void D();
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke");
CheckAttributes(reader0,
new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)));
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2");
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent),
Row(2, TableIndex.Event, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty),
Row(2, TableIndex.Property, EditAndContinueOperation.Default),
Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default),
Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(12, TableIndex.MethodDef),
Handle(13, TableIndex.MethodDef),
Handle(14, TableIndex.MethodDef),
Handle(15, TableIndex.MethodDef),
Handle(8, TableIndex.Param),
Handle(9, TableIndex.Param),
Handle(7, TableIndex.CustomAttribute),
Handle(13, TableIndex.CustomAttribute),
Handle(14, TableIndex.CustomAttribute),
Handle(15, TableIndex.CustomAttribute),
Handle(16, TableIndex.CustomAttribute),
Handle(17, TableIndex.CustomAttribute),
Handle(18, TableIndex.CustomAttribute),
Handle(19, TableIndex.CustomAttribute),
Handle(20, TableIndex.CustomAttribute),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.StandAloneSig),
Handle(2, TableIndex.Event),
Handle(2, TableIndex.Property),
Handle(4, TableIndex.MethodSemantics),
Handle(5, TableIndex.MethodSemantics),
Handle(6, TableIndex.MethodSemantics),
Handle(2, TableIndex.GenericParam));
CheckAttributes(reader1,
new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)),
new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)),
new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)));
}
/// <summary>
/// [assembly: ...] and [module: ...] attributes should
/// not be included in delta metadata.
/// </summary>
[Fact]
public void AssemblyAndModuleAttributeReferences()
{
var source0 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
}";
var source1 =
@"[assembly: System.CLSCompliantAttribute(true)]
[module: System.CLSCompliantAttribute(true)]
class C
{
static void M()
{
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M"))));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var readers = new[] { reader0, md1.Reader };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, md1.Reader.GetTypeDefNames());
CheckNames(readers, md1.Reader.GetMethodDefNames(), "M");
CheckEncLog(md1.Reader,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M
CheckEncMap(md1.Reader,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void OtherReferences()
{
var source0 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
}
}";
var source1 =
@"delegate void D();
class C
{
object F;
object P { get { return null; } }
event D E;
void M()
{
object o;
o = typeof(D);
o = F;
o = P;
E += null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C");
CheckNames(reader0, reader0.GetEventDefNames(), "E");
CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor");
CheckNames(reader0, reader0.GetPropertyDefNames(), "P");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
// Emit delta metadata.
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetEventDefNames());
CheckNames(readers, reader1.GetFieldDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "M");
CheckNames(readers, reader1.GetPropertyDefNames());
}
[Fact]
public void ArrayInitializer()
{
var source0 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3 };
}
}");
var source1 = WithWindowsLineBreaks(@"
class C
{
static void M()
{
int[] a = new[] { 1, 2, 3, 4 };
}
}");
var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll);
var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs"));
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M"))));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(12, TableIndex.TypeRef),
Handle(13, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL(
@"{
// Code size 25 (0x19)
.maxstack 4
IL_0000: nop
IL_0001: ldc.i4.4
IL_0002: newarr 0x0100000D
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.4
IL_0016: stelem.i4
IL_0017: stloc.0
IL_0018: ret
}");
diff1.VerifyPdb(new[] { 0x06000001 },
@"<symbols>
<files>
<file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" />
</files>
<methods>
<method token=""0x6000001"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" />
<entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x19"">
<local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void PInvokeModuleRefAndImplMap()
{
var source0 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
}";
var source1 =
@"using System.Runtime.InteropServices;
class C
{
[DllImport(""msvcrt.dll"")]
public static extern int getchar();
[DllImport(""msvcrt.dll"")]
public static extern int puts(string s);
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default));
CheckEncMapDefinitions(reader1,
Handle(3, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(2, TableIndex.ImplMap));
}
/// <summary>
/// ClassLayout and FieldLayout tables.
/// </summary>
[Fact]
public void ClassAndFieldLayout()
{
var source0 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}";
var source1 =
@"using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit, Pack=2)]
class A
{
[FieldOffset(0)]internal byte F;
[FieldOffset(2)]internal byte G;
}
[StructLayout(LayoutKind.Explicit, Pack=4)]
class B
{
[FieldOffset(0)]internal short F;
[FieldOffset(4)]internal short G;
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B"))));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(3, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(4, TableIndex.Field, EditAndContinueOperation.Default),
Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default),
Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default),
Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(3, TableIndex.TypeDef),
Handle(3, TableIndex.Field),
Handle(4, TableIndex.Field),
Handle(2, TableIndex.MethodDef),
Handle(5, TableIndex.MemberRef),
Handle(2, TableIndex.ClassLayout),
Handle(3, TableIndex.FieldLayout),
Handle(4, TableIndex.FieldLayout),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void NamespacesAndOverloads()
{
var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source:
@"class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
}
}
}");
var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2");
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var compilation1 = compilation0.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
}
}
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2])));
diff1.VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
}");
var compilation2 = compilation1.WithSource(@"
class C { }
namespace N
{
class C { }
}
namespace M
{
class C
{
void M1(N.C o) { }
void M1(M.C o) { }
void M1(global::C o) { }
void M2(N.C a, M.C b, global::C c)
{
M1(a);
M1(b);
M1(c);
}
}
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"),
compilation2.GetMember<MethodSymbol>("M.C.M2"))));
diff2.VerifyIL(
@"{
// Code size 26 (0x1a)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.1
IL_0003: call 0x06000002
IL_0008: nop
IL_0009: ldarg.0
IL_000a: ldarg.2
IL_000b: call 0x06000003
IL_0010: nop
IL_0011: ldarg.0
IL_0012: ldarg.3
IL_0013: call 0x06000007
IL_0018: nop
IL_0019: ret
}");
}
[Fact]
public void TypesAndOverloads()
{
const string source =
@"using System;
struct A<T>
{
internal class B<U> { }
}
class B { }
class C
{
static void M(A<B>.B<object> a)
{
M(a);
M((A<B>.B<B>)null);
}
static void M(A<B>.B<B> a)
{
M(a);
M((A<B>.B<object>)null);
}
static void M(A<B> a)
{
M(a);
M((A<B>?)a);
}
static void M(Nullable<A<B>> a)
{
M(a);
M(a.Value);
}
unsafe static void M(int* p)
{
M(p);
M((byte*)p);
}
unsafe static void M(byte* p)
{
M(p);
M((int*)p);
}
static void M(B[][] b)
{
M(b);
M((object[][])b);
}
static void M(object[][] b)
{
M(b);
M((B[][])b);
}
static void M(A<B[]>.B<object> b)
{
M(b);
M((A<B[, ,]>.B<object>)null);
}
static void M(A<B[, ,]>.B<object> b)
{
M(b);
M((A<B[]>.B<object>)null);
}
static void M(dynamic d)
{
M(d);
M((dynamic[])d);
}
static void M(dynamic[] d)
{
M(d);
M((dynamic)d);
}
static void M<T>(A<int>.B<T> t) where T : B
{
M(t);
M((A<double>.B<int>)null);
}
static void M<T>(A<double>.B<T> t) where T : struct
{
M(t);
M((A<int>.B<B>)null);
}
}";
var options = TestOptions.UnsafeDebugDll;
var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef });
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var n = compilation0.GetMembers("C.M").Length;
Assert.Equal(14, n);
//static void M(A<B>.B<object> a)
//{
// M(a);
// M((A<B>.B<B>)null);
//}
var compilation1 = compilation0.WithSource(source);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0])));
diff1.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B>.B<B> a)
//{
// M(a);
// M((A<B>.B<object>)null);
//}
var compilation2 = compilation1.WithSource(source);
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1])));
diff2.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000003
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000002
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B> a)
//{
// M(a);
// M((A<B>?)a);
//}
var compilation3 = compilation2.WithSource(source);
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2])));
diff3.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000004
IL_0007: nop
IL_0008: ldarg.0
IL_0009: newobj 0x0A000016
IL_000e: call 0x06000005
IL_0013: nop
IL_0014: ret
}");
//static void M(Nullable<A<B>> a)
//{
// M(a);
// M(a.Value);
//}
var compilation4 = compilation3.WithSource(source);
var diff4 = compilation4.EmitDifference(
diff3.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3])));
diff4.VerifyIL(
@"{
// Code size 22 (0x16)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000005
IL_0007: nop
IL_0008: ldarga.s V_0
IL_000a: call 0x0A000017
IL_000f: call 0x06000004
IL_0014: nop
IL_0015: ret
}");
//unsafe static void M(int* p)
//{
// M(p);
// M((byte*)p);
//}
var compilation5 = compilation4.WithSource(source);
var diff5 = compilation5.EmitDifference(
diff4.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4])));
diff5.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000006
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000007
IL_000e: nop
IL_000f: ret
}");
//unsafe static void M(byte* p)
//{
// M(p);
// M((int*)p);
//}
var compilation6 = compilation5.WithSource(source);
var diff6 = compilation6.EmitDifference(
diff5.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5])));
diff6.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000007
IL_0007: nop
IL_0008: ldarg.0
IL_0009: call 0x06000006
IL_000e: nop
IL_000f: ret
}");
//static void M(B[][] b)
//{
// M(b);
// M((object[][])b);
//}
var compilation7 = compilation6.WithSource(source);
var diff7 = compilation7.EmitDifference(
diff6.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6])));
diff7.VerifyIL(
@"{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000008
IL_0007: nop
IL_0008: ldarg.0
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: call 0x06000009
IL_0010: nop
IL_0011: ret
}");
//static void M(object[][] b)
//{
// M(b);
// M((B[][])b);
//}
var compilation8 = compilation7.WithSource(source);
var diff8 = compilation8.EmitDifference(
diff7.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7])));
diff8.VerifyIL(
@"{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000009
IL_0007: nop
IL_0008: ldarg.0
IL_0009: castclass 0x1B00000A
IL_000e: call 0x06000008
IL_0013: nop
IL_0014: ret
}");
//static void M(A<B[]>.B<object> b)
//{
// M(b);
// M((A<B[,,]>.B<object>)null);
//}
var compilation9 = compilation8.WithSource(source);
var diff9 = compilation9.EmitDifference(
diff8.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8])));
diff9.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000A
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000B
IL_000e: nop
IL_000f: ret
}");
//static void M(A<B[,,]>.B<object> b)
//{
// M(b);
// M((A<B[]>.B<object>)null);
//}
var compilation10 = compilation9.WithSource(source);
var diff10 = compilation10.EmitDifference(
diff9.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9])));
diff10.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x0600000B
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x0600000A
IL_000e: nop
IL_000f: ret
}");
// TODO: dynamic
#if false
//static void M(dynamic d)
//{
// M(d);
// M((dynamic[])d);
//}
previousMethod = compilation.GetMembers("C.M")[10];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
//static void M(dynamic[] d)
//{
// M(d);
// M((dynamic)d);
//}
previousMethod = compilation.GetMembers("C.M")[11];
compilation = compilation0.WithSource(source);
generation = compilation.EmitDifference(
generation,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])),
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x06000002
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x06000003
IL_000e: nop
IL_000f: ret
}");
#endif
//static void M<T>(A<int>.B<T> t) where T : B
//{
// M(t);
// M((A<double>.B<int>)null);
//}
var compilation11 = compilation10.WithSource(source);
var diff11 = compilation11.EmitDifference(
diff10.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12])));
diff11.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000005
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000006
IL_000e: nop
IL_000f: ret
}");
//static void M<T>(A<double>.B<T> t) where T : struct
//{
// M(t);
// M((A<int>.B<B>)null);
//}
var compilation12 = compilation11.WithSource(source);
var diff12 = compilation12.EmitDifference(
diff11.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13])));
diff12.VerifyIL(
@"{
// Code size 16 (0x10)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call 0x2B000007
IL_0007: nop
IL_0008: ldnull
IL_0009: call 0x2B000008
IL_000e: nop
IL_000f: ret
}");
}
[Fact]
public void Struct_ImplementSynthesizedConstructor()
{
var source0 =
@"
struct S
{
int a = 1;
int b;
}
";
var source1 =
@"
struct S
{
int a = 1;
int b;
public S()
{
b = 2;
}
}
";
var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1);
var ctor0 = compilation0.GetMember<MethodSymbol>("S..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("S..ctor");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
// Verify full metadata contains expected rows.
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "S");
CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), ".ctor");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(6, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(2, TableIndex.AssemblyRef));
}
/// <summary>
/// Types should be retained in deleted locals
/// for correct alignment of remaining locals.
/// </summary>
[Fact]
public void DeletedValueTypeLocal()
{
var source0 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var x = new S1(1, 2);
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var source1 =
@"struct S1
{
internal S1(int a, int b) { A = a; B = b; }
internal int A;
internal int B;
}
struct S2
{
internal S2(int c) { C = c; }
internal int C;
}
class C
{
static void Main()
{
var y = new S2(3);
System.Console.WriteLine(y.C);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.Main");
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
testData0.GetMethodData("C.Main").VerifyIL(
@"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (S1 V_0, //x
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: call ""S1..ctor(int, int)""
IL_000a: ldloca.s V_1
IL_000c: ldc.i4.3
IL_000d: call ""S2..ctor(int)""
IL_0012: ldloc.1
IL_0013: ldfld ""int S2.C""
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: nop
IL_001e: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main",
@"{
// Code size 22 (0x16)
.maxstack 2
.locals init ([unchanged] V_0,
S2 V_1) //y
IL_0000: nop
IL_0001: ldloca.s V_1
IL_0003: ldc.i4.3
IL_0004: call ""S2..ctor(int)""
IL_0009: ldloc.1
IL_000a: ldfld ""int S2.C""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}");
}
/// <summary>
/// Instance and static constructors synthesized for
/// PrivateImplementationDetails should not be
/// generated for delta.
/// </summary>
[Fact]
public void PrivateImplementationDetails()
{
var source =
@"class C
{
static int[] F = new int[] { 1, 2, 3 };
int[] G = new int[] { 4, 5, 6 };
int M(int index)
{
return F[index] + G[index];
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var reader0 = md0.MetadataReader;
var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames());
Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal)));
}
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 22 (0x16)
.maxstack 3
.locals init ([int] V_0,
int V_1)
IL_0000: nop
IL_0001: ldsfld ""int[] C.F""
IL_0006: ldarg.1
IL_0007: ldelem.i4
IL_0008: ldarg.0
IL_0009: ldfld ""int[] C.G""
IL_000e: ldarg.1
IL_000f: ldelem.i4
IL_0010: add
IL_0011: stloc.1
IL_0012: br.s IL_0014
IL_0014: ldloc.1
IL_0015: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromMetadata()
{
var source0 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[0]);
}
}";
var source1 =
@"class C
{
static void M()
{
int[] a = { 1, 2, 3 };
System.Console.WriteLine(a[1]);
}
}";
var source2 =
@"class C
{
static void M()
{
int[] a = { 4, 5, 6, 7, 8, 9, 10 };
System.Console.WriteLine(a[1]);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE"));
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
methodData0.VerifyIL(
@" {
// Code size 29 (0x1d)
.maxstack 3
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D""
IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: ldc.i4.0
IL_0015: ldelem.i4
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: nop
IL_001c: ret
}
");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"{
// Code size 30 (0x1e)
.maxstack 4
.locals init (int[] V_0) //a
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldc.i4.1
IL_0016: ldelem.i4
IL_0017: call ""void System.Console.WriteLine(int)""
IL_001c: nop
IL_001d: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 48 (0x30)
.maxstack 4
.locals init ([unchanged] V_0,
int[] V_1) //a
IL_0000: nop
IL_0001: ldc.i4.7
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.4
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.5
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.6
IL_0012: stelem.i4
IL_0013: dup
IL_0014: ldc.i4.3
IL_0015: ldc.i4.7
IL_0016: stelem.i4
IL_0017: dup
IL_0018: ldc.i4.4
IL_0019: ldc.i4.8
IL_001a: stelem.i4
IL_001b: dup
IL_001c: ldc.i4.5
IL_001d: ldc.i4.s 9
IL_001f: stelem.i4
IL_0020: dup
IL_0021: ldc.i4.6
IL_0022: ldc.i4.s 10
IL_0024: stelem.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: ldelem.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ret
}");
}
[WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")]
[WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")]
[Fact]
public void PrivateImplementationDetails_ArrayInitializer_FromSource()
{
// PrivateImplementationDetails not needed initially.
var source0 =
@"class C
{
static object F1() { return null; }
static object F2() { return null; }
static object F3() { return null; }
static object F4() { return null; }
}";
var source1 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return null; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var source2 =
@"class C
{
static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; }
static object F2() { return new[] { 4, 5, 6 }; }
static object F3() { return new[] { 13, 14, 15 }; }
static object F4() { return new[] { 7, 8, 9 }; }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")),
SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4"))));
diff1.VerifyIL("C.F1",
@"{
// Code size 24 (0x18)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: stloc.0
IL_0014: br.s IL_0016
IL_0016: ldloc.0
IL_0017: ret
}");
diff1.VerifyIL("C.F4",
@"{
// Code size 25 (0x19)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.7
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.8
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.s 9
IL_0013: stelem.i4
IL_0014: stloc.0
IL_0015: br.s IL_0017
IL_0017: ldloc.0
IL_0018: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")),
SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3"))));
diff2.VerifyIL("C.F1",
@"{
// Code size 49 (0x31)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: dup
IL_0010: ldc.i4.2
IL_0011: ldc.i4.3
IL_0012: stelem.i4
IL_0013: dup
IL_0014: brtrue.s IL_002c
IL_0016: pop
IL_0017: ldc.i4.3
IL_0018: newarr ""int""
IL_001d: dup
IL_001e: ldc.i4.0
IL_001f: ldc.i4.s 10
IL_0021: stelem.i4
IL_0022: dup
IL_0023: ldc.i4.1
IL_0024: ldc.i4.s 11
IL_0026: stelem.i4
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: ldc.i4.s 12
IL_002b: stelem.i4
IL_002c: stloc.0
IL_002d: br.s IL_002f
IL_002f: ldloc.0
IL_0030: ret
}");
diff2.VerifyIL("C.F3",
@"{
// Code size 27 (0x1b)
.maxstack 4
.locals init (object V_0)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.s 13
IL_000b: stelem.i4
IL_000c: dup
IL_000d: ldc.i4.1
IL_000e: ldc.i4.s 14
IL_0010: stelem.i4
IL_0011: dup
IL_0012: ldc.i4.2
IL_0013: ldc.i4.s 15
IL_0015: stelem.i4
IL_0016: stloc.0
IL_0017: br.s IL_0019
IL_0019: ldloc.0
IL_001a: ret
}");
}
/// <summary>
/// Should not generate method for string switch since
/// the CLR only allows adding private members.
/// </summary>
[WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")]
[Fact]
public void PrivateImplementationDetails_ComputeStringHash()
{
var source =
@"class C
{
static int F(string s)
{
switch (s)
{
case ""1"": return 1;
case ""2"": return 2;
case ""3"": return 3;
case ""4"": return 4;
case ""5"": return 5;
case ""6"": return 6;
case ""7"": return 7;
default: return 0;
}
}
}";
const string ComputeStringHashName = "ComputeStringHash";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.F");
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
// Should have generated call to ComputeStringHash and
// added the method to <PrivateImplementationDetails>.
var actualIL0 = methodData0.GetMethodIL();
Assert.True(actualIL0.Contains(ComputeStringHashName));
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
// Should not have generated call to ComputeStringHash nor
// added the method to <PrivateImplementationDetails>.
var actualIL1 = diff1.GetMethodIL("C.F");
Assert.False(actualIL1.Contains(ComputeStringHashName));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetMethodDefNames(), "F");
}
/// <summary>
/// Unique ids should not conflict with ids
/// from previous generation.
/// </summary>
[WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")]
public void UniqueIds()
{
var source0 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
System.Func<int> g = () => 2;
return (b ? f : g)();
}
}";
var source1 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> f = () => 1;
return f();
}
}";
var source2 =
@"class C
{
int F()
{
System.Func<int> f = () => 3;
return f();
}
static int F(bool b)
{
System.Func<int> g = () => 2;
return g();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1])));
diff1.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //f
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__5()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1])));
diff2.VerifyIL("C.F",
@"{
// Code size 40 (0x28)
.maxstack 2
.locals init (System.Func<int> V_0, //g
int V_1)
IL_0000: nop
IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_0006: dup
IL_0007: brtrue.s IL_001c
IL_0009: pop
IL_000a: ldnull
IL_000b: ldftn ""int C.<F>b__7()""
IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0016: dup
IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8""
IL_001c: stloc.0
IL_001d: ldloc.0
IL_001e: callvirt ""int System.Func<int>.Invoke()""
IL_0023: stloc.1
IL_0024: br.s IL_0026
IL_0026: ldloc.1
IL_0027: ret
}");
}
/// <summary>
/// Avoid adding references from method bodies
/// other than the changed methods.
/// </summary>
[Fact]
public void ReferencesInIL()
{
var source0 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.WriteLine(2); }
}";
var source1 =
@"class C
{
static void F() { System.Console.WriteLine(1); }
static void G() { System.Console.Write(2); }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.G");
var method1 = compilation1.GetMember<MethodSymbol>("C.G");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(
SemanticEditKind.Update,
method0,
method1,
GetEquivalentNodesMap(method1, method0),
preserveLocalVariables: true)));
// "Write" should be included in string table, but "WriteLine" should not.
Assert.True(diff1.MetadataDelta.IsIncluded("Write"));
Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine"));
}
/// <summary>
/// Local slots must be preserved based on signature.
/// </summary>
[Fact]
public void PreserveLocalSlots()
{
var source0 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
A<B> y = F();
object z = F();
M(x);
M(y);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" };
var source1 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
B z = F();
A<B> y = F();
object w = F();
M(w);
M(y);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source2 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object a = F();
object b = F();
M(a);
M(b);
}
}";
var source3 =
@"class A<T> { }
class B : A<B>
{
static B F()
{
return null;
}
static void M(object o)
{
object x = F();
B z = F();
M(x);
M(z);
}
static void N()
{
object c = F();
object b = F();
M(c);
M(b);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var method0 = compilation0.GetMember<MethodSymbol>("B.M");
var methodN = compilation0.GetMember<MethodSymbol>("B.N");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo());
#region Gen1
var method1 = compilation1.GetMember<MethodSymbol>("B.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL(
@"{
// Code size 36 (0x24)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.3
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: call 0x06000002
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: call 0x06000003
IL_001b: nop
IL_001c: ldloc.1
IL_001d: call 0x06000003
IL_0022: nop
IL_0023: ret
}");
diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" />
<entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" />
<entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" />
<entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" />
<entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x24"">
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
<local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen2
var method2 = compilation2.GetMember<MethodSymbol>("B.M");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL(
@"{
// Code size 30 (0x1e)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.s V_5
IL_0008: call 0x06000002
IL_000d: stloc.3
IL_000e: ldloc.s V_5
IL_0010: call 0x06000003
IL_0015: nop
IL_0016: ldloc.3
IL_0017: call 0x06000003
IL_001c: nop
IL_001d: ret
}");
diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000003"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" />
<entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" />
<entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" />
<entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" />
<entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1e"">
<local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
<local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
#region Gen3
// Modify different method. (Previous generations
// have not referenced method.)
method2 = compilation2.GetMember<MethodSymbol>("B.N");
var method3 = compilation3.GetMember<MethodSymbol>("B.N");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL(
@"{
// Code size 28 (0x1c)
.maxstack 1
IL_0000: nop
IL_0001: call 0x06000002
IL_0006: stloc.2
IL_0007: call 0x06000002
IL_000c: stloc.1
IL_000d: ldloc.2
IL_000e: call 0x06000003
IL_0013: nop
IL_0014: ldloc.1
IL_0015: call 0x06000003
IL_001a: nop
IL_001b: ret
}");
diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000004"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" />
<entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" />
<entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" />
<entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" />
<entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
#endregion
}
/// <summary>
/// Preserve locals for method added after initial compilation.
/// </summary>
[Fact]
public void PreserveLocalSlots_NewMethod()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void M()
{
var a = new object();
var b = string.Empty;
}
}";
var source2 =
@"class C
{
static void M()
{
var a = 1;
var b = string.Empty;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider);
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true)));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M",
@"{
// Code size 10 (0xa)
.maxstack 1
.locals init ([object] V_0,
string V_1, //b
int V_2) //a
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.2
IL_0003: ldsfld ""string string.Empty""
IL_0008: stloc.1
IL_0009: ret
}");
diff2.VerifyPdb(new[] { 0x06000002 }, @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method token=""0x6000002"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" />
<entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" />
<entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
<local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
/// <summary>
/// Local types should be retained, even if the local is no longer
/// used by the method body, since there may be existing
/// references to that slot, in a Watch window for instance.
/// </summary>
[WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")]
[Fact]
public void PreserveLocalTypes()
{
var source0 =
@"class C
{
static void Main()
{
var x = true;
var y = x;
System.Console.WriteLine(y);
}
}";
var source1 =
@"class C
{
static void Main()
{
var x = ""A"";
var y = x;
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.Main");
var method1 = compilation1.GetMember<MethodSymbol>("C.Main");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.Main", @"
{
// Code size 17 (0x11)
.maxstack 1
.locals init ([bool] V_0,
[bool] V_1,
string V_2, //x
string V_3) //y
IL_0000: nop
IL_0001: ldstr ""A""
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: stloc.3
IL_0009: ldloc.3
IL_000a: call ""void System.Console.WriteLine(string)""
IL_000f: nop
IL_0010: ret
}");
}
/// <summary>
/// Preserve locals if SemanticEdit.PreserveLocalVariables is set.
/// </summary>
[Fact]
public void PreserveLocalVariablesFlag()
{
var source =
@"class C
{
static System.IDisposable F() { return null; }
static void M()
{
using (F()) { }
using (var x = F()) { }
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1a = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false)));
diff1a.VerifyIL("C.M", @"
{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}
");
var diff1b = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true)));
diff1b.VerifyIL("C.M",
@"{
// Code size 44 (0x2c)
.maxstack 1
.locals init (System.IDisposable V_0,
System.IDisposable V_1) //x
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: call ""System.IDisposable C.F()""
IL_001b: stloc.1
.try
{
IL_001c: nop
IL_001d: nop
IL_001e: leave.s IL_002b
}
finally
{
IL_0020: ldloc.1
IL_0021: brfalse.s IL_002a
IL_0023: ldloc.1
IL_0024: callvirt ""void System.IDisposable.Dispose()""
IL_0029: nop
IL_002a: endfinally
}
IL_002b: ret
}");
}
[WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")]
[Fact]
public void ChangeLocalType()
{
var source0 =
@"enum E { }
class C
{
static void M1()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in one method to type added.
var source1 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(E);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in another method.
var source2 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
}";
// Change locals in same method.
var source3 =
@"enum E { }
class A { }
class C
{
static void M1()
{
var x = default(A);
var y = x;
var z = default(E);
System.Console.WriteLine(y);
}
static void M2()
{
var x = default(A);
var y = x;
var z = default(A);
System.Console.WriteLine(y);
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M1");
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")),
SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.M2");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true)));
diff2.VerifyIL("C.M2",
@"{
// Code size 17 (0x11)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
E V_2, //z
A V_3, //x
A V_4) //y
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldc.i4.0
IL_0007: stloc.2
IL_0008: ldloc.s V_4
IL_000a: call ""void System.Console.WriteLine(object)""
IL_000f: nop
IL_0010: ret
}");
var method3 = compilation3.GetMember<MethodSymbol>("C.M2");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true)));
diff3.VerifyIL("C.M2",
@"{
// Code size 18 (0x12)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[unchanged] V_2,
A V_3, //x
A V_4, //y
A V_5) //z
IL_0000: nop
IL_0001: ldnull
IL_0002: stloc.3
IL_0003: ldloc.3
IL_0004: stloc.s V_4
IL_0006: ldnull
IL_0007: stloc.s V_5
IL_0009: ldloc.s V_4
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Update()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 1 }</N:0>;
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</N:0>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md1 = diff1.GetMetadata();
AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader }));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
[Fact]
public void AnonymousTypes_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
class C
{
static void F()
{
}
}
");
var source1 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 2 }</N:0>;
}
}
");
var source2 = MarkedSource(@"
class C
{
static void F()
{
var <N:0>x = new { A = 3 }</N:0>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 9 (0x9)
.maxstack 1
.locals init (<>f__AnonymousType0<int> V_0) //x
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_0007: stloc.0
IL_0008: ret
}
");
// expect a single TypeRef for System.Object
var md2 = diff2.GetMetadata();
AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader }));
}
/// <summary>
/// Reuse existing anonymous types.
/// </summary>
[WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")]
[Fact]
public void AnonymousTypes()
{
var source0 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = x.A;
var z = new { };
}
}
}";
var source1 =
@"namespace N
{
class A
{
static object F = new { A = 1, B = 2 };
}
}
namespace M
{
class B
{
static void M()
{
var x = new { B = 3, A = 4 };
var y = new { A = x.A };
var z = new { };
}
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var m0 = compilation0.GetMember<MethodSymbol>("M.B.M");
var m1 = compilation1.GetMember<MethodSymbol>("M.B.M");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider());
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type
diff1.VerifyIL("M.B.M", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (<>f__AnonymousType1<int, int> V_0, //x
[int] V_1,
<>f__AnonymousType2 V_2, //z
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: ldc.i4.4
IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get""
IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_0014: stloc.3
IL_0015: newobj ""<>f__AnonymousType2..ctor()""
IL_001a: stloc.2
IL_001b: ret
}");
}
/// <summary>
/// Anonymous type names with module ids
/// and gaps in indices.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")]
[WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")]
public void AnonymousTypes_OtherTypeNames()
{
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
// Valid signature, although not sequential index
.class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
.field public !'<B>j__TPar' B
}
// Invalid signature, unexpected type parameter names
.class '<>f__AnonymousType1'<A, B> extends object
{
.field public !A A
.field public !B B
}
// Module id, duplicate index
.class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object
{
.field public !'<A>j__TPar' A
}
// Module id
.class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object
{
.field public !'<B>j__TPar' B
}
.class public C extends object
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F()
{
ldnull
ret
}
}";
var source0 =
@"class C
{
static object F()
{
return 0;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 1 };
var y = new { A = x.A };
return y;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
diff1.VerifyIL("C.F",
@"{
// Code size 31 (0x1f)
.maxstack 2
.locals init (<>f__AnonymousType2<object, int> V_0, //x
<>f__AnonymousType3<object> V_1, //y
object V_2)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: ldc.i4.1
IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)""
IL_000c: stloc.0
IL_000d: ldloc.0
IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get""
IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)""
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: stloc.2
IL_001b: br.s IL_001d
IL_001d: ldloc.2
IL_001e: ret
}");
}
/// <summary>
/// Update method with anonymous type that was
/// not directly referenced in previous generation.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration()
{
var source0 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x;
}
}");
var source1 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = 1</N:1>;
return x + 1;
}
}");
var source2 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 2 }</N:2>;
return x.A;
}
}");
var source3 = MarkedSource(
@"class A { }
class B
{
static object F()
{
var <N:0>x = new { A = 1 }</N:0>;
return x.A;
}
static object G()
{
var <N:1>x = new { A = new A() }</N:1>;
var <N:2>y = new { B = 3 }</N:2>;
return y.B;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var compilation3 = compilation2.WithSource(source3.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var method0 = compilation0.GetMember<MethodSymbol>("B.G");
var method1 = compilation1.GetMember<MethodSymbol>("B.G");
var method2 = compilation2.GetMember<MethodSymbol>("B.G");
var method3 = compilation3.GetMember<MethodSymbol>("B.G");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types
diff1.VerifyIL("B.G", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (int V_0, //x
[object] V_1,
object V_2)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.1
IL_0005: add
IL_0006: box ""int""
IL_000b: stloc.2
IL_000c: br.s IL_000e
IL_000e: ldloc.2
IL_000f: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type
diff2.VerifyIL("B.G", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
object V_5)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.2
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.3
IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get""
IL_001a: stloc.s V_5
IL_001c: br.s IL_001e
IL_001e: ldloc.s V_5
IL_0020: ret
}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types
diff3.VerifyIL("B.G", @"
{
// Code size 39 (0x27)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[object] V_2,
<>f__AnonymousType0<A> V_3, //x
<>f__AnonymousType1<int> V_4, //y
[object] V_5,
object V_6)
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)""
IL_000b: stloc.3
IL_000c: ldc.i4.3
IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)""
IL_0012: stloc.s V_4
IL_0014: ldloc.s V_4
IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get""
IL_001b: box ""int""
IL_0020: stloc.s V_6
IL_0022: br.s IL_0024
IL_0024: ldloc.s V_6
IL_0026: ret
}");
}
/// <summary>
/// Update another method (without directly referencing
/// anonymous type) after updating method with anonymous type.
/// </summary>
[Fact]
public void AnonymousTypes_SkipGeneration_2()
{
var source0 =
@"class C
{
static object F()
{
var x = new { A = 1 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = 1;
return x + 1;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = 2, B = 3 };
return x.A;
}
static object G()
{
var x = new { A = (object)null };
var y = new { A = 'a', B = 'b' };
return x;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var g3 = compilation3.GetMember<MethodSymbol>("C.G");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch
{
"F" => testData0.GetMethodData("C.F").GetEncDebugInfo(),
"G" => testData0.GetMethodData("C.G").GetEncDebugInfo(),
_ => default,
});
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetTypeDefNames()); // no additional types
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true)));
using var md3 = diff3.GetMetadata();
var reader3 = md3.Reader;
readers.Add(reader3);
CheckNames(readers, reader3.GetTypeDefNames()); // no additional types
}
/// <summary>
/// Local from previous generation is of an anonymous
/// type not available in next generation.
/// </summary>
[Fact]
public void AnonymousTypes_AddThenDelete()
{
var source0 =
@"class C
{
object A;
static object F()
{
var x = new C();
var y = x.A;
return y;
}
}";
var source1 =
@"class C
{
static object F()
{
var x = new { A = new object() };
var y = x.A;
return y;
}
}";
var source2 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 2 };
var y = x.A;
y = new { B = new object() }.B;
return y;
}
}";
var source3 =
@"class C
{
static object F()
{
var x = new { A = new object(), B = 3 };
var y = x.A;
return y;
}
}";
var source4 =
@"class C
{
static object F()
{
var x = new { B = 4, A = new object() };
var y = x.A;
return y;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var compilation4 = compilation3.WithSource(source4);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C");
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type
diff1.VerifyIL("C.F", @"
{
// Code size 27 (0x1b)
.maxstack 1
.locals init ([unchanged] V_0,
object V_1, //y
[object] V_2,
<>f__AnonymousType0<object> V_3, //x
object V_4)
IL_0000: nop
IL_0001: newobj ""object..ctor()""
IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)""
IL_000b: stloc.3
IL_000c: ldloc.3
IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get""
IL_0012: stloc.1
IL_0013: ldloc.1
IL_0014: stloc.s V_4
IL_0016: br.s IL_0018
IL_0018: ldloc.s V_4
IL_001a: ret
}");
var method2 = compilation2.GetMember<MethodSymbol>("C.F");
}
[Fact]
public void AnonymousTypes_DifferentCase()
{
var source0 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { A = 1, B = 2 }</N:0>;
var <N:1>y = new { a = 3, b = 4 }</N:1>;
}
}");
var source1 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { AB = 3 }</N:1>;
}
}");
var source2 = MarkedSource(@"
class C
{
static void M()
{
var <N:0>x = new { a = 1, B = 2 }</N:0>;
var <N:1>y = new { Ab = 5 }</N:1>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var m0 = compilation0.GetMember<MethodSymbol>("C.M");
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1");
// the first two slots can't be reused since the type changed
diff1.VerifyIL("C.M",
@"{
// Code size 17 (0x11)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
<>f__AnonymousType3<int> V_3) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.3
IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)""
IL_000f: stloc.3
IL_0010: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1");
// we can reuse slot for "x", it's type haven't changed
diff2.VerifyIL("C.M",
@"{
// Code size 18 (0x12)
.maxstack 2
.locals init ([unchanged] V_0,
[unchanged] V_1,
<>f__AnonymousType2<int, int> V_2, //x
[unchanged] V_3,
<>f__AnonymousType4<int> V_4) //y
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: ldc.i4.2
IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)""
IL_0008: stloc.2
IL_0009: ldc.i4.5
IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)""
IL_000f: stloc.s V_4
IL_0011: ret
}");
}
[Fact]
public void AnonymousTypes_Nested1()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: ret
}
";
v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Nested2()
{
var template = @"
using System;
using System.Linq;
class C
{
static void F(string[] args)
{
var <N:0>result =
from a in args
<N:1>let x = a.Reverse()</N:1>
<N:2>let y = x.Reverse()</N:2>
<N:3>where x.SequenceEqual(y)</N:3>
<N:4>select new { Value = a, Length = a.Length }</N:4></N:0>;
Console.WriteLine(<<VALUE>>);
}
}";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation0.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var expectedIL = @"
{
// Code size 155 (0x9b)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0007: dup
IL_0008: brtrue.s IL_0021
IL_000a: pop
IL_000b: ldsfld ""C.<>c C.<>c.<>9""
IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)""
IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)""
IL_001b: dup
IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0""
IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)""
IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)""
IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)""
IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_004f: dup
IL_0050: brtrue.s IL_0069
IL_0052: pop
IL_0053: ldsfld ""C.<>c C.<>c.<>9""
IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)""
IL_0063: dup
IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2""
IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)""
IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_0073: dup
IL_0074: brtrue.s IL_008d
IL_0076: pop
IL_0077: ldsfld ""C.<>c C.<>c.<>9""
IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)""
IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)""
IL_0087: dup
IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3""
IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)""
IL_0092: stloc.0
IL_0093: ldc.i4.<<VALUE>>
IL_0094: call ""void System.Console.WriteLine(int)""
IL_0099: nop
IL_009a: ret
}
";
v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0"));
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[Fact]
public void AnonymousTypes_Query1()
{
var source0 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
<N:3>select new { Value = a, Length = a.Length }</N:3></N:4>;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value</N:8>;
args = args.Concat(newArgs).ToArray();
System.Diagnostics.Debugger.Break();
result.ToString();
}
}
");
var source1 = MarkedSource(@"
using System.Linq;
class C
{
static void F(string[] args)
{
args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" };
var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null };
for (int i = 0; i < 10; i++)
{
var <N:4>result =
from a in args
<N:0>let x = a.Reverse()</N:0>
<N:1>let y = x.Reverse()</N:1>
<N:2>where x.SequenceEqual(y)</N:2>
orderby a.Length ascending, a descending
<N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>;
var linked = result.Aggregate(
false ? new { Head = (string)null, Tail = (dynamic)null } : null,
(total, curr) => new { Head = curr.Value, Tail = (dynamic)total });
var str = linked?.Tail?.Head;
var <N:8>newArgs =
from a in result
<N:5>let value = a.Value</N:5>
<N:6>let length = a.Length</N:6>
<N:7>where value.Length == length</N:7>
select value + value</N:8>;
args = args.Concat(newArgs).ToArray();
list = new { Head = (dynamic)i, Tail = (dynamic)list };
System.Diagnostics.Debugger.Break();
}
System.Diagnostics.Debugger.Break();
}
}
");
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1) //newArgs
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>o__0#1: {<>p__0}",
"C: {<>o__0#1, <>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}",
"<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyLocalSignature("C.F", @"
.locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result
System.Collections.Generic.IEnumerable<string> V_1, //newArgs
<>f__AnonymousType5<dynamic, dynamic> V_2, //list
int V_3, //i
<>f__AnonymousType5<string, dynamic> V_4, //linked
object V_5, //str
<>f__AnonymousType5<string, dynamic> V_6,
object V_7,
bool V_8)
");
}
[Fact]
public void AnonymousTypes_Dynamic1()
{
var template = @"
using System;
class C
{
public void F()
{
var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>;
Console.WriteLine(x.B + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var baselineIL0 = @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: call ""void System.Console.WriteLine(int)""
IL_0014: nop
IL_0015: ret
}
";
v0.VerifyIL("C.F", baselineIL0);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
var baselineIL = @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (<>f__AnonymousType0<dynamic, int> V_0) //x
IL_0000: nop
IL_0001: ldnull
IL_0002: ldc.i4.1
IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)""
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get""
IL_000f: ldc.i4.<<VALUE>>
IL_0010: add
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: nop
IL_0017: ret
}
";
diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1"));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2"));
}
/// <summary>
/// Should not re-use locals if the method metadata
/// signature is unsupported.
/// </summary>
[WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")]
public void LocalType_UnsupportedSignatureContent()
{
// Equivalent to C#, but with extra local and required modifier on
// expected local. Used to generate initial (unsupported) metadata.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method private static object F()
{
ldnull
ret
}
.method private static void M1()
{
.locals init ([0] object other, [1] object modreq(int32) o)
call object C::F()
stloc.1
ldloc.1
call void C::M2(object)
ret
}
.method private static void M2(object o)
{
ret
}
}";
var source =
@"class C
{
static object F()
{
return null;
}
static void M1()
{
object o = F();
M2(o);
}
static void M2(object o)
{
}
}";
ImmutableArray<byte> assemblyBytes;
ImmutableArray<byte> pdbBytes;
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.M1");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M1",
@"{
// Code size 15 (0xf)
.maxstack 1
.locals init (object V_0) //o
IL_0000: nop
IL_0001: call ""object C.F()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: call ""void C.M2(object)""
IL_000d: nop
IL_000e: ret
}");
}
/// <summary>
/// Should not re-use locals with custom modifiers.
/// </summary>
[WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")]
public void LocalType_CustomModifiers()
{
// Equivalent method signature to C#, but
// with optional modifier on locals.
var ilSource =
@".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly '<<GeneratedFileName>>' { }
.class public C
{
.method public specialname rtspecialname instance void .ctor()
{
ret
}
.method public static object F(class [mscorlib]System.IDisposable d)
{
.locals init ([0] class C modopt(int32) c,
[1] class [mscorlib]System.IDisposable modopt(object),
[2] bool V_2,
[3] object V_3)
ldnull
ret
}
}";
var source =
@"class C
{
static object F(System.IDisposable d)
{
C c;
using (d)
{
c = (C)d;
}
return c;
}
}";
var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0];
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
moduleMetadata0,
m => default);
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1,
[bool] V_2,
[object] V_3,
C V_4, //c
System.IDisposable V_5,
object V_6)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: stloc.s V_5
.try
{
-IL_0004: nop
-IL_0005: ldarg.0
IL_0006: castclass ""C""
IL_000b: stloc.s V_4
-IL_000d: nop
IL_000e: leave.s IL_001d
}
finally
{
~IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_001c
IL_0014: ldloc.s V_5
IL_0016: callvirt ""void System.IDisposable.Dispose()""
IL_001b: nop
IL_001c: endfinally
}
-IL_001d: ldloc.s V_4
IL_001f: stloc.s V_6
IL_0021: br.s IL_0023
-IL_0023: ldloc.s V_6
IL_0025: ret
}", methodToken: diff1.EmitResult.UpdatedMethods.Single());
}
/// <summary>
/// Temporaries for locals used within a single
/// statement should not be preserved.
/// </summary>
[Fact]
public void TemporaryLocals_Other()
{
// Use increment as an example of a compiler generated
// temporary that does not span multiple statements.
var source =
@"class C
{
int P { get; set; }
static int M()
{
var c = new C();
return c.P++;
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init (C V_0, //c
[int] V_1,
[int] V_2,
int V_3,
int V_4)
IL_0000: nop
IL_0001: newobj ""C..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: dup
IL_0009: callvirt ""int C.P.get""
IL_000e: stloc.3
IL_000f: ldloc.3
IL_0010: ldc.i4.1
IL_0011: add
IL_0012: callvirt ""void C.P.set""
IL_0017: nop
IL_0018: ldloc.3
IL_0019: stloc.s V_4
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_4
IL_001f: ret
}");
}
/// <summary>
/// Local names array (from PDB) may have fewer slots than method
/// signature (from metadata) when the trailing slots are unnamed.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270()
{
var source =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(
ModuleMetadata.CreateFromImage(bytes0),
testData0.GetMethodData("C.M").EncDebugInfoProvider());
testData0.GetMethodData("C.M").VerifyIL(@"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init (System.IDisposable V_0) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.0
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.0
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}");
}
/// <summary>
/// Similar to above test but with no named locals in original.
/// </summary>
[WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")]
[Fact]
public void Bug782270_NoNamedLocals()
{
// Equivalent to C#, but with unnamed locals.
// Used to generate initial metadata.
var ilSource =
@".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) }
.assembly '<<GeneratedFileName>>' { }
.class C extends object
{
.method private static class [netstandard]System.IDisposable F()
{
ldnull
ret
}
.method private static void M()
{
.locals init ([0] object, [1] object)
ret
}
}";
var source0 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
}
}";
var source1 =
@"class C
{
static System.IDisposable F()
{
return null;
}
static void M()
{
using (var o = F())
{
}
}
}";
EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes);
var md0 = ModuleMetadata.CreateFromImage(assemblyBytes);
// Still need a compilation with source for the initial
// generation - to get a MethodSymbol and syntax map.
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M", @"
{
// Code size 23 (0x17)
.maxstack 1
.locals init ([object] V_0,
[object] V_1,
System.IDisposable V_2) //o
IL_0000: nop
IL_0001: call ""System.IDisposable C.F()""
IL_0006: stloc.2
.try
{
IL_0007: nop
IL_0008: nop
IL_0009: leave.s IL_0016
}
finally
{
IL_000b: ldloc.2
IL_000c: brfalse.s IL_0015
IL_000e: ldloc.2
IL_000f: callvirt ""void System.IDisposable.Dispose()""
IL_0014: nop
IL_0015: endfinally
}
IL_0016: ret
}
");
}
[Fact]
public void TemporaryLocals_ReferencedType()
{
var source =
@"class C
{
static object F()
{
return null;
}
static void M()
{
var x = new System.Collections.Generic.HashSet<int>();
x.Add(1);
}
}";
var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var modMeta = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(
modMeta,
methodData0.EncDebugInfoProvider());
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.VerifyIL("C.M",
@"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (System.Collections.Generic.HashSet<int> V_0) //x
IL_0000: nop
IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)""
IL_000e: pop
IL_000f: ret
}
");
}
[WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")]
[WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")]
[Fact]
public void DynamicOperations()
{
var source =
@"class A
{
static object F = null;
object x = ((dynamic)F) + 1;
static A()
{
((dynamic)F).F();
}
A() { }
static void M(object o)
{
((dynamic)o).x = 1;
}
static void N(A o)
{
o.x = 1;
}
}
class B
{
static object F = null;
static object G = ((dynamic)F).F();
object x = ((dynamic)F) + 1;
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef });
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
// Source method with dynamic operations.
var methodData0 = testData0.GetMethodData("A.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var method0 = compilation0.GetMember<MethodSymbol>("A.M");
var method1 = compilation1.GetMember<MethodSymbol>("A.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Source method with no dynamic operations.
methodData0 = testData0.GetMethodData("A.N");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A.N");
method1 = compilation1.GetMember<MethodSymbol>("A.N");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..ctor");
method1 = compilation1.GetMember<MethodSymbol>("A..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Explicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("A..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("A..cctor");
method1 = compilation1.GetMember<MethodSymbol>("A..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .ctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..ctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..ctor");
method1 = compilation1.GetMember<MethodSymbol>("B..ctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
// Implicit .cctor with dynamic operations.
methodData0 = testData0.GetMethodData("B..cctor");
generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
method0 = compilation0.GetMember<MethodSymbol>("B..cctor");
method1 = compilation1.GetMember<MethodSymbol>("B..cctor");
diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
}
[Fact]
public void DynamicLocals()
{
var template = @"
using System;
class C
{
public void F()
{
dynamic <N:0>x = 1</N:0>;
Console.WriteLine((int)x + <<VALUE>>);
}
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var v0 = CompileAndVerify(compilation0);
v0.VerifyDiagnostics();
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
v0.VerifyIL("C.F", @"
{
// Code size 82 (0x52)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: call ""void System.Console.WriteLine(int)""
IL_0050: nop
IL_0051: ret
}
");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>o__0#1}",
"C.<>o__0#1: {<>p__0}");
diff1.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.1
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>o__0#2, <>o__0#1}",
"C.<>o__0#1: {<>p__0}",
"C.<>o__0#2: {<>p__0}");
diff2.VerifyIL("C.F", @"
{
// Code size 84 (0x54)
.maxstack 3
.locals init (object V_0) //x
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: box ""int""
IL_0007: stloc.0
IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_000d: brfalse.s IL_0011
IL_000f: br.s IL_0036
IL_0011: ldc.i4.s 16
IL_0013: ldtoken ""int""
IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001d: ldtoken ""C""
IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)""
IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target""
IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0""
IL_0045: ldloc.0
IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)""
IL_004b: ldc.i4.2
IL_004c: add
IL_004d: call ""void System.Console.WriteLine(int)""
IL_0052: nop
IL_0053: ret
}
");
}
[Fact]
public void ExceptionFilters()
{
var source0 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
}
}
");
var source1 = MarkedSource(@"
using System;
using System.IO;
class C
{
static bool G(Exception e) => true;
static void F()
{
try
{
throw new InvalidOperationException();
}
catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1>
{
Console.WriteLine();
}
catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3>
{
Console.WriteLine();
}
Console.WriteLine(1);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 90 (0x5a)
.maxstack 2
.locals init (System.IO.IOException V_0, //e
bool V_1,
System.Exception V_2, //e
bool V_3)
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: newobj ""System.InvalidOperationException..ctor()""
IL_0007: throw
}
filter
{
IL_0008: isinst ""System.IO.IOException""
IL_000d: dup
IL_000e: brtrue.s IL_0014
IL_0010: pop
IL_0011: ldc.i4.0
IL_0012: br.s IL_0020
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: call ""bool C.G(System.Exception)""
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldc.i4.0
IL_001e: cgt.un
IL_0020: endfilter
} // end filter
{ // handler
IL_0022: pop
IL_0023: nop
IL_0024: call ""void System.Console.WriteLine()""
IL_0029: nop
IL_002a: nop
IL_002b: leave.s IL_0052
}
filter
{
IL_002d: isinst ""System.Exception""
IL_0032: dup
IL_0033: brtrue.s IL_0039
IL_0035: pop
IL_0036: ldc.i4.0
IL_0037: br.s IL_0045
IL_0039: stloc.2
IL_003a: ldloc.2
IL_003b: call ""bool C.G(System.Exception)""
IL_0040: stloc.3
IL_0041: ldloc.3
IL_0042: ldc.i4.0
IL_0043: cgt.un
IL_0045: endfilter
} // end filter
{ // handler
IL_0047: pop
IL_0048: nop
IL_0049: call ""void System.Console.WriteLine()""
IL_004e: nop
IL_004f: nop
IL_0050: leave.s IL_0052
}
IL_0052: ldc.i4.1
IL_0053: call ""void System.Console.WriteLine(int)""
IL_0058: nop
IL_0059: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void MethodSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(1);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
System.Console.WriteLine(2);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
[WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void LocalSignatureWithNoPIAType()
{
var sourcePIA = @"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")]
public interface I
{
}";
var source0 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(null);
}
}");
var source1 = MarkedSource(@"
class C
{
static void M(I x)
{
I <N:0>y = null</N:0>;
M(x);
}
}");
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA });
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,16): warning CS0219: The variable 'y' is assigned but its value is never used
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"),
// error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I"));
}
/// <summary>
/// Disallow edits that require NoPIA references.
/// </summary>
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIAReferences()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")]
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")]
public interface IA
{
void M();
int P { get; }
event Action E;
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")]
public interface IB
{
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")]
public interface IC
{
}
public struct S
{
public object F;
}";
var source0 =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
var o = default(IA);
o.M();
M2(o.P);
o.E += M1;
M2(C<IA>.F);
M2(new S());
}
static void M2(object o)
{
}
}";
var source1A = source0;
var source1B =
@"class C<T>
{
static object F = typeof(IC);
static void M1()
{
M2(null);
}
static void M2(object o)
{
}
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1A = compilation0.WithSource(source1A);
var compilation1B = compilation0.WithSource(source1B);
var method0 = compilation0.GetMember<MethodSymbol>("C.M1");
var method1B = compilation1B.GetMember<MethodSymbol>("C.M1");
var method1A = compilation1A.GetMember<MethodSymbol>("C.M1");
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C<T>.M1");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
// Disallow edits that require NoPIA references.
var diff1A = compilation1A.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true)));
diff1A.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA"));
// Allow edits that do not require NoPIA references,
// even if the previous code included references.
var diff1B = compilation1B.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true)));
diff1B.VerifyIL("C<T>.M1",
@"{
// Code size 9 (0x9)
.maxstack 1
.locals init ([unchanged] V_0,
[unchanged] V_1)
IL_0000: nop
IL_0001: ldnull
IL_0002: call ""void C<T>.M2(object)""
IL_0007: nop
IL_0008: ret
}");
using var md1 = diff1B.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetTypeDefNames());
}
[WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)]
public void NoPIATypeInNamespace()
{
var sourcePIA =
@"using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""_.dll"")]
[assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")]
namespace N
{
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")]
public interface IA
{
}
}
[ComImport()]
[Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")]
public interface IB
{
}";
var source =
@"class C<T>
{
static void M(object o)
{
M(C<N.IA>.E.X);
M(C<IB>.E.X);
}
enum E { X }
}";
var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef });
var compilation1 = compilation0.WithSource(source);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"),
// error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'.
Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB"));
diff1.VerifyIL("C<T>.M",
@"{
// Code size 26 (0x1a)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: box ""C<N.IA>.E""
IL_0007: call ""void C<T>.M(object)""
IL_000c: nop
IL_000d: ldc.i4.0
IL_000e: box ""C<IB>.E""
IL_0013: call ""void C<T>.M(object)""
IL_0018: nop
IL_0019: ret
}");
}
/// <summary>
/// Should use TypeDef rather than TypeRef for unrecognized
/// local of a type defined in the original assembly.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfTypeFromAssembly()
{
var source =
@"class E : System.Exception
{
}
class C
{
static void M()
{
try
{
}
catch (E e)
{
}
}
}";
var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source);
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var methodData0 = testData0.GetMethodData("C.M");
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider());
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeRefNames(), "Object");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(7, TableIndex.TypeRef),
Handle(2, TableIndex.MethodDef),
Handle(2, TableIndex.StandAloneSig),
Handle(2, TableIndex.AssemblyRef));
diff1.VerifyIL("C.M", @"
{
// Code size 11 (0xb)
.maxstack 1
.locals init (E V_0) //e
IL_0000: nop
.try
{
IL_0001: nop
IL_0002: nop
IL_0003: leave.s IL_000a
}
catch E
{
IL_0005: stloc.0
IL_0006: nop
IL_0007: nop
IL_0008: leave.s IL_000a
}
IL_000a: ret
}");
}
/// <summary>
/// Similar to above test but with anonymous type
/// added in subsequent generation.
/// </summary>
[WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")]
[Fact]
public void UnrecognizedLocalOfAnonymousTypeFromAssembly()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
static string G()
{
var o = new { Y = 1 };
return o.ToString();
}
}";
var source2 =
@"class C
{
static string F()
{
return null;
}
static string G()
{
return null;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var method1G = compilation1.GetMember<MethodSymbol>("C.G");
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var method2G = compilation2.GetMember<MethodSymbol>("C.G");
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
// Use empty LocalVariableNameProvider for original locals and
// use preserveLocalVariables: true for the edit so that existing
// locals are retained even though all are unrecognized.
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new List<MetadataReader> { reader0, reader1 };
CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1");
CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider");
// Change method updated in generation 1.
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
readers.Add(reader2);
CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard");
CheckNames(readers, reader2.GetTypeDefNames());
CheckNames(readers, reader2.GetTypeRefNames(), "Object");
// Change method unchanged since generation 0.
var diff2G = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true)));
}
[Fact]
public void BrokenOutputStreams()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray();
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
badStream,
ilStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
badStream,
pdbStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred.
Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1)
);
result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[Fact]
public void BrokenPortablePdbStream()
{
var source0 =
@"class C
{
static string F()
{
return null;
}
}";
var source1 =
@"class C
{
static string F()
{
var o = new { X = 1 };
return o.ToString();
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb));
using (new EnsureEnglishUICulture())
using (var md0 = ModuleMetadata.CreateFromImage(bytes0))
{
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream();
var isAddedSymbol = new Func<ISymbol, bool>(s => false);
var badStream = new BrokenStream();
badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite;
var result = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)),
isAddedSymbol,
mdStream,
ilStream,
badStream,
new CompilationTestData(),
default);
Assert.False(result.Success);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'I/O error occurred.'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)
);
}
}
[WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SymWriterErrors()
{
var source0 =
@"class C
{
}";
var source1 =
@"class C
{
static void Main() { }
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(source1);
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var diff1 = compilation1.EmitDifference(
EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider),
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))),
testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() });
diff1.EmitResult.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message"));
Assert.False(diff1.EmitResult.Success);
}
[WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")]
[Fact]
public void BlobContainsInvalidValues()
{
var source0 =
@"class C
{
static void F()
{
string goo = ""abc"";
}
}";
var source1 =
@"class C
{
static void F()
{
float goo = 10;
}
}";
var source2 =
@"class C
{
static void F()
{
bool goo = true;
}
}";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20);
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard");
var method0F = compilation0.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method1F = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)));
var handle = MetadataTokens.BlobHandle(1);
byte[] value0 = reader0.GetBlobBytes(handle);
Assert.Equal("20-01-01-08", BitConverter.ToString(value0));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var method2F = compilation2.GetMember<MethodSymbol>("C.F");
var diff2F = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true)));
byte[] value1 = reader1.GetBlobBytes(handle);
Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1));
using var md2 = diff2F.GetMetadata();
var reader2 = md2.Reader;
byte[] value2 = reader2.GetBlobBytes(handle);
Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly1()
{
var sourceA0 = @"
public class A
{
}
";
var sourceA1 = @"
public class A
{
public void M() { System.Console.WriteLine(1);}
}
public class X {}
";
var sourceB0 = @"
public class B
{
public static void F() { }
}";
var sourceB1 = @"
public class B
{
public static void F() { new A().M(); }
}
public class Y : X { }
";
var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA");
var compilationA1 = compilationA0.WithSource(sourceA1);
var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB");
var bytesA0 = compilationA0.EmitToArray();
var bytesB0 = compilationB0.EmitToArray();
var mdA0 = ModuleMetadata.CreateFromImage(bytesA0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider);
var mA1 = compilationA1.GetMember<MethodSymbol>("A.M");
var mX1 = compilationA1.GetMember<TypeSymbol>("X");
var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() };
var diffA1 = compilationA1.EmitDifference(
generationA0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, mA1),
SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)),
allAddedSymbols);
diffA1.EmitResult.Diagnostics.Verify();
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")),
SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))),
allAddedSymbols);
diffB1.EmitResult.Diagnostics.Verify(
// (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public class X {}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14),
// (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'.
// public void M() { System.Console.WriteLine(1);}
Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17));
}
[Fact]
public void ReferenceToMemberAddedToAnotherAssembly2()
{
var sourceA = @"
public class A
{
public void M() { }
}";
var sourceB0 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var sourceB1 = @"
public class B
{
public static void F() { var a = new A(); a.M(); }
}";
var sourceB2 = @"
public class B
{
public static void F() { var a = new A(); }
}";
var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA");
var aRef = compilationA.ToMetadataReference();
var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB");
var compilationB1 = compilationB0.WithSource(sourceB1);
var compilationB2 = compilationB1.WithSource(sourceB2);
var testDataB0 = new CompilationTestData();
var bytesB0 = compilationB0.EmitToArray(testData: testDataB0);
var mdB0 = ModuleMetadata.CreateFromImage(bytesB0);
var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider());
var f0 = compilationB0.GetMember<MethodSymbol>("B.F");
var f1 = compilationB1.GetMember<MethodSymbol>("B.F");
var f2 = compilationB2.GetMember<MethodSymbol>("B.F");
var diffB1 = compilationB1.EmitDifference(
generationB0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true)));
diffB1.VerifyIL("B.F", @"
{
// Code size 15 (0xf)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: callvirt ""void A.M()""
IL_000d: nop
IL_000e: ret
}
");
var diffB2 = compilationB2.EmitDifference(
diffB1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true)));
diffB2.VerifyIL("B.F", @"
{
// Code size 8 (0x8)
.maxstack 1
.locals init (A V_0) //a
IL_0000: nop
IL_0001: newobj ""A..ctor()""
IL_0006: stloc.0
IL_0007: ret
}
");
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)]
public void UniqueSynthesizedNames_DynamicSiteContainer()
{
var source0 = @"
public class C
{
public static void F(dynamic d) { d.Goo(); }
}";
var source1 = @"
public class C
{
public static void F(dynamic d) { d.Bar(); }
}";
var source2 = @"
public class C
{
public static void F(dynamic d, byte b) { d.Bar(); }
public static void F(dynamic d) { d.Bar(); }
}";
var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp,
options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify();
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
diff2.EmitResult.Diagnostics.Verify();
var reader0 = md0.MetadataReader;
var reader1 = diff1.GetMetadata().Reader;
var reader2 = diff2.GetMetadata().Reader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0");
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2");
}
[WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")]
[Fact]
public void ManyGenerations()
{
var source =
@"class C
{{
static int F() {{ return {0}; }}
}}";
var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll);
var bytes0 = compilation0.EmitToArray();
var md0 = ModuleMetadata.CreateFromImage(bytes0);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var method0 = compilation0.GetMember<MethodSymbol>("C.F");
for (int i = 2; i <= 50; i++)
{
var compilation1 = compilation0.WithSource(String.Format(source, i));
var method1 = compilation1.GetMember<MethodSymbol>("C.F");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
compilation0 = compilation1;
method0 = method1;
generation0 = diff1.NextGeneration;
}
}
[WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")]
[Fact]
public void PdbReadingErrors()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle =>
{
throw new InvalidDataException("Bad PDB!");
});
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.EmitResult.Diagnostics.Verify(
// (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''.
Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14));
}
[Fact]
public void PdbReadingErrors_PassThruExceptions()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(1);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
{
<N:0>Console.WriteLine(2);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly");
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle =>
{
throw new ArgumentOutOfRangeException();
});
// the compiler should't swallow any exceptions but InvalidDataException
Assert.Throws<ArgumentOutOfRangeException>(() =>
compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))));
}
[Fact]
public void PatternVariable_TypeChange()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 46 (0x2e)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3, //i
bool V_4,
int V_5)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""bool""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""bool""
IL_000f: stloc.3
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.s V_4
IL_0016: ldloc.s V_4
IL_0018: brfalse.s IL_0026
IL_001a: nop
IL_001b: ldloc.3
IL_001c: brtrue.s IL_0021
IL_001e: ldc.i4.0
IL_001f: br.s IL_0022
IL_0021: ldc.i4.1
IL_0022: stloc.s V_5
IL_0024: br.s IL_002b
IL_0026: ldc.i4.0
IL_0027: stloc.s V_5
IL_0029: br.s IL_002b
IL_002b: ldloc.s V_5
IL_002d: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[bool] V_4,
[int] V_5,
int V_6, //j
bool V_7,
int V_8)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_6
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_7
IL_0017: ldloc.s V_7
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_6
IL_001e: stloc.s V_8
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_8
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_8
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_DeleteInsert()
{
var source0 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var source1 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int) { return 1; } return 0; }
}");
var source2 = MarkedSource(@"
class C
{
static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 35 (0x23)
.maxstack 1
.locals init (int V_0, //i
bool V_1,
int V_2)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0013
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.0
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: ldloc.1
IL_0016: brfalse.s IL_001d
IL_0018: nop
IL_0019: ldloc.0
IL_001a: stloc.2
IL_001b: br.s IL_0021
IL_001d: ldc.i4.0
IL_001e: stloc.2
IL_001f: br.s IL_0021
IL_0021: ldloc.2
IL_0022: ret
}");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
bool V_3,
int V_4)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: ldnull
IL_0008: cgt.un
IL_000a: stloc.3
IL_000b: ldloc.3
IL_000c: brfalse.s IL_0014
IL_000e: nop
IL_000f: ldc.i4.1
IL_0010: stloc.s V_4
IL_0012: br.s IL_0019
IL_0014: ldc.i4.0
IL_0015: stloc.s V_4
IL_0017: br.s IL_0019
IL_0019: ldloc.s V_4
IL_001b: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 42 (0x2a)
.maxstack 1
.locals init ([int] V_0,
[bool] V_1,
[int] V_2,
[bool] V_3,
[int] V_4,
int V_5, //i
bool V_6,
int V_7)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: isinst ""int""
IL_0007: brfalse.s IL_0014
IL_0009: ldarg.0
IL_000a: unbox.any ""int""
IL_000f: stloc.s V_5
IL_0011: ldc.i4.1
IL_0012: br.s IL_0015
IL_0014: ldc.i4.0
IL_0015: stloc.s V_6
IL_0017: ldloc.s V_6
IL_0019: brfalse.s IL_0022
IL_001b: nop
IL_001c: ldloc.s V_5
IL_001e: stloc.s V_7
IL_0020: br.s IL_0027
IL_0022: ldc.i4.0
IL_0023: stloc.s V_7
IL_0025: br.s IL_0027
IL_0027: ldloc.s V_7
IL_0029: ret
}");
}
[Fact]
public void PatternVariable_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(bool x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; }
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { }
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.1
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.1
IL_0015: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 15 (0xf)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.0
IL_0005: ceq
IL_0007: call ""Base..ctor(bool)""
IL_000c: nop
IL_000d: nop
IL_000e: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: brtrue.s IL_000b
IL_0006: ldarg.1
IL_0007: stloc.2
IL_0008: ldc.i4.1
IL_0009: br.s IL_000c
IL_000b: ldc.i4.0
IL_000c: call ""Base..ctor(bool)""
IL_0011: nop
IL_0012: nop
IL_0013: ldc.i4.1
IL_0014: stloc.2
IL_0015: ret
}
");
}
[Fact]
public void PatternVariable_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>;
}");
var source1 = MarkedSource(@"
public class C
{
public static int a = 0;
public bool field = a is int <N:0>x</N:0> && x == 0;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.1
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 24 (0x18)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: ceq
IL_000b: stfld ""bool C.field""
IL_0010: ldarg.0
IL_0011: call ""object..ctor()""
IL_0016: nop
IL_0017: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldsfld ""int C.a""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brtrue.s IL_0013
IL_000a: ldsfld ""int C.a""
IL_000f: stloc.2
IL_0010: ldc.i4.1
IL_0011: br.s IL_0014
IL_0013: ldc.i4.0
IL_0014: stfld ""bool C.field""
IL_0019: ldarg.0
IL_001a: call ""object..ctor()""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void PatternVariable_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.1
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 7 (0x7)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.0
IL_0004: ceq
IL_0006: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)""
IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: brtrue.s IL_000a
IL_0005: ldarg.1
IL_0006: stloc.2
IL_0007: ldc.i4.1
IL_0008: br.s IL_000b
IL_000a: ldc.i4.0
IL_000b: ret
}
");
}
[Fact]
public void Tuple_Parenthesized()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 51 (0x33)
.maxstack 4
.locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x
int V_1)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)""
IL_0010: ldloc.0
IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1""
IL_0016: ldloc.0
IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0021: add
IL_0022: ldloc.0
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_002d: add
IL_002e: stloc.1
IL_002f: br.s IL_0031
IL_0031: ldloc.1
IL_0032: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 36 (0x24)
.maxstack 4
.locals init ([unchanged] V_0,
[int] V_1,
System.ValueTuple<int, int, int> V_2, //x
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_2
IL_0003: ldc.i4.1
IL_0004: ldc.i4.2
IL_0005: ldc.i4.3
IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)""
IL_000b: ldloc.2
IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1""
IL_0011: ldloc.2
IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2""
IL_0017: add
IL_0018: ldloc.2
IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3""
IL_001e: add
IL_001f: stloc.3
IL_0020: br.s IL_0022
IL_0022: ldloc.3
IL_0023: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 32 (0x20)
.maxstack 3
.locals init ([unchanged] V_0,
[int] V_1,
[unchanged] V_2,
[int] V_3,
System.ValueTuple<int, int> V_4, //x
int V_5)
IL_0000: nop
IL_0001: ldloca.s V_4
IL_0003: ldc.i4.1
IL_0004: ldc.i4.3
IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)""
IL_000a: ldloc.s V_4
IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_0011: ldloc.s V_4
IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2""
IL_0018: add
IL_0019: stloc.s V_5
IL_001b: br.s IL_001d
IL_001d: ldloc.s V_5
IL_001f: ret
}
");
}
[Fact]
public void Tuple_Decomposition()
{
var source0 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var source1 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.F", @"
{
// Code size 17 (0x11)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2, //z
int V_3)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.1
IL_0005: ldc.i4.3
IL_0006: stloc.2
IL_0007: ldloc.0
IL_0008: ldloc.1
IL_0009: add
IL_000a: ldloc.2
IL_000b: add
IL_000c: stloc.3
IL_000d: br.s IL_000f
IL_000f: ldloc.3
IL_0010: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F", @"
{
// Code size 15 (0xf)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.3
IL_0004: stloc.2
IL_0005: ldloc.0
IL_0006: ldloc.2
IL_0007: add
IL_0008: stloc.s V_4
IL_000a: br.s IL_000c
IL_000c: ldloc.s V_4
IL_000e: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.F", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
[int] V_1,
int V_2, //z
[int] V_3,
[int] V_4,
int V_5, //y
int V_6)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: stloc.s V_5
IL_0006: ldc.i4.3
IL_0007: stloc.2
IL_0008: ldloc.0
IL_0009: ldloc.s V_5
IL_000b: add
IL_000c: ldloc.2
IL_000d: add
IL_000e: stloc.s V_6
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_6
IL_0014: ret
}
");
}
[Fact]
public void ForeachStatement()
{
var source0 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x);
}
}
}");
var source1 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var source2 = MarkedSource(@"
class C
{
public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) };
public static void G()
{
foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F())
{
System.Console.WriteLine(x1);
}
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 70 (0x46)
.maxstack 2
.locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0,
int V_1,
int V_2, //x
bool V_3, //y
double V_4, //z
System.ValueTuple<bool, double> V_5)
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.0
IL_0008: ldc.i4.0
IL_0009: stloc.1
IL_000a: br.s IL_003f
IL_000c: ldloc.0
IL_000d: ldloc.1
IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0013: dup
IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0019: stloc.s V_5
IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0020: stloc.2
IL_0021: ldloc.s V_5
IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_0028: stloc.3
IL_0029: ldloc.s V_5
IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0030: stloc.s V_4
IL_0032: nop
IL_0033: ldloc.2
IL_0034: call ""void System.Console.WriteLine(int)""
IL_0039: nop
IL_003a: nop
IL_003b: ldloc.1
IL_003c: ldc.i4.1
IL_003d: add
IL_003e: stloc.1
IL_003f: ldloc.1
IL_0040: ldloc.0
IL_0041: ldlen
IL_0042: conv.i4
IL_0043: blt.s IL_000c
IL_0045: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.G", @"
{
// Code size 78 (0x4e)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
bool V_3, //y
double V_4, //z
[unchanged] V_5,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6,
int V_7,
System.ValueTuple<bool, double> V_8)
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_6
IL_0009: ldc.i4.0
IL_000a: stloc.s V_7
IL_000c: br.s IL_0045
IL_000e: ldloc.s V_6
IL_0010: ldloc.s V_7
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_001d: stloc.s V_8
IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_0024: stloc.2
IL_0025: ldloc.s V_8
IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1""
IL_002c: stloc.3
IL_002d: ldloc.s V_8
IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2""
IL_0034: stloc.s V_4
IL_0036: nop
IL_0037: ldloc.2
IL_0038: call ""void System.Console.WriteLine(int)""
IL_003d: nop
IL_003e: nop
IL_003f: ldloc.s V_7
IL_0041: ldc.i4.1
IL_0042: add
IL_0043: stloc.s V_7
IL_0045: ldloc.s V_7
IL_0047: ldloc.s V_6
IL_0049: ldlen
IL_004a: conv.i4
IL_004b: blt.s IL_000e
IL_004d: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 61 (0x3d)
.maxstack 2
.locals init ([unchanged] V_0,
[int] V_1,
int V_2, //x1
[bool] V_3,
[unchanged] V_4,
[unchanged] V_5,
[unchanged] V_6,
[int] V_7,
[unchanged] V_8,
System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9,
int V_10,
System.ValueTuple<bool, double> V_11) //yz
IL_0000: nop
IL_0001: nop
IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()""
IL_0007: stloc.s V_9
IL_0009: ldc.i4.0
IL_000a: stloc.s V_10
IL_000c: br.s IL_0034
IL_000e: ldloc.s V_9
IL_0010: ldloc.s V_10
IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>""
IL_0017: dup
IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1""
IL_001d: stloc.2
IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2""
IL_0023: stloc.s V_11
IL_0025: nop
IL_0026: ldloc.2
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: nop
IL_002d: nop
IL_002e: ldloc.s V_10
IL_0030: ldc.i4.1
IL_0031: add
IL_0032: stloc.s V_10
IL_0034: ldloc.s V_10
IL_0036: ldloc.s V_9
IL_0038: ldlen
IL_0039: conv.i4
IL_003a: blt.s IL_000e
IL_003c: ret
}
");
}
[Fact]
public void OutVar()
{
var source0 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; }
}");
var source1 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; }
}");
var source2 = MarkedSource(@"
class C
{
static void F(out int x, out int y) { x = 1; y = 2; }
static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source2.Tree);
var f0 = compilation0.GetMember<MethodSymbol>("C.G");
var f1 = compilation1.GetMember<MethodSymbol>("C.G");
var f2 = compilation2.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
int V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.2
IL_000f: br.s IL_0011
IL_0011: ldloc.2
IL_0012: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.G", @"
{
// Code size 19 (0x13)
.maxstack 2
.locals init (int V_0, //x
int V_1, //z
[int] V_2,
int V_3)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.3
IL_000f: br.s IL_0011
IL_0011: ldloc.3
IL_0012: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifyIL("C.G", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (int V_0, //x
int V_1, //y
[int] V_2,
[int] V_3,
int V_4)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: ldloca.s V_1
IL_0005: call ""void C.F(out int, out int)""
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: add
IL_000e: stloc.s V_4
IL_0010: br.s IL_0012
IL_0012: ldloc.s V_4
IL_0014: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); }
static int M(out int x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
public C() : base(M(out int <N:0>x</N:0>) + x) { }
static int M(out int x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.1
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 18 (0x12)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: call ""Base..ctor(int)""
IL_000f: nop
IL_0010: nop
IL_0011: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: call ""Base..ctor(int)""
IL_0017: nop
IL_0018: nop
IL_0019: ldloc.2
IL_001a: call ""void System.Console.Write(int)""
IL_001f: nop
IL_0020: ret
}
");
}
[Fact]
public void OutVar_InConstructorInitializer_WithLambda()
{
var baseClass = "public class Base { public Base(int x) { } }";
var source0 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var source1 = MarkedSource(@"
public class C : Base
{
<N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}" + baseClass);
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0");
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
using var md2 = diff2.GetMetadata();
var reader2 = md2.Reader;
readers = new[] { reader0, reader1, reader2 };
CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0");
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <.ctor>b__0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 44 (0x2c)
.maxstack 4
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: call ""Base..ctor(int)""
IL_0029: nop
IL_002a: nop
IL_002b: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InMethodBody_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0>
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method");
var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method");
var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int V_1) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.1
IL_0025: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff1.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
int V_2) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.2
IL_0025: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}");
diff2.VerifyIL("C.Method", @"
{
// Code size 38 (0x26)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
[int] V_1,
[int] V_2,
int V_3) //_
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stloc.3
IL_0025: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InFieldInitializer()
{
var source0 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>);
static int M(out int x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
public int field = M(out int <N:0>x</N:0>) + x;
static int M(out int x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_1
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C..ctor", @"
{
// Code size 23 (0x17)
.maxstack 3
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: stfld ""int C.field""
IL_000f: ldarg.0
IL_0010: call ""object..ctor()""
IL_0015: nop
IL_0016: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifyIL("C..ctor", @"
{
// Code size 31 (0x1f)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.0
IL_0001: ldloca.s V_0
IL_0003: call ""int C.M(out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldloca.s V_2
IL_000c: call ""int C.M(out int)""
IL_0011: add
IL_0012: stfld ""int C.field""
IL_0017: ldarg.0
IL_0018: call ""object..ctor()""
IL_001d: nop
IL_001e: ret
}
");
}
[Fact]
public void OutVar_InFieldInitializer_WithLambda()
{
var source0 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var source1 = MarkedSource(@"
public class C
{
int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>;
static int M(out int x) => throw null;
static int M2(System.Func<int> x) => throw null;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C.<>c__DisplayClass3_0: {x, <.ctor>b__0}",
"C: {<>c__DisplayClass3_0}");
diff2.VerifyIL("C..ctor", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.0
IL_0007: ldloc.0
IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x""
IL_000d: call ""int C.M(out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int C.M2(System.Func<int>)""
IL_0023: add
IL_0024: stfld ""int C.field""
IL_0029: ldarg.0
IL_002a: call ""object..ctor()""
IL_002f: nop
IL_0030: ret
}
");
diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InQuery()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
int V_1) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_1
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (int V_0, //x
[int] V_1)
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program: {<>c}",
"Program.<>c: {<>9__1_0, <N>b__1_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @"
{
// Code size 20 (0x14)
.maxstack 3
.locals init (int V_0, //x
[int] V_1,
int V_2) //y
IL_0000: ldarg.1
IL_0001: ldloca.s V_0
IL_0003: call ""int Program.M(int, out int)""
IL_0008: ldloc.0
IL_0009: add
IL_000a: ldarg.1
IL_000b: ldloca.s V_2
IL_000d: call ""int Program.M(int, out int)""
IL_0012: add
IL_0013: ret
}
");
}
[Fact]
public void OutVar_InQuery_WithLambda()
{
var source0 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
public class Program
{
static int M(int x, out int y) { y = 42; return 43; }
static int M2(System.Func<int> x) => throw null;
static void N()
{
var <N:0>query =
from a in new int[] { 1, 2 }
<N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.N");
var n1 = compilation1.GetMember<MethodSymbol>("Program.N");
var n2 = compilation2.GetMember<MethodSymbol>("Program.N");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff1.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: sub
IL_0008: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"Program.<>c__DisplayClass2_0: {x, <N>b__1}",
"Program: {<>c__DisplayClass2_0, <>c}",
"Program.<>c: {<>9__2_0, <N>b__2_0}");
diff2.VerifyIL("Program.N()", @"
{
// Code size 53 (0x35)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //query
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: newarr ""int""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.1
IL_000a: stelem.i4
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: stelem.i4
IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_0014: dup
IL_0015: brtrue.s IL_002e
IL_0017: pop
IL_0018: ldsfld ""Program.<>c Program.<>c.<>9""
IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)""
IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0028: dup
IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0""
IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_0033: stloc.0
IL_0034: ret
}
");
diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @"
{
// Code size 37 (0x25)
.maxstack 3
.locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()""
IL_0005: stloc.0
IL_0006: ldarg.1
IL_0007: ldloc.0
IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x""
IL_000d: call ""int Program.M(int, out int)""
IL_0012: ldloc.0
IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()""
IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001e: call ""int Program.M2(System.Func<int>)""
IL_0023: add
IL_0024: ret
}
");
diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
}
[Fact]
public void OutVar_InSwitchExpression()
{
var source0 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i switch
{
0 => 0,
_ => 1
};
}
static object N(out int x) { x = 1; return null; }
}");
var source1 = MarkedSource(@"
public class Program
{
static object G(int i)
{
return i + N(out var x) switch
{
0 => 0,
_ => 1
};
}
static int N(out int x) { x = 1; return 0; }
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var compilation2 = compilation1.WithSource(source0.Tree);
var n0 = compilation0.GetMember<MethodSymbol>("Program.G");
var n1 = compilation1.GetMember<MethodSymbol>("Program.G");
var n2 = compilation2.GetMember<MethodSymbol>("Program.G");
var v0 = CompileAndVerify(compilation0);
v0.VerifyIL("Program.G(int)", @"
{
// Code size 33 (0x21)
.maxstack 1
.locals init (int V_0,
object V_1)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000e
IL_000a: ldc.i4.0
IL_000b: stloc.0
IL_000c: br.s IL_0012
IL_000e: ldc.i4.1
IL_000f: stloc.0
IL_0010: br.s IL_0012
IL_0012: ldc.i4.1
IL_0013: brtrue.s IL_0016
IL_0015: nop
IL_0016: ldloc.0
IL_0017: box ""int""
IL_001c: stloc.1
IL_001d: br.s IL_001f
IL_001f: ldloc.1
IL_0020: ret
}
");
v0.VerifyIL("Program.N(out int)", @"
{
// Code size 10 (0xa)
.maxstack 2
.locals init (object V_0)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.1
IL_0003: stind.i4
IL_0004: ldnull
IL_0005: stloc.0
IL_0006: br.s IL_0008
IL_0008: ldloc.0
IL_0009: ret
}
");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers();
diff1.VerifyIL("Program.G(int)", @"
{
// Code size 52 (0x34)
.maxstack 2
.locals init ([int] V_0,
[object] V_1,
int V_2, //x
int V_3,
int V_4,
int V_5,
object V_6)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.3
IL_0003: ldloca.s V_2
IL_0005: call ""int Program.N(out int)""
IL_000a: stloc.s V_5
IL_000c: ldc.i4.1
IL_000d: brtrue.s IL_0010
IL_000f: nop
IL_0010: ldloc.s V_5
IL_0012: brfalse.s IL_0016
IL_0014: br.s IL_001b
IL_0016: ldc.i4.0
IL_0017: stloc.s V_4
IL_0019: br.s IL_0020
IL_001b: ldc.i4.1
IL_001c: stloc.s V_4
IL_001e: br.s IL_0020
IL_0020: ldc.i4.1
IL_0021: brtrue.s IL_0024
IL_0023: nop
IL_0024: ldloc.3
IL_0025: ldloc.s V_4
IL_0027: add
IL_0028: box ""int""
IL_002d: stloc.s V_6
IL_002f: br.s IL_0031
IL_0031: ldloc.s V_6
IL_0033: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers();
diff2.VerifyIL("Program.G(int)", @"
{
// Code size 38 (0x26)
.maxstack 1
.locals init ([int] V_0,
[object] V_1,
[int] V_2,
[int] V_3,
[int] V_4,
[int] V_5,
[object] V_6,
int V_7,
object V_8)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: brtrue.s IL_0005
IL_0004: nop
IL_0005: ldarg.0
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_000f
IL_000a: ldc.i4.0
IL_000b: stloc.s V_7
IL_000d: br.s IL_0014
IL_000f: ldc.i4.1
IL_0010: stloc.s V_7
IL_0012: br.s IL_0014
IL_0014: ldc.i4.1
IL_0015: brtrue.s IL_0018
IL_0017: nop
IL_0018: ldloc.s V_7
IL_001a: box ""int""
IL_001f: stloc.s V_8
IL_0021: br.s IL_0023
IL_0023: ldloc.s V_8
IL_0025: ret
}
");
}
[Fact]
public void AddUsing_AmbiguousCode()
{
var source0 = MarkedSource(@"
using System.Threading;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
}");
var source1 = MarkedSource(@"
using System.Threading;
using System.Timers;
class C
{
static void E()
{
var t = new Timer(s => System.Console.WriteLine(s));
}
static void G()
{
System.Console.WriteLine(new TimersDescriptionAttribute(""""));
}
}");
var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var e0 = compilation0.GetMember<MethodSymbol>("C.E");
var e1 = compilation1.GetMember<MethodSymbol>("C.E");
var g1 = compilation1.GetMember<MethodSymbol>("C.G");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// Pretend there was an update to C.E to ensure we haven't invalidated the test
var diffError = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diffError.EmitResult.Diagnostics.Verify(
// (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer'
// var t = new Timer(s => System.Console.WriteLine(s));
Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21));
// Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, g1)));
diff.EmitResult.Diagnostics.Verify();
diff.VerifyIL(@"C.G", @"
{
// Code size 18 (0x12)
.maxstack 1
IL_0000: nop
IL_0001: ldstr """"
IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)""
IL_000b: call ""void System.Console.WriteLine(object)""
IL_0010: nop
IL_0011: ret
}
");
}
[Fact]
public void Records_AddWellKnownMember()
{
var source0 =
@"
#nullable enable
namespace N
{
record R(int X)
{
}
}
";
var source1 =
@"
#nullable enable
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
// Verify full metadata contains expected rows.
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R");
CheckNames(reader0, reader0.GetMethodDefNames(),
/* EmbeddedAttribute */".ctor",
/* NullableAttribute */ ".ctor",
/* NullableContextAttribute */".ctor",
/* IsExternalInit */".ctor",
/* R: */
".ctor",
"get_EqualityContract",
"get_X",
"set_X",
"ToString",
"PrintMembers",
"op_Inequality",
"op_Equality",
"GetHashCode",
"Equals",
"Equals",
"<Clone>$",
".ctor",
"Deconstruct");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default),
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), // R.PrintMembers
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(20, TableIndex.TypeRef),
Handle(21, TableIndex.TypeRef),
Handle(22, TableIndex.TypeRef),
Handle(10, TableIndex.MethodDef),
Handle(3, TableIndex.Param),
Handle(3, TableIndex.StandAloneSig),
Handle(4, TableIndex.TypeSpec),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void Records_RemoveWellKnownMember()
{
var source0 =
@"
namespace N
{
record R(int X)
{
protected virtual bool PrintMembers(System.Text.StringBuilder builder)
{
return true;
}
}
}
";
var source1 =
@"
namespace N
{
record R(int X)
{
}
}
";
var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition });
var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers");
var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
diff1.VerifySynthesizedMembers(
"<global namespace>: {Microsoft}",
"Microsoft: {CodeAnalysis}",
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}");
}
[Fact]
public void TopLevelStatement_Update()
{
var source0 = @"
using System;
Console.WriteLine(""Hello"");
";
var source1 = @"
using System;
Console.WriteLine(""Hello World"");
";
var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1);
var method0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$");
var method1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$");
// Verify full metadata contains expected rows.
var bytes0 = compilation0.EmitToArray();
using var md0 = ModuleMetadata.CreateFromImage(bytes0);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "Program");
CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$", ".ctor");
CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine", /*Program.*/".ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(
md0,
EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1)));
// Verify delta metadata contains expected rows.
using var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var readers = new[] { reader0, reader1 };
EncValidation.VerifyModuleMvid(1, reader0, reader1);
CheckNames(readers, reader1.GetTypeDefNames());
CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$");
CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine");
CheckEncLog(reader1,
Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default),
Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default),
Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), // Synthesized Main method
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
CheckEncMap(reader1,
Handle(8, TableIndex.TypeRef),
Handle(9, TableIndex.TypeRef),
Handle(10, TableIndex.TypeRef),
Handle(1, TableIndex.MethodDef),
Handle(1, TableIndex.Param),
Handle(7, TableIndex.MemberRef),
Handle(8, TableIndex.MemberRef),
Handle(2, TableIndex.AssemblyRef));
}
[Fact]
public void LambdaParameterToDiscard()
{
var source0 = MarkedSource(@"
using System;
class C
{
void M()
{
var x = new Func<int, int, int>(<N:0>(a, b) => a + b + 1</N:0>);
Console.WriteLine(x(1, 2));
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void M()
{
var x = new Func<int, int, int>(<N:0>(_, _) => 10</N:0>);
Console.WriteLine(x(1, 2));
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var method0 = compilation0.GetMember<MethodSymbol>("C.M");
var method1 = compilation1.GetMember<MethodSymbol>("C.M");
var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped);
using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
// There should be no diagnostics from rude edits
diff.EmitResult.Diagnostics.Verify();
diff.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <M>b__0_0}");
diff.VerifyIL("C.M",
@"
{
// Code size 48 (0x30)
.maxstack 3
.locals init ([unchanged] V_0,
System.Func<int, int, int> V_1) //x
IL_0000: nop
IL_0001: ldsfld ""System.Func<int, int, int> C.<>c.<>9__0_0""
IL_0006: dup
IL_0007: brtrue.s IL_0020
IL_0009: pop
IL_000a: ldsfld ""C.<>c C.<>c.<>9""
IL_000f: ldftn ""int C.<>c.<M>b__0_0(int, int)""
IL_0015: newobj ""System.Func<int, int, int>..ctor(object, System.IntPtr)""
IL_001a: dup
IL_001b: stsfld ""System.Func<int, int, int> C.<>c.<>9__0_0""
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldc.i4.1
IL_0023: ldc.i4.2
IL_0024: callvirt ""int System.Func<int, int, int>.Invoke(int, int)""
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: nop
IL_002f: ret
}");
diff.VerifyIL("C.<>c.<M>b__0_0(int, int)", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldc.i4.s 10
IL_0002: ret
}");
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers
{
internal static class CastSimplifier
{
public static bool IsUnnecessaryCast(ExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> cast is CastExpressionSyntax castExpression ? IsUnnecessaryCast(castExpression, semanticModel, cancellationToken) :
cast is BinaryExpressionSyntax binaryExpression ? IsUnnecessaryAsCast(binaryExpression, semanticModel, cancellationToken) : false;
public static bool IsUnnecessaryCast(CastExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> IsCastSafeToRemove(cast, cast.Expression, semanticModel, cancellationToken);
public static bool IsUnnecessaryAsCast(BinaryExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> cast.Kind() == SyntaxKind.AsExpression &&
IsCastSafeToRemove(cast, cast.Left, semanticModel, cancellationToken);
private static bool IsCastSafeToRemove(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
var speculationAnalyzer = new SpeculationAnalyzer(castNode,
castedExpressionNode, semanticModel, cancellationToken,
skipVerificationForReplacedNode: true, failOnOverloadResolutionFailuresInOriginalCode: true);
// First, check to see if the node ultimately parenting this cast has any
// syntax errors. If so, we bail.
if (speculationAnalyzer.SemanticRootOfOriginalExpression.ContainsDiagnostics)
return false;
// Now perform basic checks looking for a few things:
//
// 1. casts that must stay because removal will produce actually illegal code.
// 2. casts that must stay because they have runtime impact (i.e. could cause exceptions to be thrown).
// 3. casts that *seem* unnecessary because they don't violate the above, and the cast seems like it has no
// effect at runtime (i.e. casting a `string` to `object`). Note: just because the cast seems like it
// will have not runtime impact doesn't mean we can remove it. It still may be necessary to preserve the
// meaning of the code (for example for overload resolution). That check will occur after this.
//
// This is the fundamental separation between CastHasNoRuntimeImpact and
// speculationAnalyzer.ReplacementChangesSemantics. The former is simple and is only asking if the cast
// seems like it would have no impact *at runtime*. The latter ensures that the static meaning of the code
// is preserved.
//
// When adding/updating checks keep the above in mind to determine where the check should go.
var castHasRuntimeImpact = CastHasRuntimeImpact(
speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken);
if (castHasRuntimeImpact)
return false;
// Cast has no runtime effect. But it may change static semantics. Only allow removal if static semantics
// don't change.
if (speculationAnalyzer.ReplacementChangesSemantics())
return false;
return true;
}
private static bool CastHasRuntimeImpact(
SpeculationAnalyzer speculationAnalyzer,
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Look for simple patterns we know will never cause any runtime changes.
if (CastDefinitelyHasNoRuntimeImpact(castNode, castedExpressionNode, semanticModel, cancellationToken))
return false;
// Call into our legacy codepath that tries to make the same determination.
return !CastHasNoRuntimeImpact_Legacy(speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken);
}
private static bool CastDefinitelyHasNoRuntimeImpact(
ExpressionSyntax castNode,
ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// NOTE: Keep this method simple. Each type of runtime impact check should just be a new check added
// independently from the rest. We want to make it very clear exactly which cases each check is covering.
// castNode is: `(Type)expr` or `expr as Type`.
// castedExpressionnode is: `expr`
// The type in `(Type)...` or `... as Type`
var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type;
// The type in `(...)expr` or `expr as ...`
var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type;
// $"x {(object)y} z" It's always safe to remove this `(object)` cast as this cast happens automatically.
if (IsObjectCastInInterpolation(castNode, castType))
return true;
// if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~`
if (IsEnumToNumericCastThatCanDefinitelyBeRemoved(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
return false;
}
private static bool CastHasNoRuntimeImpact_Legacy(
SpeculationAnalyzer speculationAnalyzer,
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Note: Legacy codepaths for determining if a cast is removable. As much as possible we should attempt to
// extract simple and clearly defined checks from here and move to CastDefinitelyHasNoRuntimeImpact.
// Then look for patterns for cases where we never want to remove casts.
if (CastMustBePreserved(castNode, castedExpressionNode, semanticModel, cancellationToken))
return false;
// If this changes static semantics (i.e. causes a different overload to be called), then we can't remove it.
if (speculationAnalyzer.ReplacementChangesSemantics())
return false;
var castTypeInfo = semanticModel.GetTypeInfo(castNode, cancellationToken);
var castType = castTypeInfo.Type;
RoslynDebug.AssertNotNull(castType);
var expressionTypeInfo = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken);
var expressionType = expressionTypeInfo.Type;
var expressionToCastType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true);
var outerType = GetOuterCastType(castNode, semanticModel, out var parentIsOrAsExpression) ?? castTypeInfo.ConvertedType;
// Clearest case. We know we haven't changed static semantic, and we have an Identity (i.e. no-impact,
// representation-preserving) cast. This is always safe to remove.
//
// Note: while these casts are always safe to remove, there is a case where we still keep them.
// Specifically, if the compiler would warn that the code is no longer clear, then we will keep the cast
// around. These warning checks should go into CastMustBePreserved above.
if (expressionToCastType.IsIdentity)
return true;
// Is this a cast inside a conditional expression? Because of target typing we already sorted that out
// in ReplacementChangesSemantics()
if (IsBranchOfConditionalExpression(castNode))
{
return true;
}
// We already bailed out of we had an explicit/none conversions back in CastMustBePreserved
// (except for implicit user defined conversions).
Debug.Assert(!expressionToCastType.IsExplicit || expressionToCastType.IsUserDefined);
// At this point, the only type of conversion left are implicit or user-defined conversions. These may be
// conversions we can remove, but need further analysis.
Debug.Assert(expressionToCastType.IsImplicit || expressionToCastType.IsUserDefined);
if (expressionToCastType.IsInterpolatedString)
{
// interpolation casts are necessary to preserve semantics if our destination type is not itself
// FormattableString or some interface of FormattableString.
return castType.Equals(castTypeInfo.ConvertedType) ||
ImmutableArray<ITypeSymbol?>.CastUp(castType.AllInterfaces).Contains(castTypeInfo.ConvertedType);
}
if (castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.DefaultLiteralExpression) &&
!castType.Equals(outerType) &&
outerType.IsNullable())
{
// We have a cast like `(T?)(X)default`. We can't remove the inner cast as it effects what value
// 'default' means in this context.
return false;
}
if (parentIsOrAsExpression)
{
// Note: speculationAnalyzer.ReplacementChangesSemantics() ensures that the parenting is or as expression are not broken.
// Here we just need to ensure that the original cast expression doesn't invoke a user defined operator.
return !expressionToCastType.IsUserDefined;
}
if (outerType != null)
{
var castToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castNode, outerType);
var expressionToOuterType = GetSpeculatedExpressionToOuterTypeConversion(speculationAnalyzer.ReplacedExpression, speculationAnalyzer, cancellationToken);
// if the conversion to the outer type doesn't exist, then we shouldn't offer, except for anonymous functions which can't be reasoned about the same way (see below)
if (!expressionToOuterType.Exists && !expressionToOuterType.IsAnonymousFunction)
{
return false;
}
// CONSIDER: Anonymous function conversions cannot be compared from different semantic models as lambda symbol comparison requires syntax tree equality. Should this be a compiler bug?
// For now, just revert back to computing expressionToOuterType using the original semantic model.
if (expressionToOuterType.IsAnonymousFunction)
{
expressionToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, outerType);
}
// If there is an user-defined conversion from the expression to the cast type or the cast
// to the outer type, we need to make sure that the same user-defined conversion will be
// called if the cast is removed.
if (castToOuterType.IsUserDefined || expressionToCastType.IsUserDefined)
{
return !expressionToOuterType.IsExplicit &&
(HaveSameUserDefinedConversion(expressionToCastType, expressionToOuterType) ||
HaveSameUserDefinedConversion(castToOuterType, expressionToOuterType)) &&
UserDefinedConversionIsAllowed(castNode);
}
else if (expressionToOuterType.IsUserDefined)
{
return false;
}
if (expressionToCastType.IsExplicit &&
expressionToOuterType.IsExplicit)
{
return false;
}
// If the conversion from the expression to the cast type is implicit numeric or constant
// and the conversion from the expression to the outer type is identity, we'll go ahead
// and remove the cast.
if (expressionToOuterType.IsIdentity &&
expressionToCastType.IsImplicit &&
(expressionToCastType.IsNumeric || expressionToCastType.IsConstantExpression))
{
RoslynDebug.AssertNotNull(expressionType);
// Some implicit numeric conversions can cause loss of precision and must not be removed.
return !IsRequiredImplicitNumericConversion(expressionType, castType);
}
if (!castToOuterType.IsBoxing &&
castToOuterType == expressionToOuterType)
{
if (castToOuterType.IsNullable)
{
// Even though both the nullable conversions (castToOuterType and expressionToOuterType) are equal, we can guarantee no data loss only if there is an
// implicit conversion from expression type to cast type and expression type is non-nullable. For example, consider the cast removal "(float?)" for below:
// Console.WriteLine((int)(float?)(int?)2147483647); // Prints -2147483648
// castToOuterType: ExplicitNullable
// expressionToOuterType: ExplicitNullable
// expressionToCastType: ImplicitNullable
// We should not remove the cast to "float?".
// However, cast to "int?" is unnecessary and should be removable.
return expressionToCastType.IsImplicit && !expressionType.IsNullable();
}
else if (expressionToCastType.IsImplicit && expressionToCastType.IsNumeric && !castToOuterType.IsIdentity)
{
RoslynDebug.AssertNotNull(expressionType);
// Some implicit numeric conversions can cause loss of precision and must not be removed.
return !IsRequiredImplicitNumericConversion(expressionType, castType);
}
return true;
}
if (castToOuterType.IsIdentity &&
!expressionToCastType.IsUnboxing &&
expressionToCastType == expressionToOuterType)
{
return true;
}
// Special case: It's possible to have useless casts inside delegate creation expressions.
// For example: new Func<string, bool>((Predicate<object>)(y => true)).
if (IsInDelegateCreationExpression(castNode, semanticModel))
{
if (expressionToCastType.IsAnonymousFunction && expressionToOuterType.IsAnonymousFunction)
{
return !speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression);
}
if (expressionToCastType.IsMethodGroup && expressionToOuterType.IsMethodGroup)
{
return true;
}
}
// Case :
// 1. IList<object> y = (IList<dynamic>)new List<object>()
if (expressionToCastType.IsExplicit && castToOuterType.IsExplicit && expressionToOuterType.IsImplicit)
{
// If both expressionToCastType and castToOuterType are numeric, then this is a required cast as one of the conversions leads to loss of precision.
// Cast removal can change program behavior.
return !(expressionToCastType.IsNumeric && castToOuterType.IsNumeric);
}
// Case :
// 2. object y = (ValueType)1;
if (expressionToCastType.IsBoxing && expressionToOuterType.IsBoxing && castToOuterType.IsImplicit)
{
return true;
}
// Case :
// 3. object y = (NullableValueType)null;
if ((!castToOuterType.IsBoxing || expressionToCastType.IsNullLiteral) &&
castToOuterType.IsImplicit &&
expressionToCastType.IsImplicit &&
expressionToOuterType.IsImplicit)
{
if (expressionToOuterType.IsAnonymousFunction)
{
return expressionToCastType.IsAnonymousFunction &&
!speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression);
}
return true;
}
}
return false;
}
private static bool IsObjectCastInInterpolation(ExpressionSyntax castNode, [NotNullWhen(true)] ITypeSymbol? castType)
{
// A casts to object can always be removed from an expression inside of an interpolation, since it'll be converted to object
// in order to call string.Format(...) anyway.
return castType?.SpecialType == SpecialType.System_Object &&
castNode.WalkUpParentheses().IsParentKind(SyntaxKind.Interpolation);
}
private static bool IsEnumToNumericCastThatCanDefinitelyBeRemoved(
ExpressionSyntax castNode,
[NotNullWhen(true)] ITypeSymbol? castType,
[NotNullWhen(true)] ITypeSymbol? castedExpressionType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (!castedExpressionType.IsEnumType(out var castedEnumType))
return false;
if (!Equals(castType, castedEnumType.EnumUnderlyingType))
return false;
// if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~`.
castNode = castNode.WalkUpParentheses();
if (castNode.IsParentKind(SyntaxKind.BitwiseNotExpression, out PrefixUnaryExpressionSyntax? prefixUnary))
{
if (!prefixUnary.WalkUpParentheses().IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax? parentCast))
return false;
// `(int)` in `(E?)~(int)e` is also redundant.
var parentCastType = semanticModel.GetTypeInfo(parentCast.Type, cancellationToken).Type;
if (parentCastType.IsNullable(out var underlyingType))
parentCastType = underlyingType;
return castedEnumType.Equals(parentCastType);
}
// if we have `(int)e == 0` then the cast can be removed. Note: this is only for the exact cast of
// comparing to the constant 0. All other comparisons are not allowed.
if (castNode.Parent is BinaryExpressionSyntax binaryExpression)
{
if (binaryExpression.IsKind(SyntaxKind.EqualsExpression) || binaryExpression.IsKind(SyntaxKind.NotEqualsExpression))
{
var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left;
var otherSideType = semanticModel.GetTypeInfo(otherSide, cancellationToken).Type;
if (Equals(otherSideType, castedEnumType.EnumUnderlyingType))
{
var constantValue = semanticModel.GetConstantValue(otherSide, cancellationToken);
if (constantValue.HasValue &&
IntegerUtilities.IsIntegral(constantValue.Value) &&
IntegerUtilities.ToInt64(constantValue.Value) == 0)
{
return true;
}
}
}
}
return false;
}
private static bool CastMustBePreserved(
ExpressionSyntax castNode,
ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// castNode is: `(Type)expr` or `expr as Type`.
// castedExpressionnode is: `expr`
// The type in `(Type)...` or `... as Type`
var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type;
// If we don't understand the type, we must keep it.
if (castType == null)
return true;
// The type in `(...)expr` or `expr as ...`
var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type;
var conversion = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true);
// If we've got an error for some reason, then we don't want to touch this at all.
if (castType.IsErrorType())
return true;
// Almost all explicit conversions can cause an exception or data loss, hence can never be removed.
if (IsExplicitCastThatMustBePreserved(castNode, conversion))
return true;
// If this conversion doesn't even exist, then this code is in error, and we don't want to touch it.
if (!conversion.Exists)
return true;
// `dynamic` changes the semantics of everything and is rarely safe to remove. We could consider removing
// absolutely safe casts (i.e. `(dynamic)(dynamic)a`), but it's likely not worth the effort, so we just
// disallow touching them entirely.
if (InvolvesDynamic(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
// If removing the cast would cause the compiler to issue a specific warning, then we have to preserve it.
if (CastRemovalWouldCauseSignExtensionWarning(castNode, semanticModel, cancellationToken))
return true;
// *(T*)null. Can't remove this case.
if (IsDereferenceOfNullPointerCast(castNode, castedExpressionNode))
return true;
if (ParamsArgumentCastMustBePreserved(castNode, castType, semanticModel, cancellationToken))
return true;
// `... ? (int?)1 : default`. This cast is necessary as the 'null/default' on the other side of the
// conditional can change meaning since based on the type on the other side.
//
// TODO(cyrusn): This should move into SpeculationAnalyzer as it's a static-semantics change.
if (CastMustBePreservedInConditionalBranch(castNode, conversion))
return true;
// (object)"" == someObj
//
// This cast can be removed with no runtime or static-semantics change. However, the compiler warns here
// that this could be confusing (since it's not clear it's calling `==(object,object)` instead of
// `==(string,string)`), so we have to preserve this.
if (CastIsRequiredToPreventUnintendedComparisonWarning(castNode, castedExpressionNode, castType, semanticModel, cancellationToken))
return true;
// Identity fp-casts can actually change the runtime value of the fp number. This can happen because the
// runtime is allowed to perform the operations with wider precision than the actual specified fp-precision.
// i.e. 64-bit doubles can actually be 80 bits at runtime. Even though the language considers this to be an
// identity cast, we don't want to remove these because the user may be depending on that truncation.
RoslynDebug.Assert(!conversion.IsIdentity || castedExpressionType is not null);
if (IdentityFloatingPointCastMustBePreserved(castNode, castedExpressionNode, castType, castedExpressionType!, semanticModel, conversion, cancellationToken))
return true;
if (PointerOrIntPtrCastMustBePreserved(conversion))
return true;
// If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can
// be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't
// even bother removing this.
if (IsTypeLessExpressionNotInTargetTypedLocation(castNode, castedExpressionType))
return true;
// If we have something like `(nuint)(nint)x` where x is an IntPtr then the nint cast cannot be removed
// as IntPtr to nuint is invalid.
if (IsIntPtrToNativeIntegerNestedCast(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
// If we have `~(ulong)uintVal` then we have to preserve the `(ulong)` cast. Otherwise, the `~` will
// operate on the shorter-bit value, before being extended out to the full length, rather than operating on
// the full length.
if (IsBitwiseNotOfExtendedUnsignedValue(castNode, conversion, castType, castedExpressionType))
return true;
return false;
}
private static bool IsBitwiseNotOfExtendedUnsignedValue(ExpressionSyntax castNode, Conversion conversion, ITypeSymbol castType, ITypeSymbol castedExressionType)
{
if (castNode.WalkUpParentheses().IsParentKind(SyntaxKind.BitwiseNotExpression) &&
conversion.IsImplicit &&
conversion.IsNumeric)
{
return IsUnsigned(castType) || IsUnsigned(castedExressionType);
}
return false;
}
private static bool IsUnsigned(ITypeSymbol type)
=> type.SpecialType.IsUnsignedIntegralType() || IsNuint(type);
private static bool IsNuint(ITypeSymbol type)
=> type.SpecialType == SpecialType.System_UIntPtr && type.IsNativeIntegerType;
private static bool IsIntPtrToNativeIntegerNestedCast(ExpressionSyntax castNode, ITypeSymbol castType, ITypeSymbol castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (castedExpressionType == null)
{
return false;
}
if (castType.SpecialType is not (SpecialType.System_IntPtr or SpecialType.System_UIntPtr))
{
return false;
}
if (castNode.WalkUpParentheses().Parent is CastExpressionSyntax castExpression)
{
var parentCastType = semanticModel.GetTypeInfo(castExpression, cancellationToken).Type;
if (parentCastType == null)
{
return false;
}
// Given (nuint)(nint)myIntPtr we would normally suggest removing the (nint) cast as being identity
// but it is required as a means to get from IntPtr to nuint, and vice versa from UIntPtr to nint,
// so we check for an identity cast from [U]IntPtr to n[u]int and then to a number type.
if (castedExpressionType.SpecialType == castType.SpecialType &&
!castedExpressionType.IsNativeIntegerType &&
castType.IsNativeIntegerType &&
parentCastType.IsNumericType())
{
return true;
}
}
return false;
}
private static bool IsTypeLessExpressionNotInTargetTypedLocation(ExpressionSyntax castNode, [NotNullWhen(false)] ITypeSymbol? castedExpressionType)
{
// If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can
// be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't
// even bother removing this.
// checked if the expression being casted is typeless.
if (castedExpressionType != null)
return false;
if (IsInTargetTypingLocation(castNode))
return false;
// we don't have our own type, and we're not in a location where a type can be inferred. don't remove this
// cast.
return true;
}
private static bool IsInTargetTypingLocation(ExpressionSyntax node)
{
node = node.WalkUpParentheses();
var parent = node.Parent;
// note: the list below is not intended to be exhaustive. For example there are places we can target type,
// but which we don't want to bother doing all the work to validate. For example, technically you can
// target type `throw (Exception)null`, so we could allow `(Exception)` to be removed. But it's such a corner
// case that we don't care about supporting, versus all the hugely valuable cases users will actually run into.
// also: the list doesn't have to be firmly accurate:
// 1. If we have a false positive and we say something is a target typing location, then that means we
// simply try to remove the cast, but then catch the break later.
// 2. If we have a false negative and we say something is not a target typing location, then we simply
// don't try to remove the cast and the user has no impact on their code.
// `null op e2`. Either side can target type the other.
if (parent is BinaryExpressionSyntax)
return true;
// `Goo(null)`. The type of the arg is target typed by the Goo method being called.
//
// This also helps Tuples fall out as they're built of arguments. i.e. `(string s, string y) = (null, null)`.
if (parent is ArgumentSyntax)
return true;
// same as above
if (parent is AttributeArgumentSyntax)
return true;
// `new SomeType[] { null }` or `new [] { null, expr }`.
// Type of the element can be target typed by the array type, or the sibling expression types.
if (parent is InitializerExpressionSyntax)
return true;
// `return null;`. target typed by whatever method this is in.
if (parent is ReturnStatementSyntax)
return true;
// `yield return null;` same as above.
if (parent is YieldStatementSyntax)
return true;
// `x = null`. target typed by the other side.
if (parent is AssignmentExpressionSyntax)
return true;
// ... = null
//
// handles: parameters, variable declarations and the like.
if (parent is EqualsValueClauseSyntax)
return true;
// `(SomeType)null`. Definitely can target type this type-less expression.
if (parent is CastExpressionSyntax)
return true;
// `... ? null : ...`. Either side can target type the other.
if (parent is ConditionalExpressionSyntax)
return true;
// case null:
if (parent is CaseSwitchLabelSyntax)
return true;
return false;
}
private static bool IsExplicitCastThatMustBePreserved(ExpressionSyntax castNode, Conversion conversion)
{
if (conversion.IsExplicit)
{
// Consider the explicit cast in a line like:
//
// string? s = conditional ? (string?)"hello" : null;
//
// That string? cast is an explicit conversion that not IsUserDefined, but it may be removable if we support
// target-typed conditionals; in that case we'll return false here and force the full algorithm to be ran rather
// than this fast-path.
if (IsBranchOfConditionalExpression(castNode) &&
!CastMustBePreservedInConditionalBranch(castNode, conversion))
{
return false;
}
// if it's not a user defined conversion, we must preserve it as it has runtime impact that we don't want to change.
if (!conversion.IsUserDefined)
return true;
// Casts that involve implicit conversions are still represented as explicit casts. Because they're
// implicit though, we may be able to remove it. i.e. if we have `(C)0 + (C)1` we can remove one of the
// casts because it will be inferred from the binary context.
var userMethod = conversion.MethodSymbol;
if (userMethod?.Name != WellKnownMemberNames.ImplicitConversionName)
return true;
}
return false;
}
private static bool PointerOrIntPtrCastMustBePreserved(Conversion conversion)
{
if (!conversion.IsIdentity)
return false;
// if we have a non-identity cast to an int* or IntPtr just do not touch this.
// https://github.com/dotnet/roslyn/issues/2987 tracks improving on this conservative approach.
//
// NOTE(cyrusn): This code should not be necessary. However there is additional code that deals with
// `*(x*)expr` ends up masking that this change should not be safe. That code is suspect and should be
// changed. Until then though we disable this.
return conversion.IsPointer || conversion.IsIntPtr;
}
private static bool InvolvesDynamic(
ExpressionSyntax castNode,
ITypeSymbol? castType,
ITypeSymbol? castedExpressionType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// We do not remove any cast on
// 1. Dynamic Expressions
// 2. If there is any other argument which is dynamic
// 3. Dynamic Invocation
// 4. Assignment to dynamic
if (castType?.Kind == SymbolKind.DynamicType || castedExpressionType?.Kind == SymbolKind.DynamicType)
return true;
return IsDynamicInvocation(castNode, semanticModel, cancellationToken) ||
IsDynamicAssignment(castNode, semanticModel, cancellationToken);
}
private static bool IsDereferenceOfNullPointerCast(ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode)
{
return castNode.WalkUpParentheses().IsParentKind(SyntaxKind.PointerIndirectionExpression) &&
castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression);
}
private static bool IsBranchOfConditionalExpression(ExpressionSyntax expression)
{
return expression.Parent is ConditionalExpressionSyntax conditionalExpression &&
expression != conditionalExpression.Condition;
}
private static bool CastMustBePreservedInConditionalBranch(
ExpressionSyntax castNode, Conversion conversion)
{
// `... ? (int?)i : default`. This cast is necessary as the 'null/default' on the other side of the
// conditional can change meaning since based on the type on the other side.
// It's safe to remove the cast when it's an identity. for example:
// `... ? (int)1 : default`.
if (!conversion.IsIdentity)
{
castNode = castNode.WalkUpParentheses();
if (castNode.Parent is ConditionalExpressionSyntax conditionalExpression)
{
if (conditionalExpression.WhenTrue == castNode ||
conditionalExpression.WhenFalse == castNode)
{
var otherSide = conditionalExpression.WhenTrue == castNode
? conditionalExpression.WhenFalse
: conditionalExpression.WhenTrue;
otherSide = otherSide.WalkDownParentheses();
// In C# 9 we can potentially remove the cast if the other side is null, since the cast was previously required to
// resolve a situation like:
//
// var x = condition ? (int?)i : null
//
// but it isn't with target-typed conditionals. We do have to keep the cast if it's default, as:
//
// var x = condition ? (int?)i : default
//
// is inferred by the compiler to mean 'default(int?)', whereas removing the cast would mean default(int).
var languageVersion = ((CSharpParseOptions)castNode.SyntaxTree.Options).LanguageVersion;
return (otherSide.IsKind(SyntaxKind.NullLiteralExpression) && languageVersion < LanguageVersion.CSharp9) ||
otherSide.IsKind(SyntaxKind.DefaultLiteralExpression);
}
}
}
return false;
}
private static bool CastRemovalWouldCauseSignExtensionWarning(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Logic copied from DiagnosticsPass_Warnings.CheckForBitwiseOrSignExtend. Including comments.
if (!(expression is CastExpressionSyntax castExpression))
return false;
var castRoot = castExpression.WalkUpParentheses();
// Check both binary-or, and assignment-or
//
// x | (...)y
// x |= (...)y
ExpressionSyntax leftOperand, rightOperand;
if (castRoot.Parent is BinaryExpressionSyntax parentBinary)
{
if (!parentBinary.IsKind(SyntaxKind.BitwiseOrExpression))
return false;
(leftOperand, rightOperand) = (parentBinary.Left, parentBinary.Right);
}
else if (castRoot.Parent is AssignmentExpressionSyntax parentAssignment)
{
if (!parentAssignment.IsKind(SyntaxKind.OrAssignmentExpression))
return false;
(leftOperand, rightOperand) = (parentAssignment.Left, parentAssignment.Right);
}
else
{
return false;
}
// The native compiler skips this warning if both sides of the operator are constants.
//
// CONSIDER: Is that sensible? It seems reasonable that if we would warn on int | short
// when they are non-constants, or when one is a constant, that we would similarly warn
// when both are constants.
var constantValue = semanticModel.GetConstantValue(castRoot.Parent, cancellationToken);
if (constantValue.HasValue && constantValue.Value != null)
return false;
// Start by determining *which bits on each side are going to be unexpectedly turned on*.
var leftOperation = semanticModel.GetOperation(leftOperand.WalkDownParentheses(), cancellationToken);
var rightOperation = semanticModel.GetOperation(rightOperand.WalkDownParentheses(), cancellationToken);
if (leftOperation == null || rightOperation == null)
return false;
// Note: we are asking the question about if there would be a problem removing the cast. So we have to act
// as if an explicit cast becomes an implicit one. We do this by ignoring the appropriate cast and not
// treating it as explicit when we encounter it.
var left = FindSurprisingSignExtensionBits(leftOperation, leftOperand == castRoot);
var right = FindSurprisingSignExtensionBits(rightOperation, rightOperand == castRoot);
// If they are all the same then there's no warning to give.
if (left == right)
return false;
// Suppress the warning if one side is a constant, and either all the unexpected
// bits are already off, or all the unexpected bits are already on.
var constVal = GetConstantValueForBitwiseOrCheck(leftOperation);
if (constVal != null)
{
var val = constVal.Value;
if ((val & right) == right || (~val & right) == right)
return false;
}
constVal = GetConstantValueForBitwiseOrCheck(rightOperation);
if (constVal != null)
{
var val = constVal.Value;
if ((val & left) == left || (~val & left) == left)
return false;
}
// This would produce a warning. Don't offer to remove the cast.
return true;
}
private static ulong? GetConstantValueForBitwiseOrCheck(IOperation operation)
{
// We might have a nullable conversion on top of an integer constant. But only dig out
// one level.
if (operation is IConversionOperation conversion &&
conversion.Conversion.IsImplicit &&
conversion.Conversion.IsNullable)
{
operation = conversion.Operand;
}
var constantValue = operation.ConstantValue;
if (!constantValue.HasValue || constantValue.Value == null)
return null;
RoslynDebug.Assert(operation.Type is not null);
if (!operation.Type.SpecialType.IsIntegralType())
return null;
return IntegerUtilities.ToUInt64(constantValue.Value);
}
// A "surprising" sign extension is:
//
// * a conversion with no cast in source code that goes from a smaller
// signed type to a larger signed or unsigned type.
//
// * an conversion (with or without a cast) from a smaller
// signed type to a larger unsigned type.
private static ulong FindSurprisingSignExtensionBits(IOperation? operation, bool treatExplicitCastAsImplicit)
{
if (!(operation is IConversionOperation conversion))
return 0;
var from = conversion.Operand.Type;
var to = conversion.Type;
if (from is null || to is null)
return 0;
if (from.IsNullable(out var fromUnderlying))
from = fromUnderlying;
if (to.IsNullable(out var toUnderlying))
to = toUnderlying;
var fromSpecialType = from.SpecialType;
var toSpecialType = to.SpecialType;
if (!fromSpecialType.IsIntegralType() || !toSpecialType.IsIntegralType())
return 0;
var fromSize = fromSpecialType.SizeInBytes();
var toSize = toSpecialType.SizeInBytes();
if (fromSize == 0 || toSize == 0)
return 0;
// The operand might itself be a conversion, and might be contributing
// surprising bits. We might have more, fewer or the same surprising bits
// as the operand.
var recursive = FindSurprisingSignExtensionBits(conversion.Operand, treatExplicitCastAsImplicit: false);
if (fromSize == toSize)
{
// No change.
return recursive;
}
if (toSize < fromSize)
{
// We are casting from a larger type to a smaller type, and are therefore
// losing surprising bits.
switch (toSize)
{
case 1: return unchecked((ulong)(byte)recursive);
case 2: return unchecked((ulong)(ushort)recursive);
case 4: return unchecked((ulong)(uint)recursive);
}
Debug.Assert(false, "How did we get here?");
return recursive;
}
// We are converting from a smaller type to a larger type, and therefore might
// be adding surprising bits. First of all, the smaller type has got to be signed
// for there to be sign extension.
var fromSigned = fromSpecialType.IsSignedIntegralType();
if (!fromSigned)
return recursive;
// OK, we know that the "from" type is a signed integer that is smaller than the
// "to" type, so we are going to have sign extension. Is it surprising? The only
// time that sign extension is *not* surprising is when we have a cast operator
// to a *signed* type. That is, (int)myShort is not a surprising sign extension.
var explicitInCode = !conversion.IsImplicit;
if (!treatExplicitCastAsImplicit &&
explicitInCode &&
toSpecialType.IsSignedIntegralType())
{
return recursive;
}
// Note that we *could* be somewhat more clever here. Consider the following edge case:
//
// (ulong)(int)(uint)(ushort)mySbyte
//
// We could reason that the sbyte-to-ushort conversion is going to add one byte of
// unexpected sign extension. The conversion from ushort to uint adds no more bytes.
// The conversion from uint to int adds no more bytes. Does the conversion from int
// to ulong add any more bytes of unexpected sign extension? Well, no, because we
// know that the previous conversion from ushort to uint will ensure that the top bit
// of the uint is off!
//
// But we are not going to try to be that clever. In the extremely unlikely event that
// someone does this, we will record that the unexpectedly turned-on bits are
// 0xFFFFFFFF0000FF00, even though we could in theory deduce that only 0x000000000000FF00
// are the unexpected bits.
var result = recursive;
for (var i = fromSize; i < toSize; ++i)
result |= (0xFFUL) << (i * 8);
return result;
}
private static bool IdentityFloatingPointCastMustBePreserved(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
ITypeSymbol castType, ITypeSymbol castedExpressionType,
SemanticModel semanticModel, Conversion conversion, CancellationToken cancellationToken)
{
if (!conversion.IsIdentity)
return false;
// Floating point casts can have subtle runtime behavior, even between the same fp types. For example, a
// cast from float-to-float can still change behavior because it may take a higher precision computation and
// truncate it to 32bits.
//
// Because of this we keep floating point conversions unless we can prove that it's safe. The only safe
// times are when we're loading or storing into a location we know has the same size as the cast size
// (i.e. reading/writing into a field).
if (castedExpressionType.SpecialType != SpecialType.System_Double &&
castedExpressionType.SpecialType != SpecialType.System_Single &&
castType.SpecialType != SpecialType.System_Double &&
castType.SpecialType != SpecialType.System_Single)
{
// wasn't a floating point conversion.
return false;
}
// Identity fp conversion is safe if this is a read from a fp field/array
if (IsFieldOrArrayElement(semanticModel, castedExpressionNode, cancellationToken))
return false;
castNode = castNode.WalkUpParentheses();
if (castNode.Parent is AssignmentExpressionSyntax assignmentExpression &&
assignmentExpression.Right == castNode)
{
// Identity fp conversion is safe if this is a write to a fp field/array
if (IsFieldOrArrayElement(semanticModel, assignmentExpression.Left, cancellationToken))
return false;
}
else if (castNode.Parent.IsKind(SyntaxKind.ArrayInitializerExpression, out InitializerExpressionSyntax? arrayInitializer))
{
// Identity fp conversion is safe if this is in an array initializer.
var typeInfo = semanticModel.GetTypeInfo(arrayInitializer, cancellationToken);
return typeInfo.Type?.Kind == SymbolKind.ArrayType;
}
else if (castNode.Parent is EqualsValueClauseSyntax equalsValue &&
equalsValue.Value == castNode &&
equalsValue.Parent is VariableDeclaratorSyntax variableDeclarator)
{
// Identity fp conversion is safe if this is in a field initializer.
var symbol = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
if (symbol?.Kind == SymbolKind.Field)
return false;
}
// We have to preserve this cast.
return true;
}
private static bool IsFieldOrArrayElement(
SemanticModel semanticModel, ExpressionSyntax expr, CancellationToken cancellationToken)
{
expr = expr.WalkDownParentheses();
var castedExpresionSymbol = semanticModel.GetSymbolInfo(expr, cancellationToken).Symbol;
// we're reading from a field of the same size. it's safe to remove this case.
if (castedExpresionSymbol?.Kind == SymbolKind.Field)
return true;
if (expr is ElementAccessExpressionSyntax elementAccess)
{
var locationType = semanticModel.GetTypeInfo(elementAccess.Expression, cancellationToken);
return locationType.Type?.Kind == SymbolKind.ArrayType;
}
return false;
}
private static bool HaveSameUserDefinedConversion(Conversion conversion1, Conversion conversion2)
{
return conversion1.IsUserDefined
&& conversion2.IsUserDefined
&& Equals(conversion1.MethodSymbol, conversion2.MethodSymbol);
}
private static bool IsInDelegateCreationExpression(
ExpressionSyntax castNode, SemanticModel semanticModel)
{
if (!(castNode.WalkUpParentheses().Parent is ArgumentSyntax argument))
{
return false;
}
if (!(argument.Parent is ArgumentListSyntax argumentList))
{
return false;
}
if (!(argumentList.Parent is ObjectCreationExpressionSyntax objectCreation))
{
return false;
}
var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type).Symbol;
return typeSymbol != null
&& typeSymbol.IsDelegateType();
}
private static bool IsDynamicInvocation(
ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (castExpression.WalkUpParentheses().IsParentKind(SyntaxKind.Argument, out ArgumentSyntax? argument) &&
argument.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList) &&
argument.Parent.Parent.IsKind(SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression))
{
var typeInfo = semanticModel.GetTypeInfo(argument.Parent.Parent, cancellationToken);
return typeInfo.Type?.Kind == SymbolKind.DynamicType;
}
return false;
}
private static bool IsDynamicAssignment(ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
castExpression = castExpression.WalkUpParentheses();
if (castExpression.IsRightSideOfAnyAssignExpression())
{
var assignmentExpression = (AssignmentExpressionSyntax)castExpression.Parent!;
var assignmentType = semanticModel.GetTypeInfo(assignmentExpression.Left, cancellationToken).Type;
return assignmentType?.Kind == SymbolKind.DynamicType;
}
return false;
}
private static bool IsRequiredImplicitNumericConversion(ITypeSymbol sourceType, ITypeSymbol destinationType)
{
// C# Language Specification: Section 6.1.2 Implicit numeric conversions
// Conversions from int, uint, long, or ulong to float and from long or ulong to double may cause a loss of precision,
// but will never cause a loss of magnitude. The other implicit numeric conversions never lose any information.
switch (destinationType.SpecialType)
{
case SpecialType.System_Single:
switch (sourceType.SpecialType)
{
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
return true;
default:
return false;
}
case SpecialType.System_Double:
switch (sourceType.SpecialType)
{
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
return true;
default:
return false;
}
default:
return false;
}
}
private static bool CastIsRequiredToPreventUnintendedComparisonWarning(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, ITypeSymbol castType,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Based on the check in DiagnosticPass.CheckRelationals.
// (object)"" == someObj
//
// This cast can be removed with no runtime or static-semantics change. However, the compiler warns here
// that this could be confusing (since it's not clear it's calling `==(object,object)` instead of
// `==(string,string)`), so we have to preserve this.
// compiler: if (node.Left.Type.SpecialType == SpecialType.System_Object
if (castType?.SpecialType != SpecialType.System_Object)
return false;
// compiler: node.OperatorKind == BinaryOperatorKind.ObjectEqual || node.OperatorKind == BinaryOperatorKind.ObjectNotEqual
castNode = castNode.WalkUpParentheses();
var parent = castNode.Parent;
if (!(parent is BinaryExpressionSyntax binaryExpression))
return false;
if (!binaryExpression.IsKind(SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression))
return false;
var binaryMethod = semanticModel.GetSymbolInfo(binaryExpression, cancellationToken).Symbol as IMethodSymbol;
if (binaryMethod == null)
return false;
if (binaryMethod.ContainingType?.SpecialType != SpecialType.System_Object)
return false;
var operatorName = binaryMethod.Name;
if (operatorName != WellKnownMemberNames.EqualityOperatorName && operatorName != WellKnownMemberNames.InequalityOperatorName)
return false;
// compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t))
var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left;
otherSide = otherSide.WalkDownParentheses();
return CastIsRequiredToPreventUnintendedComparisonWarning(castedExpressionNode, otherSide, operatorName, semanticModel, cancellationToken) ||
CastIsRequiredToPreventUnintendedComparisonWarning(otherSide, castedExpressionNode, operatorName, semanticModel, cancellationToken);
}
private static bool CastIsRequiredToPreventUnintendedComparisonWarning(
ExpressionSyntax left, ExpressionSyntax right, string operatorName,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// compiler: node.Left.Type.SpecialType == SpecialType.System_Object
var leftType = semanticModel.GetTypeInfo(left, cancellationToken).Type;
if (leftType?.SpecialType != SpecialType.System_Object)
return false;
// compiler: && !IsExplicitCast(node.Left)
if (left.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression))
return false;
// compiler: && !(node.Left.ConstantValue != null && node.Left.ConstantValue.IsNull)
var constantValue = semanticModel.GetConstantValue(left, cancellationToken);
if (constantValue.HasValue && constantValue.Value is null)
return false;
// compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t))
// Code for: ConvertedHasEqual
// compiler: if (conv.ExplicitCastInCode) return false;
if (right.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression))
return false;
// compiler: NamedTypeSymbol nt = conv.Operand.Type as NamedTypeSymbol;
// if ((object)nt == null || !nt.IsReferenceType || nt.IsInterface)
var otherSideType = semanticModel.GetTypeInfo(right, cancellationToken).Type as INamedTypeSymbol;
if (otherSideType == null)
return false;
if (!otherSideType.IsReferenceType || otherSideType.TypeKind == TypeKind.Interface)
return false;
// compiler: for (var t = nt; (object)t != null; t = t.BaseTypeNoUseSiteDiagnostics)
for (var currentType = otherSideType; currentType != null; currentType = currentType.BaseType)
{
// compiler: foreach (var sym in t.GetMembers(opName))
foreach (var opMember in currentType.GetMembers(operatorName))
{
// compiler: MethodSymbol op = sym as MethodSymbol;
var opMethod = opMember as IMethodSymbol;
// compiler: if ((object)op == null || op.MethodKind != MethodKind.UserDefinedOperator) continue;
if (opMethod == null || opMethod.MethodKind != MethodKind.UserDefinedOperator)
continue;
// compiler: var parameters = op.GetParameters();
// if (parameters.Length == 2 && TypeSymbol.Equals(parameters[0].Type, t, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(parameters[1].Type, t, TypeCompareKind.ConsiderEverything2))
// return true
var parameters = opMethod.Parameters;
if (parameters.Length == 2 && Equals(parameters[0].Type, currentType) && Equals(parameters[1].Type, currentType))
return true;
}
}
return false;
}
private static Conversion GetSpeculatedExpressionToOuterTypeConversion(ExpressionSyntax speculatedExpression, SpeculationAnalyzer speculationAnalyzer, CancellationToken cancellationToken)
{
var typeInfo = speculationAnalyzer.SpeculativeSemanticModel.GetTypeInfo(speculatedExpression, cancellationToken);
var conversion = speculationAnalyzer.SpeculativeSemanticModel.GetConversion(speculatedExpression, cancellationToken);
if (!conversion.IsIdentity)
{
return conversion;
}
var speculatedExpressionOuterType = GetOuterCastType(speculatedExpression, speculationAnalyzer.SpeculativeSemanticModel, out _) ?? typeInfo.ConvertedType;
if (speculatedExpressionOuterType == null)
{
return default;
}
return speculationAnalyzer.SpeculativeSemanticModel.ClassifyConversion(speculatedExpression, speculatedExpressionOuterType);
}
private static bool UserDefinedConversionIsAllowed(ExpressionSyntax expression)
{
expression = expression.WalkUpParentheses();
var parentNode = expression.Parent;
if (parentNode == null)
{
return false;
}
if (parentNode.IsKind(SyntaxKind.ThrowStatement))
{
return false;
}
return true;
}
private static bool ParamsArgumentCastMustBePreserved(
ExpressionSyntax cast,
ITypeSymbol castType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// When a casted value is passed as the single argument to a params parameter,
// we can only remove the cast if it is implicitly convertible to the parameter's type,
// but not the parameter's element type. Otherwise, we could end up changing the invocation
// to pass an array rather than an array with a single element.
//
// IOW, given the following method...
//
// static void Goo(params object[] x) { }
//
// ...we should remove this cast...
//
// Goo((object[])null);
//
// ...but not this cast...
//
// Goo((object)null);
var parent = cast.WalkUpParentheses().Parent;
if (parent is ArgumentSyntax argument)
{
// If there are any arguments to the right (and the argument is not named), we can assume that this is
// not a *single* argument passed to a params parameter.
if (argument.NameColon == null && argument.Parent is BaseArgumentListSyntax argumentList)
{
var argumentIndex = argumentList.Arguments.IndexOf(argument);
if (argumentIndex < argumentList.Arguments.Count - 1)
{
return false;
}
}
var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken);
return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel);
}
if (parent is AttributeArgumentSyntax attributeArgument)
{
if (attributeArgument.Parent is AttributeArgumentListSyntax)
{
// We don't check the position of the argument because in attributes it is allowed that
// params parameter are positioned in between if named arguments are used.
var parameter = attributeArgument.DetermineParameter(semanticModel, cancellationToken: cancellationToken);
return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel);
}
}
return false;
}
private static bool ParameterTypeMatchesParamsElementType([NotNullWhen(true)] IParameterSymbol? parameter, ITypeSymbol castType, SemanticModel semanticModel)
{
if (parameter?.IsParams == true)
{
// if the method is defined with errors: void M(params int wrongDefined), parameter.IsParams == true but parameter.Type is not an array.
// In such cases is better to be conservative and opt out.
if (!(parameter.Type is IArrayTypeSymbol parameterType))
{
return true;
}
var conversion = semanticModel.Compilation.ClassifyConversion(castType, parameterType);
if (conversion.Exists &&
conversion.IsImplicit)
{
return false;
}
var conversionElementType = semanticModel.Compilation.ClassifyConversion(castType, parameterType.ElementType);
if (conversionElementType.Exists &&
conversionElementType.IsImplicit)
{
return true;
}
}
return false;
}
private static ITypeSymbol? GetOuterCastType(
ExpressionSyntax expression, SemanticModel semanticModel, out bool parentIsIsOrAsExpression)
{
expression = expression.WalkUpParentheses();
parentIsIsOrAsExpression = false;
var parentNode = expression.Parent;
if (parentNode == null)
{
return null;
}
if (parentNode.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax? castExpression))
{
return semanticModel.GetTypeInfo(castExpression).Type;
}
if (parentNode.IsKind(SyntaxKind.PointerIndirectionExpression))
{
return semanticModel.GetTypeInfo(expression).Type;
}
if (parentNode.IsKind(SyntaxKind.IsExpression) ||
parentNode.IsKind(SyntaxKind.AsExpression))
{
parentIsIsOrAsExpression = true;
return null;
}
if (parentNode.IsKind(SyntaxKind.ArrayRankSpecifier))
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Int32);
}
if (parentNode.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess))
{
if (memberAccess.Expression == expression)
{
var memberSymbol = semanticModel.GetSymbolInfo(memberAccess).Symbol;
if (memberSymbol != null)
{
return memberSymbol.ContainingType;
}
}
}
if (parentNode.IsKind(SyntaxKind.ConditionalExpression) &&
((ConditionalExpressionSyntax)parentNode).Condition == expression)
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean);
}
if ((parentNode is PrefixUnaryExpressionSyntax || parentNode is PostfixUnaryExpressionSyntax) &&
!semanticModel.GetConversion(expression).IsUserDefined)
{
var parentExpression = (ExpressionSyntax)parentNode;
return GetOuterCastType(parentExpression, semanticModel, out parentIsIsOrAsExpression) ?? semanticModel.GetTypeInfo(parentExpression).ConvertedType;
}
if (parentNode is InterpolationSyntax)
{
// $"{(x)y}"
//
// Regardless of the cast to 'x', being in an interpolation automatically casts the result to object
// since this becomes a call to: FormattableStringFactory.Create(string, params object[]).
return semanticModel.Compilation.ObjectType;
}
return null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers
{
internal static class CastSimplifier
{
public static bool IsUnnecessaryCast(ExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> cast is CastExpressionSyntax castExpression ? IsUnnecessaryCast(castExpression, semanticModel, cancellationToken) :
cast is BinaryExpressionSyntax binaryExpression ? IsUnnecessaryAsCast(binaryExpression, semanticModel, cancellationToken) : false;
public static bool IsUnnecessaryCast(CastExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> IsCastSafeToRemove(cast, cast.Expression, semanticModel, cancellationToken);
public static bool IsUnnecessaryAsCast(BinaryExpressionSyntax cast, SemanticModel semanticModel, CancellationToken cancellationToken)
=> cast.Kind() == SyntaxKind.AsExpression &&
IsCastSafeToRemove(cast, cast.Left, semanticModel, cancellationToken);
private static bool IsCastSafeToRemove(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
var speculationAnalyzer = new SpeculationAnalyzer(castNode,
castedExpressionNode, semanticModel, cancellationToken,
skipVerificationForReplacedNode: true, failOnOverloadResolutionFailuresInOriginalCode: true);
// First, check to see if the node ultimately parenting this cast has any
// syntax errors. If so, we bail.
if (speculationAnalyzer.SemanticRootOfOriginalExpression.ContainsDiagnostics)
return false;
// Now perform basic checks looking for a few things:
//
// 1. casts that must stay because removal will produce actually illegal code.
// 2. casts that must stay because they have runtime impact (i.e. could cause exceptions to be thrown).
// 3. casts that *seem* unnecessary because they don't violate the above, and the cast seems like it has no
// effect at runtime (i.e. casting a `string` to `object`). Note: just because the cast seems like it
// will have not runtime impact doesn't mean we can remove it. It still may be necessary to preserve the
// meaning of the code (for example for overload resolution). That check will occur after this.
//
// This is the fundamental separation between CastHasNoRuntimeImpact and
// speculationAnalyzer.ReplacementChangesSemantics. The former is simple and is only asking if the cast
// seems like it would have no impact *at runtime*. The latter ensures that the static meaning of the code
// is preserved.
//
// When adding/updating checks keep the above in mind to determine where the check should go.
var castHasRuntimeImpact = CastHasRuntimeImpact(
speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken);
if (castHasRuntimeImpact)
return false;
// Cast has no runtime effect. But it may change static semantics. Only allow removal if static semantics
// don't change.
if (speculationAnalyzer.ReplacementChangesSemantics())
return false;
return true;
}
private static bool CastHasRuntimeImpact(
SpeculationAnalyzer speculationAnalyzer,
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Look for simple patterns we know will never cause any runtime changes.
if (CastDefinitelyHasNoRuntimeImpact(castNode, castedExpressionNode, semanticModel, cancellationToken))
return false;
// Call into our legacy codepath that tries to make the same determination.
return !CastHasNoRuntimeImpact_Legacy(speculationAnalyzer, castNode, castedExpressionNode, semanticModel, cancellationToken);
}
private static bool CastDefinitelyHasNoRuntimeImpact(
ExpressionSyntax castNode,
ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// NOTE: Keep this method simple. Each type of runtime impact check should just be a new check added
// independently from the rest. We want to make it very clear exactly which cases each check is covering.
// castNode is: `(Type)expr` or `expr as Type`.
// castedExpressionnode is: `expr`
// The type in `(Type)...` or `... as Type`
var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type;
// The type in `(...)expr` or `expr as ...`
var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type;
// $"x {(object)y} z" It's always safe to remove this `(object)` cast as this cast happens automatically.
if (IsObjectCastInInterpolation(castNode, castType))
return true;
// if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~`
if (IsEnumToNumericCastThatCanDefinitelyBeRemoved(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
return false;
}
private static bool CastHasNoRuntimeImpact_Legacy(
SpeculationAnalyzer speculationAnalyzer,
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Note: Legacy codepaths for determining if a cast is removable. As much as possible we should attempt to
// extract simple and clearly defined checks from here and move to CastDefinitelyHasNoRuntimeImpact.
// Then look for patterns for cases where we never want to remove casts.
if (CastMustBePreserved(castNode, castedExpressionNode, semanticModel, cancellationToken))
return false;
// If this changes static semantics (i.e. causes a different overload to be called), then we can't remove it.
if (speculationAnalyzer.ReplacementChangesSemantics())
return false;
var castTypeInfo = semanticModel.GetTypeInfo(castNode, cancellationToken);
var castType = castTypeInfo.Type;
RoslynDebug.AssertNotNull(castType);
var expressionTypeInfo = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken);
var expressionType = expressionTypeInfo.Type;
var expressionToCastType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true);
var outerType = GetOuterCastType(castNode, semanticModel, out var parentIsOrAsExpression) ?? castTypeInfo.ConvertedType;
// Clearest case. We know we haven't changed static semantic, and we have an Identity (i.e. no-impact,
// representation-preserving) cast. This is always safe to remove.
//
// Note: while these casts are always safe to remove, there is a case where we still keep them.
// Specifically, if the compiler would warn that the code is no longer clear, then we will keep the cast
// around. These warning checks should go into CastMustBePreserved above.
if (expressionToCastType.IsIdentity)
return true;
// Is this a cast inside a conditional expression? Because of target typing we already sorted that out
// in ReplacementChangesSemantics()
if (IsBranchOfConditionalExpression(castNode))
{
return true;
}
// We already bailed out of we had an explicit/none conversions back in CastMustBePreserved
// (except for implicit user defined conversions).
Debug.Assert(!expressionToCastType.IsExplicit || expressionToCastType.IsUserDefined);
// At this point, the only type of conversion left are implicit or user-defined conversions. These may be
// conversions we can remove, but need further analysis.
Debug.Assert(expressionToCastType.IsImplicit || expressionToCastType.IsUserDefined);
if (expressionToCastType.IsInterpolatedString)
{
// interpolation casts are necessary to preserve semantics if our destination type is not itself
// FormattableString or some interface of FormattableString.
return castType.Equals(castTypeInfo.ConvertedType) ||
ImmutableArray<ITypeSymbol?>.CastUp(castType.AllInterfaces).Contains(castTypeInfo.ConvertedType);
}
if (castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.DefaultLiteralExpression) &&
!castType.Equals(outerType) &&
outerType.IsNullable())
{
// We have a cast like `(T?)(X)default`. We can't remove the inner cast as it effects what value
// 'default' means in this context.
return false;
}
if (parentIsOrAsExpression)
{
// Note: speculationAnalyzer.ReplacementChangesSemantics() ensures that the parenting is or as expression are not broken.
// Here we just need to ensure that the original cast expression doesn't invoke a user defined operator.
return !expressionToCastType.IsUserDefined;
}
if (outerType != null)
{
var castToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castNode, outerType);
var expressionToOuterType = GetSpeculatedExpressionToOuterTypeConversion(speculationAnalyzer.ReplacedExpression, speculationAnalyzer, cancellationToken);
// if the conversion to the outer type doesn't exist, then we shouldn't offer, except for anonymous functions which can't be reasoned about the same way (see below)
if (!expressionToOuterType.Exists && !expressionToOuterType.IsAnonymousFunction)
{
return false;
}
// CONSIDER: Anonymous function conversions cannot be compared from different semantic models as lambda symbol comparison requires syntax tree equality. Should this be a compiler bug?
// For now, just revert back to computing expressionToOuterType using the original semantic model.
if (expressionToOuterType.IsAnonymousFunction)
{
expressionToOuterType = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, outerType);
}
// If there is an user-defined conversion from the expression to the cast type or the cast
// to the outer type, we need to make sure that the same user-defined conversion will be
// called if the cast is removed.
if (castToOuterType.IsUserDefined || expressionToCastType.IsUserDefined)
{
return !expressionToOuterType.IsExplicit &&
(HaveSameUserDefinedConversion(expressionToCastType, expressionToOuterType) ||
HaveSameUserDefinedConversion(castToOuterType, expressionToOuterType)) &&
UserDefinedConversionIsAllowed(castNode);
}
else if (expressionToOuterType.IsUserDefined)
{
return false;
}
if (expressionToCastType.IsExplicit &&
expressionToOuterType.IsExplicit)
{
return false;
}
// If the conversion from the expression to the cast type is implicit numeric or constant
// and the conversion from the expression to the outer type is identity, we'll go ahead
// and remove the cast.
if (expressionToOuterType.IsIdentity &&
expressionToCastType.IsImplicit &&
(expressionToCastType.IsNumeric || expressionToCastType.IsConstantExpression))
{
RoslynDebug.AssertNotNull(expressionType);
// Some implicit numeric conversions can cause loss of precision and must not be removed.
return !IsRequiredImplicitNumericConversion(expressionType, castType);
}
if (!castToOuterType.IsBoxing &&
castToOuterType == expressionToOuterType)
{
if (castToOuterType.IsNullable)
{
// Even though both the nullable conversions (castToOuterType and expressionToOuterType) are equal, we can guarantee no data loss only if there is an
// implicit conversion from expression type to cast type and expression type is non-nullable. For example, consider the cast removal "(float?)" for below:
// Console.WriteLine((int)(float?)(int?)2147483647); // Prints -2147483648
// castToOuterType: ExplicitNullable
// expressionToOuterType: ExplicitNullable
// expressionToCastType: ImplicitNullable
// We should not remove the cast to "float?".
// However, cast to "int?" is unnecessary and should be removable.
return expressionToCastType.IsImplicit && !expressionType.IsNullable();
}
else if (expressionToCastType.IsImplicit && expressionToCastType.IsNumeric && !castToOuterType.IsIdentity)
{
RoslynDebug.AssertNotNull(expressionType);
// Some implicit numeric conversions can cause loss of precision and must not be removed.
return !IsRequiredImplicitNumericConversion(expressionType, castType);
}
return true;
}
if (castToOuterType.IsIdentity &&
!expressionToCastType.IsUnboxing &&
expressionToCastType == expressionToOuterType)
{
return true;
}
// Special case: It's possible to have useless casts inside delegate creation expressions.
// For example: new Func<string, bool>((Predicate<object>)(y => true)).
if (IsInDelegateCreationExpression(castNode, semanticModel))
{
if (expressionToCastType.IsAnonymousFunction && expressionToOuterType.IsAnonymousFunction)
{
return !speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression);
}
if (expressionToCastType.IsMethodGroup && expressionToOuterType.IsMethodGroup)
{
return true;
}
}
// Case :
// 1. IList<object> y = (IList<dynamic>)new List<object>()
if (expressionToCastType.IsExplicit && castToOuterType.IsExplicit && expressionToOuterType.IsImplicit)
{
// If both expressionToCastType and castToOuterType are numeric, then this is a required cast as one of the conversions leads to loss of precision.
// Cast removal can change program behavior.
return !(expressionToCastType.IsNumeric && castToOuterType.IsNumeric);
}
// Case :
// 2. object y = (ValueType)1;
if (expressionToCastType.IsBoxing && expressionToOuterType.IsBoxing && castToOuterType.IsImplicit)
{
return true;
}
// Case :
// 3. object y = (NullableValueType)null;
if ((!castToOuterType.IsBoxing || expressionToCastType.IsNullLiteral) &&
castToOuterType.IsImplicit &&
expressionToCastType.IsImplicit &&
expressionToOuterType.IsImplicit)
{
if (expressionToOuterType.IsAnonymousFunction)
{
return expressionToCastType.IsAnonymousFunction &&
!speculationAnalyzer.ReplacementChangesSemanticsOfUnchangedLambda(castedExpressionNode, speculationAnalyzer.ReplacedExpression);
}
return true;
}
}
return false;
}
private static bool IsObjectCastInInterpolation(ExpressionSyntax castNode, [NotNullWhen(true)] ITypeSymbol? castType)
{
// A casts to object can always be removed from an expression inside of an interpolation, since it'll be converted to object
// in order to call string.Format(...) anyway.
return castType?.SpecialType == SpecialType.System_Object &&
castNode.WalkUpParentheses().IsParentKind(SyntaxKind.Interpolation);
}
private static bool IsEnumToNumericCastThatCanDefinitelyBeRemoved(
ExpressionSyntax castNode,
[NotNullWhen(true)] ITypeSymbol? castType,
[NotNullWhen(true)] ITypeSymbol? castedExpressionType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (!castedExpressionType.IsEnumType(out var castedEnumType))
return false;
if (!Equals(castType, castedEnumType.EnumUnderlyingType))
return false;
// if we have `(E)~(int)e` then the cast to (int) is not necessary as enums always support `~`.
castNode = castNode.WalkUpParentheses();
if (castNode.IsParentKind(SyntaxKind.BitwiseNotExpression, out PrefixUnaryExpressionSyntax? prefixUnary))
{
if (!prefixUnary.WalkUpParentheses().IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax? parentCast))
return false;
// `(int)` in `(E?)~(int)e` is also redundant.
var parentCastType = semanticModel.GetTypeInfo(parentCast.Type, cancellationToken).Type;
if (parentCastType.IsNullable(out var underlyingType))
parentCastType = underlyingType;
return castedEnumType.Equals(parentCastType);
}
// if we have `(int)e == 0` then the cast can be removed. Note: this is only for the exact cast of
// comparing to the constant 0. All other comparisons are not allowed.
if (castNode.Parent is BinaryExpressionSyntax binaryExpression)
{
if (binaryExpression.IsKind(SyntaxKind.EqualsExpression) || binaryExpression.IsKind(SyntaxKind.NotEqualsExpression))
{
var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left;
var otherSideType = semanticModel.GetTypeInfo(otherSide, cancellationToken).Type;
if (Equals(otherSideType, castedEnumType.EnumUnderlyingType))
{
var constantValue = semanticModel.GetConstantValue(otherSide, cancellationToken);
if (constantValue.HasValue &&
IntegerUtilities.IsIntegral(constantValue.Value) &&
IntegerUtilities.ToInt64(constantValue.Value) == 0)
{
return true;
}
}
}
}
return false;
}
private static bool CastMustBePreserved(
ExpressionSyntax castNode,
ExpressionSyntax castedExpressionNode,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// castNode is: `(Type)expr` or `expr as Type`.
// castedExpressionnode is: `expr`
// The type in `(Type)...` or `... as Type`
var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type;
// If we don't understand the type, we must keep it.
if (castType == null)
return true;
// The type in `(...)expr` or `expr as ...`
var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type;
var conversion = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true);
// If we've got an error for some reason, then we don't want to touch this at all.
if (castType.IsErrorType())
return true;
// Almost all explicit conversions can cause an exception or data loss, hence can never be removed.
if (IsExplicitCastThatMustBePreserved(castNode, conversion))
return true;
// If this conversion doesn't even exist, then this code is in error, and we don't want to touch it.
if (!conversion.Exists)
return true;
// `dynamic` changes the semantics of everything and is rarely safe to remove. We could consider removing
// absolutely safe casts (i.e. `(dynamic)(dynamic)a`), but it's likely not worth the effort, so we just
// disallow touching them entirely.
if (InvolvesDynamic(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
// If removing the cast would cause the compiler to issue a specific warning, then we have to preserve it.
if (CastRemovalWouldCauseSignExtensionWarning(castNode, semanticModel, cancellationToken))
return true;
// *(T*)null. Can't remove this case.
if (IsDereferenceOfNullPointerCast(castNode, castedExpressionNode))
return true;
if (ParamsArgumentCastMustBePreserved(castNode, castType, semanticModel, cancellationToken))
return true;
// `... ? (int?)1 : default`. This cast is necessary as the 'null/default' on the other side of the
// conditional can change meaning since based on the type on the other side.
//
// TODO(cyrusn): This should move into SpeculationAnalyzer as it's a static-semantics change.
if (CastMustBePreservedInConditionalBranch(castNode, conversion))
return true;
// (object)"" == someObj
//
// This cast can be removed with no runtime or static-semantics change. However, the compiler warns here
// that this could be confusing (since it's not clear it's calling `==(object,object)` instead of
// `==(string,string)`), so we have to preserve this.
if (CastIsRequiredToPreventUnintendedComparisonWarning(castNode, castedExpressionNode, castType, semanticModel, cancellationToken))
return true;
// Identity fp-casts can actually change the runtime value of the fp number. This can happen because the
// runtime is allowed to perform the operations with wider precision than the actual specified fp-precision.
// i.e. 64-bit doubles can actually be 80 bits at runtime. Even though the language considers this to be an
// identity cast, we don't want to remove these because the user may be depending on that truncation.
RoslynDebug.Assert(!conversion.IsIdentity || castedExpressionType is not null);
if (IdentityFloatingPointCastMustBePreserved(castNode, castedExpressionNode, castType, castedExpressionType!, semanticModel, conversion, cancellationToken))
return true;
if (PointerOrIntPtrCastMustBePreserved(conversion))
return true;
// If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can
// be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't
// even bother removing this.
if (IsTypeLessExpressionNotInTargetTypedLocation(castNode, castedExpressionType))
return true;
// If we have something like `(nuint)(nint)x` where x is an IntPtr then the nint cast cannot be removed
// as IntPtr to nuint is invalid.
if (IsIntPtrToNativeIntegerNestedCast(castNode, castType, castedExpressionType, semanticModel, cancellationToken))
return true;
// If we have `~(ulong)uintVal` then we have to preserve the `(ulong)` cast. Otherwise, the `~` will
// operate on the shorter-bit value, before being extended out to the full length, rather than operating on
// the full length.
if (IsBitwiseNotOfExtendedUnsignedValue(castNode, conversion, castType, castedExpressionType))
return true;
return false;
}
private static bool IsBitwiseNotOfExtendedUnsignedValue(ExpressionSyntax castNode, Conversion conversion, ITypeSymbol castType, ITypeSymbol castedExressionType)
{
if (castNode.WalkUpParentheses().IsParentKind(SyntaxKind.BitwiseNotExpression) &&
conversion.IsImplicit &&
conversion.IsNumeric)
{
return IsUnsigned(castType) || IsUnsigned(castedExressionType);
}
return false;
}
private static bool IsUnsigned(ITypeSymbol type)
=> type.SpecialType.IsUnsignedIntegralType() || IsNuint(type);
private static bool IsNuint(ITypeSymbol type)
=> type.SpecialType == SpecialType.System_UIntPtr && type.IsNativeIntegerType;
private static bool IsIntPtrToNativeIntegerNestedCast(ExpressionSyntax castNode, ITypeSymbol castType, ITypeSymbol castedExpressionType, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (castedExpressionType == null)
{
return false;
}
if (castType.SpecialType is not (SpecialType.System_IntPtr or SpecialType.System_UIntPtr))
{
return false;
}
if (castNode.WalkUpParentheses().Parent is CastExpressionSyntax castExpression)
{
var parentCastType = semanticModel.GetTypeInfo(castExpression, cancellationToken).Type;
if (parentCastType == null)
{
return false;
}
// Given (nuint)(nint)myIntPtr we would normally suggest removing the (nint) cast as being identity
// but it is required as a means to get from IntPtr to nuint, and vice versa from UIntPtr to nint,
// so we check for an identity cast from [U]IntPtr to n[u]int and then to a number type.
if (castedExpressionType.SpecialType == castType.SpecialType &&
!castedExpressionType.IsNativeIntegerType &&
castType.IsNativeIntegerType &&
parentCastType.IsNumericType())
{
return true;
}
}
return false;
}
private static bool IsTypeLessExpressionNotInTargetTypedLocation(ExpressionSyntax castNode, [NotNullWhen(false)] ITypeSymbol? castedExpressionType)
{
// If we have something like `((int)default).ToString()`. `default` has no type of it's own, but instead can
// be target typed. However `(...).ToString()` is not a location where a target type can appear. So don't
// even bother removing this.
// checked if the expression being casted is typeless.
if (castedExpressionType != null)
return false;
if (IsInTargetTypingLocation(castNode))
return false;
// we don't have our own type, and we're not in a location where a type can be inferred. don't remove this
// cast.
return true;
}
private static bool IsInTargetTypingLocation(ExpressionSyntax node)
{
node = node.WalkUpParentheses();
var parent = node.Parent;
// note: the list below is not intended to be exhaustive. For example there are places we can target type,
// but which we don't want to bother doing all the work to validate. For example, technically you can
// target type `throw (Exception)null`, so we could allow `(Exception)` to be removed. But it's such a corner
// case that we don't care about supporting, versus all the hugely valuable cases users will actually run into.
// also: the list doesn't have to be firmly accurate:
// 1. If we have a false positive and we say something is a target typing location, then that means we
// simply try to remove the cast, but then catch the break later.
// 2. If we have a false negative and we say something is not a target typing location, then we simply
// don't try to remove the cast and the user has no impact on their code.
// `null op e2`. Either side can target type the other.
if (parent is BinaryExpressionSyntax)
return true;
// `Goo(null)`. The type of the arg is target typed by the Goo method being called.
//
// This also helps Tuples fall out as they're built of arguments. i.e. `(string s, string y) = (null, null)`.
if (parent is ArgumentSyntax)
return true;
// same as above
if (parent is AttributeArgumentSyntax)
return true;
// `new SomeType[] { null }` or `new [] { null, expr }`.
// Type of the element can be target typed by the array type, or the sibling expression types.
if (parent is InitializerExpressionSyntax)
return true;
// `return null;`. target typed by whatever method this is in.
if (parent is ReturnStatementSyntax)
return true;
// `yield return null;` same as above.
if (parent is YieldStatementSyntax)
return true;
// `x = null`. target typed by the other side.
if (parent is AssignmentExpressionSyntax)
return true;
// ... = null
//
// handles: parameters, variable declarations and the like.
if (parent is EqualsValueClauseSyntax)
return true;
// `(SomeType)null`. Definitely can target type this type-less expression.
if (parent is CastExpressionSyntax)
return true;
// `... ? null : ...`. Either side can target type the other.
if (parent is ConditionalExpressionSyntax)
return true;
// case null:
if (parent is CaseSwitchLabelSyntax)
return true;
return false;
}
private static bool IsExplicitCastThatMustBePreserved(ExpressionSyntax castNode, Conversion conversion)
{
if (conversion.IsExplicit)
{
// Consider the explicit cast in a line like:
//
// string? s = conditional ? (string?)"hello" : null;
//
// That string? cast is an explicit conversion that not IsUserDefined, but it may be removable if we support
// target-typed conditionals; in that case we'll return false here and force the full algorithm to be ran rather
// than this fast-path.
if (IsBranchOfConditionalExpression(castNode) &&
!CastMustBePreservedInConditionalBranch(castNode, conversion))
{
return false;
}
// if it's not a user defined conversion, we must preserve it as it has runtime impact that we don't want to change.
if (!conversion.IsUserDefined)
return true;
// Casts that involve implicit conversions are still represented as explicit casts. Because they're
// implicit though, we may be able to remove it. i.e. if we have `(C)0 + (C)1` we can remove one of the
// casts because it will be inferred from the binary context.
var userMethod = conversion.MethodSymbol;
if (userMethod?.Name != WellKnownMemberNames.ImplicitConversionName)
return true;
}
return false;
}
private static bool PointerOrIntPtrCastMustBePreserved(Conversion conversion)
{
if (!conversion.IsIdentity)
return false;
// if we have a non-identity cast to an int* or IntPtr just do not touch this.
// https://github.com/dotnet/roslyn/issues/2987 tracks improving on this conservative approach.
//
// NOTE(cyrusn): This code should not be necessary. However there is additional code that deals with
// `*(x*)expr` ends up masking that this change should not be safe. That code is suspect and should be
// changed. Until then though we disable this.
return conversion.IsPointer || conversion.IsIntPtr;
}
private static bool InvolvesDynamic(
ExpressionSyntax castNode,
ITypeSymbol? castType,
ITypeSymbol? castedExpressionType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// We do not remove any cast on
// 1. Dynamic Expressions
// 2. If there is any other argument which is dynamic
// 3. Dynamic Invocation
// 4. Assignment to dynamic
if (castType?.Kind == SymbolKind.DynamicType || castedExpressionType?.Kind == SymbolKind.DynamicType)
return true;
return IsDynamicInvocation(castNode, semanticModel, cancellationToken) ||
IsDynamicAssignment(castNode, semanticModel, cancellationToken);
}
private static bool IsDereferenceOfNullPointerCast(ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode)
{
return castNode.WalkUpParentheses().IsParentKind(SyntaxKind.PointerIndirectionExpression) &&
castedExpressionNode.WalkDownParentheses().IsKind(SyntaxKind.NullLiteralExpression, SyntaxKind.DefaultLiteralExpression);
}
private static bool IsBranchOfConditionalExpression(ExpressionSyntax expression)
{
return expression.Parent is ConditionalExpressionSyntax conditionalExpression &&
expression != conditionalExpression.Condition;
}
private static bool CastMustBePreservedInConditionalBranch(
ExpressionSyntax castNode, Conversion conversion)
{
// `... ? (int?)i : default`. This cast is necessary as the 'null/default' on the other side of the
// conditional can change meaning since based on the type on the other side.
// It's safe to remove the cast when it's an identity. for example:
// `... ? (int)1 : default`.
if (!conversion.IsIdentity)
{
castNode = castNode.WalkUpParentheses();
if (castNode.Parent is ConditionalExpressionSyntax conditionalExpression)
{
if (conditionalExpression.WhenTrue == castNode ||
conditionalExpression.WhenFalse == castNode)
{
var otherSide = conditionalExpression.WhenTrue == castNode
? conditionalExpression.WhenFalse
: conditionalExpression.WhenTrue;
otherSide = otherSide.WalkDownParentheses();
// In C# 9 we can potentially remove the cast if the other side is null, since the cast was previously required to
// resolve a situation like:
//
// var x = condition ? (int?)i : null
//
// but it isn't with target-typed conditionals. We do have to keep the cast if it's default, as:
//
// var x = condition ? (int?)i : default
//
// is inferred by the compiler to mean 'default(int?)', whereas removing the cast would mean default(int).
var languageVersion = ((CSharpParseOptions)castNode.SyntaxTree.Options).LanguageVersion;
return (otherSide.IsKind(SyntaxKind.NullLiteralExpression) && languageVersion < LanguageVersion.CSharp9) ||
otherSide.IsKind(SyntaxKind.DefaultLiteralExpression);
}
}
}
return false;
}
private static bool CastRemovalWouldCauseSignExtensionWarning(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Logic copied from DiagnosticsPass_Warnings.CheckForBitwiseOrSignExtend. Including comments.
if (!(expression is CastExpressionSyntax castExpression))
return false;
var castRoot = castExpression.WalkUpParentheses();
// Check both binary-or, and assignment-or
//
// x | (...)y
// x |= (...)y
ExpressionSyntax leftOperand, rightOperand;
if (castRoot.Parent is BinaryExpressionSyntax parentBinary)
{
if (!parentBinary.IsKind(SyntaxKind.BitwiseOrExpression))
return false;
(leftOperand, rightOperand) = (parentBinary.Left, parentBinary.Right);
}
else if (castRoot.Parent is AssignmentExpressionSyntax parentAssignment)
{
if (!parentAssignment.IsKind(SyntaxKind.OrAssignmentExpression))
return false;
(leftOperand, rightOperand) = (parentAssignment.Left, parentAssignment.Right);
}
else
{
return false;
}
// The native compiler skips this warning if both sides of the operator are constants.
//
// CONSIDER: Is that sensible? It seems reasonable that if we would warn on int | short
// when they are non-constants, or when one is a constant, that we would similarly warn
// when both are constants.
var constantValue = semanticModel.GetConstantValue(castRoot.Parent, cancellationToken);
if (constantValue.HasValue && constantValue.Value != null)
return false;
// Start by determining *which bits on each side are going to be unexpectedly turned on*.
var leftOperation = semanticModel.GetOperation(leftOperand.WalkDownParentheses(), cancellationToken);
var rightOperation = semanticModel.GetOperation(rightOperand.WalkDownParentheses(), cancellationToken);
if (leftOperation == null || rightOperation == null)
return false;
// Note: we are asking the question about if there would be a problem removing the cast. So we have to act
// as if an explicit cast becomes an implicit one. We do this by ignoring the appropriate cast and not
// treating it as explicit when we encounter it.
var left = FindSurprisingSignExtensionBits(leftOperation, leftOperand == castRoot);
var right = FindSurprisingSignExtensionBits(rightOperation, rightOperand == castRoot);
// If they are all the same then there's no warning to give.
if (left == right)
return false;
// Suppress the warning if one side is a constant, and either all the unexpected
// bits are already off, or all the unexpected bits are already on.
var constVal = GetConstantValueForBitwiseOrCheck(leftOperation);
if (constVal != null)
{
var val = constVal.Value;
if ((val & right) == right || (~val & right) == right)
return false;
}
constVal = GetConstantValueForBitwiseOrCheck(rightOperation);
if (constVal != null)
{
var val = constVal.Value;
if ((val & left) == left || (~val & left) == left)
return false;
}
// This would produce a warning. Don't offer to remove the cast.
return true;
}
private static ulong? GetConstantValueForBitwiseOrCheck(IOperation operation)
{
// We might have a nullable conversion on top of an integer constant. But only dig out
// one level.
if (operation is IConversionOperation conversion &&
conversion.Conversion.IsImplicit &&
conversion.Conversion.IsNullable)
{
operation = conversion.Operand;
}
var constantValue = operation.ConstantValue;
if (!constantValue.HasValue || constantValue.Value == null)
return null;
RoslynDebug.Assert(operation.Type is not null);
if (!operation.Type.SpecialType.IsIntegralType())
return null;
return IntegerUtilities.ToUInt64(constantValue.Value);
}
// A "surprising" sign extension is:
//
// * a conversion with no cast in source code that goes from a smaller
// signed type to a larger signed or unsigned type.
//
// * an conversion (with or without a cast) from a smaller
// signed type to a larger unsigned type.
private static ulong FindSurprisingSignExtensionBits(IOperation? operation, bool treatExplicitCastAsImplicit)
{
if (!(operation is IConversionOperation conversion))
return 0;
var from = conversion.Operand.Type;
var to = conversion.Type;
if (from is null || to is null)
return 0;
if (from.IsNullable(out var fromUnderlying))
from = fromUnderlying;
if (to.IsNullable(out var toUnderlying))
to = toUnderlying;
var fromSpecialType = from.SpecialType;
var toSpecialType = to.SpecialType;
if (!fromSpecialType.IsIntegralType() || !toSpecialType.IsIntegralType())
return 0;
var fromSize = fromSpecialType.SizeInBytes();
var toSize = toSpecialType.SizeInBytes();
if (fromSize == 0 || toSize == 0)
return 0;
// The operand might itself be a conversion, and might be contributing
// surprising bits. We might have more, fewer or the same surprising bits
// as the operand.
var recursive = FindSurprisingSignExtensionBits(conversion.Operand, treatExplicitCastAsImplicit: false);
if (fromSize == toSize)
{
// No change.
return recursive;
}
if (toSize < fromSize)
{
// We are casting from a larger type to a smaller type, and are therefore
// losing surprising bits.
switch (toSize)
{
case 1: return unchecked((ulong)(byte)recursive);
case 2: return unchecked((ulong)(ushort)recursive);
case 4: return unchecked((ulong)(uint)recursive);
}
Debug.Assert(false, "How did we get here?");
return recursive;
}
// We are converting from a smaller type to a larger type, and therefore might
// be adding surprising bits. First of all, the smaller type has got to be signed
// for there to be sign extension.
var fromSigned = fromSpecialType.IsSignedIntegralType();
if (!fromSigned)
return recursive;
// OK, we know that the "from" type is a signed integer that is smaller than the
// "to" type, so we are going to have sign extension. Is it surprising? The only
// time that sign extension is *not* surprising is when we have a cast operator
// to a *signed* type. That is, (int)myShort is not a surprising sign extension.
var explicitInCode = !conversion.IsImplicit;
if (!treatExplicitCastAsImplicit &&
explicitInCode &&
toSpecialType.IsSignedIntegralType())
{
return recursive;
}
// Note that we *could* be somewhat more clever here. Consider the following edge case:
//
// (ulong)(int)(uint)(ushort)mySbyte
//
// We could reason that the sbyte-to-ushort conversion is going to add one byte of
// unexpected sign extension. The conversion from ushort to uint adds no more bytes.
// The conversion from uint to int adds no more bytes. Does the conversion from int
// to ulong add any more bytes of unexpected sign extension? Well, no, because we
// know that the previous conversion from ushort to uint will ensure that the top bit
// of the uint is off!
//
// But we are not going to try to be that clever. In the extremely unlikely event that
// someone does this, we will record that the unexpectedly turned-on bits are
// 0xFFFFFFFF0000FF00, even though we could in theory deduce that only 0x000000000000FF00
// are the unexpected bits.
var result = recursive;
for (var i = fromSize; i < toSize; ++i)
result |= (0xFFUL) << (i * 8);
return result;
}
private static bool IdentityFloatingPointCastMustBePreserved(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode,
ITypeSymbol castType, ITypeSymbol castedExpressionType,
SemanticModel semanticModel, Conversion conversion, CancellationToken cancellationToken)
{
if (!conversion.IsIdentity)
return false;
// Floating point casts can have subtle runtime behavior, even between the same fp types. For example, a
// cast from float-to-float can still change behavior because it may take a higher precision computation and
// truncate it to 32bits.
//
// Because of this we keep floating point conversions unless we can prove that it's safe. The only safe
// times are when we're loading or storing into a location we know has the same size as the cast size
// (i.e. reading/writing into a field).
if (castedExpressionType.SpecialType != SpecialType.System_Double &&
castedExpressionType.SpecialType != SpecialType.System_Single &&
castType.SpecialType != SpecialType.System_Double &&
castType.SpecialType != SpecialType.System_Single)
{
// wasn't a floating point conversion.
return false;
}
// Identity fp conversion is safe if this is a read from a fp field/array
if (IsFieldOrArrayElement(semanticModel, castedExpressionNode, cancellationToken))
return false;
castNode = castNode.WalkUpParentheses();
if (castNode.Parent is AssignmentExpressionSyntax assignmentExpression &&
assignmentExpression.Right == castNode)
{
// Identity fp conversion is safe if this is a write to a fp field/array
if (IsFieldOrArrayElement(semanticModel, assignmentExpression.Left, cancellationToken))
return false;
}
else if (castNode.Parent.IsKind(SyntaxKind.ArrayInitializerExpression, out InitializerExpressionSyntax? arrayInitializer))
{
// Identity fp conversion is safe if this is in an array initializer.
var typeInfo = semanticModel.GetTypeInfo(arrayInitializer, cancellationToken);
return typeInfo.Type?.Kind == SymbolKind.ArrayType;
}
else if (castNode.Parent is EqualsValueClauseSyntax equalsValue &&
equalsValue.Value == castNode &&
equalsValue.Parent is VariableDeclaratorSyntax variableDeclarator)
{
// Identity fp conversion is safe if this is in a field initializer.
var symbol = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken);
if (symbol?.Kind == SymbolKind.Field)
return false;
}
// We have to preserve this cast.
return true;
}
private static bool IsFieldOrArrayElement(
SemanticModel semanticModel, ExpressionSyntax expr, CancellationToken cancellationToken)
{
expr = expr.WalkDownParentheses();
var castedExpresionSymbol = semanticModel.GetSymbolInfo(expr, cancellationToken).Symbol;
// we're reading from a field of the same size. it's safe to remove this case.
if (castedExpresionSymbol?.Kind == SymbolKind.Field)
return true;
if (expr is ElementAccessExpressionSyntax elementAccess)
{
var locationType = semanticModel.GetTypeInfo(elementAccess.Expression, cancellationToken);
return locationType.Type?.Kind == SymbolKind.ArrayType;
}
return false;
}
private static bool HaveSameUserDefinedConversion(Conversion conversion1, Conversion conversion2)
{
return conversion1.IsUserDefined
&& conversion2.IsUserDefined
&& Equals(conversion1.MethodSymbol, conversion2.MethodSymbol);
}
private static bool IsInDelegateCreationExpression(
ExpressionSyntax castNode, SemanticModel semanticModel)
{
if (!(castNode.WalkUpParentheses().Parent is ArgumentSyntax argument))
{
return false;
}
if (!(argument.Parent is ArgumentListSyntax argumentList))
{
return false;
}
if (!(argumentList.Parent is ObjectCreationExpressionSyntax objectCreation))
{
return false;
}
var typeSymbol = semanticModel.GetSymbolInfo(objectCreation.Type).Symbol;
return typeSymbol != null
&& typeSymbol.IsDelegateType();
}
private static bool IsDynamicInvocation(
ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (castExpression.WalkUpParentheses().IsParentKind(SyntaxKind.Argument, out ArgumentSyntax? argument) &&
argument.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.BracketedArgumentList) &&
argument.Parent.Parent.IsKind(SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression))
{
var typeInfo = semanticModel.GetTypeInfo(argument.Parent.Parent, cancellationToken);
return typeInfo.Type?.Kind == SymbolKind.DynamicType;
}
return false;
}
private static bool IsDynamicAssignment(ExpressionSyntax castExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
castExpression = castExpression.WalkUpParentheses();
if (castExpression.IsRightSideOfAnyAssignExpression())
{
var assignmentExpression = (AssignmentExpressionSyntax)castExpression.Parent!;
var assignmentType = semanticModel.GetTypeInfo(assignmentExpression.Left, cancellationToken).Type;
return assignmentType?.Kind == SymbolKind.DynamicType;
}
return false;
}
private static bool IsRequiredImplicitNumericConversion(ITypeSymbol sourceType, ITypeSymbol destinationType)
{
// C# Language Specification: Section 6.1.2 Implicit numeric conversions
// Conversions from int, uint, long, or ulong to float and from long or ulong to double may cause a loss of precision,
// but will never cause a loss of magnitude. The other implicit numeric conversions never lose any information.
switch (destinationType.SpecialType)
{
case SpecialType.System_Single:
switch (sourceType.SpecialType)
{
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
return true;
default:
return false;
}
case SpecialType.System_Double:
switch (sourceType.SpecialType)
{
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
return true;
default:
return false;
}
default:
return false;
}
}
private static bool CastIsRequiredToPreventUnintendedComparisonWarning(
ExpressionSyntax castNode, ExpressionSyntax castedExpressionNode, ITypeSymbol castType,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// Based on the check in DiagnosticPass.CheckRelationals.
// (object)"" == someObj
//
// This cast can be removed with no runtime or static-semantics change. However, the compiler warns here
// that this could be confusing (since it's not clear it's calling `==(object,object)` instead of
// `==(string,string)`), so we have to preserve this.
// compiler: if (node.Left.Type.SpecialType == SpecialType.System_Object
if (castType?.SpecialType != SpecialType.System_Object)
return false;
// compiler: node.OperatorKind == BinaryOperatorKind.ObjectEqual || node.OperatorKind == BinaryOperatorKind.ObjectNotEqual
castNode = castNode.WalkUpParentheses();
var parent = castNode.Parent;
if (!(parent is BinaryExpressionSyntax binaryExpression))
return false;
if (!binaryExpression.IsKind(SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression))
return false;
var binaryMethod = semanticModel.GetSymbolInfo(binaryExpression, cancellationToken).Symbol as IMethodSymbol;
if (binaryMethod == null)
return false;
if (binaryMethod.ContainingType?.SpecialType != SpecialType.System_Object)
return false;
var operatorName = binaryMethod.Name;
if (operatorName != WellKnownMemberNames.EqualityOperatorName && operatorName != WellKnownMemberNames.InequalityOperatorName)
return false;
// compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t))
var otherSide = castNode == binaryExpression.Left ? binaryExpression.Right : binaryExpression.Left;
otherSide = otherSide.WalkDownParentheses();
return CastIsRequiredToPreventUnintendedComparisonWarning(castedExpressionNode, otherSide, operatorName, semanticModel, cancellationToken) ||
CastIsRequiredToPreventUnintendedComparisonWarning(otherSide, castedExpressionNode, operatorName, semanticModel, cancellationToken);
}
private static bool CastIsRequiredToPreventUnintendedComparisonWarning(
ExpressionSyntax left, ExpressionSyntax right, string operatorName,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
// compiler: node.Left.Type.SpecialType == SpecialType.System_Object
var leftType = semanticModel.GetTypeInfo(left, cancellationToken).Type;
if (leftType?.SpecialType != SpecialType.System_Object)
return false;
// compiler: && !IsExplicitCast(node.Left)
if (left.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression))
return false;
// compiler: && !(node.Left.ConstantValue != null && node.Left.ConstantValue.IsNull)
var constantValue = semanticModel.GetConstantValue(left, cancellationToken);
if (constantValue.HasValue && constantValue.Value is null)
return false;
// compiler: && ConvertedHasEqual(node.OperatorKind, node.Right, out t))
// Code for: ConvertedHasEqual
// compiler: if (conv.ExplicitCastInCode) return false;
if (right.IsKind(SyntaxKind.CastExpression, SyntaxKind.AsExpression))
return false;
// compiler: NamedTypeSymbol nt = conv.Operand.Type as NamedTypeSymbol;
// if ((object)nt == null || !nt.IsReferenceType || nt.IsInterface)
var otherSideType = semanticModel.GetTypeInfo(right, cancellationToken).Type as INamedTypeSymbol;
if (otherSideType == null)
return false;
if (!otherSideType.IsReferenceType || otherSideType.TypeKind == TypeKind.Interface)
return false;
// compiler: for (var t = nt; (object)t != null; t = t.BaseTypeNoUseSiteDiagnostics)
for (var currentType = otherSideType; currentType != null; currentType = currentType.BaseType)
{
// compiler: foreach (var sym in t.GetMembers(opName))
foreach (var opMember in currentType.GetMembers(operatorName))
{
// compiler: MethodSymbol op = sym as MethodSymbol;
var opMethod = opMember as IMethodSymbol;
// compiler: if ((object)op == null || op.MethodKind != MethodKind.UserDefinedOperator) continue;
if (opMethod == null || opMethod.MethodKind != MethodKind.UserDefinedOperator)
continue;
// compiler: var parameters = op.GetParameters();
// if (parameters.Length == 2 && TypeSymbol.Equals(parameters[0].Type, t, TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(parameters[1].Type, t, TypeCompareKind.ConsiderEverything2))
// return true
var parameters = opMethod.Parameters;
if (parameters.Length == 2 && Equals(parameters[0].Type, currentType) && Equals(parameters[1].Type, currentType))
return true;
}
}
return false;
}
private static Conversion GetSpeculatedExpressionToOuterTypeConversion(ExpressionSyntax speculatedExpression, SpeculationAnalyzer speculationAnalyzer, CancellationToken cancellationToken)
{
var typeInfo = speculationAnalyzer.SpeculativeSemanticModel.GetTypeInfo(speculatedExpression, cancellationToken);
var conversion = speculationAnalyzer.SpeculativeSemanticModel.GetConversion(speculatedExpression, cancellationToken);
if (!conversion.IsIdentity)
{
return conversion;
}
var speculatedExpressionOuterType = GetOuterCastType(speculatedExpression, speculationAnalyzer.SpeculativeSemanticModel, out _) ?? typeInfo.ConvertedType;
if (speculatedExpressionOuterType == null)
{
return default;
}
return speculationAnalyzer.SpeculativeSemanticModel.ClassifyConversion(speculatedExpression, speculatedExpressionOuterType);
}
private static bool UserDefinedConversionIsAllowed(ExpressionSyntax expression)
{
expression = expression.WalkUpParentheses();
var parentNode = expression.Parent;
if (parentNode == null)
{
return false;
}
if (parentNode.IsKind(SyntaxKind.ThrowStatement))
{
return false;
}
return true;
}
private static bool ParamsArgumentCastMustBePreserved(
ExpressionSyntax cast,
ITypeSymbol castType,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// When a casted value is passed as the single argument to a params parameter,
// we can only remove the cast if it is implicitly convertible to the parameter's type,
// but not the parameter's element type. Otherwise, we could end up changing the invocation
// to pass an array rather than an array with a single element.
//
// IOW, given the following method...
//
// static void Goo(params object[] x) { }
//
// ...we should remove this cast...
//
// Goo((object[])null);
//
// ...but not this cast...
//
// Goo((object)null);
var parent = cast.WalkUpParentheses().Parent;
if (parent is ArgumentSyntax argument)
{
// If there are any arguments to the right (and the argument is not named), we can assume that this is
// not a *single* argument passed to a params parameter.
if (argument.NameColon == null && argument.Parent is BaseArgumentListSyntax argumentList)
{
var argumentIndex = argumentList.Arguments.IndexOf(argument);
if (argumentIndex < argumentList.Arguments.Count - 1)
{
return false;
}
}
var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken);
return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel);
}
if (parent is AttributeArgumentSyntax attributeArgument)
{
if (attributeArgument.Parent is AttributeArgumentListSyntax)
{
// We don't check the position of the argument because in attributes it is allowed that
// params parameter are positioned in between if named arguments are used.
var parameter = attributeArgument.DetermineParameter(semanticModel, cancellationToken: cancellationToken);
return ParameterTypeMatchesParamsElementType(parameter, castType, semanticModel);
}
}
return false;
}
private static bool ParameterTypeMatchesParamsElementType([NotNullWhen(true)] IParameterSymbol? parameter, ITypeSymbol castType, SemanticModel semanticModel)
{
if (parameter?.IsParams == true)
{
// if the method is defined with errors: void M(params int wrongDefined), parameter.IsParams == true but parameter.Type is not an array.
// In such cases is better to be conservative and opt out.
if (!(parameter.Type is IArrayTypeSymbol parameterType))
{
return true;
}
var conversion = semanticModel.Compilation.ClassifyConversion(castType, parameterType);
if (conversion.Exists &&
conversion.IsImplicit)
{
return false;
}
var conversionElementType = semanticModel.Compilation.ClassifyConversion(castType, parameterType.ElementType);
if (conversionElementType.Exists &&
conversionElementType.IsImplicit)
{
return true;
}
}
return false;
}
private static ITypeSymbol? GetOuterCastType(
ExpressionSyntax expression, SemanticModel semanticModel, out bool parentIsIsOrAsExpression)
{
expression = expression.WalkUpParentheses();
parentIsIsOrAsExpression = false;
var parentNode = expression.Parent;
if (parentNode == null)
{
return null;
}
if (parentNode.IsKind(SyntaxKind.CastExpression, out CastExpressionSyntax? castExpression))
{
return semanticModel.GetTypeInfo(castExpression).Type;
}
if (parentNode.IsKind(SyntaxKind.PointerIndirectionExpression))
{
return semanticModel.GetTypeInfo(expression).Type;
}
if (parentNode.IsKind(SyntaxKind.IsExpression) ||
parentNode.IsKind(SyntaxKind.AsExpression))
{
parentIsIsOrAsExpression = true;
return null;
}
if (parentNode.IsKind(SyntaxKind.ArrayRankSpecifier))
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Int32);
}
if (parentNode.IsKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess))
{
if (memberAccess.Expression == expression)
{
var memberSymbol = semanticModel.GetSymbolInfo(memberAccess).Symbol;
if (memberSymbol != null)
{
return memberSymbol.ContainingType;
}
}
}
if (parentNode.IsKind(SyntaxKind.ConditionalExpression) &&
((ConditionalExpressionSyntax)parentNode).Condition == expression)
{
return semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean);
}
if ((parentNode is PrefixUnaryExpressionSyntax || parentNode is PostfixUnaryExpressionSyntax) &&
!semanticModel.GetConversion(expression).IsUserDefined)
{
var parentExpression = (ExpressionSyntax)parentNode;
return GetOuterCastType(parentExpression, semanticModel, out parentIsIsOrAsExpression) ?? semanticModel.GetTypeInfo(parentExpression).ConvertedType;
}
if (parentNode is InterpolationSyntax)
{
// $"{(x)y}"
//
// Regardless of the cast to 'x', being in an interpolation automatically casts the result to object
// since this becomes a call to: FormattableStringFactory.Create(string, params object[]).
return semanticModel.Compilation.ObjectType;
}
return null;
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/ParameterModifiersKeywordRecommenderTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class ParameterModifiersKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForFirstParameterTest()
VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(|</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForSecondParameterAfterByRefFirstTest()
VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(ByRef first As Integer, |</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForSecondParameterAfterByValFirstTest()
VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(ByVal first As Integer, |</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForFirstParameterAfterGenericParamsTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(Of T)(|</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ByValAndByRefAfterOptionalTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(Optional |</ClassDeclaration>, "ByVal", "ByRef")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterOptionalByValTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(Optional ByVal |</ClassDeclaration>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByRefOptionalTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(ByRef Optional |</ClassDeclaration>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByValOptionalTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(ByVal Optional |</ClassDeclaration>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterOptionalByRefTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(Optional ByRef |</ClassDeclaration>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ByValAfterParamArrayTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(ParamArray |</ClassDeclaration>, "ByVal")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterPreviousParamArrayTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(ParamArray arg1 As Integer(), |</ClassDeclaration>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OptionalRecommendedAfterPreviousOptionalTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(Optional arg1 = 2, |</ClassDeclaration>, "Optional")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NoByRefByValOrParamArrayAfterByValTest()
VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo(ByVal |, |</ClassDeclaration>, "ByVal", "ByRef", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NoByRefByValAfterByRefTest()
VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo(ByRef |, |</ClassDeclaration>, "ByVal", "ByRef")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllAppropriateInPropertyParametersTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Property Goo(| As Integer</ClassDeclaration>, "ByVal", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllInExternalMethodDeclarationTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Declare Sub Goo Lib "goo.dll" (|</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllInExternalDelegateDeclarationTest()
VerifyRecommendationsContain(<ClassDeclaration>Delegate Sub Goo(|</ClassDeclaration>, "ByVal", "ByRef")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForSubLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Sub(|</MethodBody>, "ByVal", "ByRef")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByValInSubLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Sub(ByVal |</MethodBody>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByRefInSubLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Sub(ByRef |</MethodBody>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForFunctionLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Function(|</MethodBody>, "ByVal", "ByRef")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForEventTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Event MyEvent(|</ClassDeclaration>, "ByVal", "ByRef")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByValInFunctionLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Function(ByVal |</MethodBody>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByRefInFunctionLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Function(ByRef |</MethodBody>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForFirstParameterOfOperatorTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Shared Operator &(|</ClassDeclaration>, "ByVal")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForSecondParameterOfOperatorTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Shared Operator &(i As Integer, |</ClassDeclaration>, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForPropertyAccessorTest()
VerifyRecommendationsAreExactly(<PropertyDeclaration>Set(| value As String)</PropertyDeclaration>, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForAddHandlerAccessorTest()
VerifyRecommendationsAreExactly(<CustomEventDeclaration>AddHandler(| value As EventHandler)</CustomEventDeclaration>, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForRemoveHandlerAccessorTest()
VerifyRecommendationsAreExactly(<CustomEventDeclaration>RemoveHandler(| value As EventHandler)</CustomEventDeclaration>, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForRemoveHandlerWhenAllAccessorsPresentTest()
Dim code =
<File>
Class C
Public Custom Event Click As EventHandler
AddHandler(v As EventHandler)
End AddHandler
RemoveHandler(| value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, e As EventArgs)
End RaiseEvent
End Event
End Class
</File>
VerifyRecommendationsAreExactly(code, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForRaiseEventHandlerAccessorTest()
VerifyRecommendationsAreExactly(<CustomEventDeclaration>RaiseEvent(| sender As Object, e As EventArgs)</CustomEventDeclaration>, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForRaiseEventHandlerWhenAllAccessorsPresentTest()
Dim code =
<File>
Class C
Public Custom Event Click As EventHandler
AddHandler(v As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(| sender As Object, e As EventArgs)
End RaiseEvent
End Event
End Class
</File>
VerifyRecommendationsAreExactly(code, "ByVal")
End Sub
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterLineContinuationTest()
VerifyRecommendationsContain(
<ClassDeclaration>Sub Goo(
|</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class ParameterModifiersKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForFirstParameterTest()
VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(|</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForSecondParameterAfterByRefFirstTest()
VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(ByRef first As Integer, |</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForSecondParameterAfterByValFirstTest()
VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(ByVal first As Integer, |</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForFirstParameterAfterGenericParamsTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(Of T)(|</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ByValAndByRefAfterOptionalTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(Optional |</ClassDeclaration>, "ByVal", "ByRef")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterOptionalByValTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(Optional ByVal |</ClassDeclaration>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByRefOptionalTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(ByRef Optional |</ClassDeclaration>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByValOptionalTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(ByVal Optional |</ClassDeclaration>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterOptionalByRefTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(Optional ByRef |</ClassDeclaration>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub ByValAfterParamArrayTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(ParamArray |</ClassDeclaration>, "ByVal")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterPreviousParamArrayTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(ParamArray arg1 As Integer(), |</ClassDeclaration>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OptionalRecommendedAfterPreviousOptionalTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Sub Goo(Optional arg1 = 2, |</ClassDeclaration>, "Optional")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NoByRefByValOrParamArrayAfterByValTest()
VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo(ByVal |, |</ClassDeclaration>, "ByVal", "ByRef", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NoByRefByValAfterByRefTest()
VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo(ByRef |, |</ClassDeclaration>, "ByVal", "ByRef")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllAppropriateInPropertyParametersTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Property Goo(| As Integer</ClassDeclaration>, "ByVal", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllInExternalMethodDeclarationTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Declare Sub Goo Lib "goo.dll" (|</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllInExternalDelegateDeclarationTest()
VerifyRecommendationsContain(<ClassDeclaration>Delegate Sub Goo(|</ClassDeclaration>, "ByVal", "ByRef")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForSubLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Sub(|</MethodBody>, "ByVal", "ByRef")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByValInSubLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Sub(ByVal |</MethodBody>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByRefInSubLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Sub(ByRef |</MethodBody>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForFunctionLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Function(|</MethodBody>, "ByVal", "ByRef")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AllRecommendationsForEventTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Event MyEvent(|</ClassDeclaration>, "ByVal", "ByRef")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByValInFunctionLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Function(ByVal |</MethodBody>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NothingAfterByRefInFunctionLambdaTest()
VerifyRecommendationsAreExactly(<MethodBody>Dim x = Function(ByRef |</MethodBody>, {})
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForFirstParameterOfOperatorTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Shared Operator &(|</ClassDeclaration>, "ByVal")
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForSecondParameterOfOperatorTest()
VerifyRecommendationsAreExactly(<ClassDeclaration>Shared Operator &(i As Integer, |</ClassDeclaration>, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForPropertyAccessorTest()
VerifyRecommendationsAreExactly(<PropertyDeclaration>Set(| value As String)</PropertyDeclaration>, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForAddHandlerAccessorTest()
VerifyRecommendationsAreExactly(<CustomEventDeclaration>AddHandler(| value As EventHandler)</CustomEventDeclaration>, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForRemoveHandlerAccessorTest()
VerifyRecommendationsAreExactly(<CustomEventDeclaration>RemoveHandler(| value As EventHandler)</CustomEventDeclaration>, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForRemoveHandlerWhenAllAccessorsPresentTest()
Dim code =
<File>
Class C
Public Custom Event Click As EventHandler
AddHandler(v As EventHandler)
End AddHandler
RemoveHandler(| value As EventHandler)
End RemoveHandler
RaiseEvent(ByVal sender As Object, e As EventArgs)
End RaiseEvent
End Event
End Class
</File>
VerifyRecommendationsAreExactly(code, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForRaiseEventHandlerAccessorTest()
VerifyRecommendationsAreExactly(<CustomEventDeclaration>RaiseEvent(| sender As Object, e As EventArgs)</CustomEventDeclaration>, "ByVal")
End Sub
<WorkItem(529209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529209")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub OnlyByValForRaiseEventHandlerWhenAllAccessorsPresentTest()
Dim code =
<File>
Class C
Public Custom Event Click As EventHandler
AddHandler(v As EventHandler)
End AddHandler
RemoveHandler(ByVal value As EventHandler)
End RemoveHandler
RaiseEvent(| sender As Object, e As EventArgs)
End RaiseEvent
End Event
End Class
</File>
VerifyRecommendationsAreExactly(code, "ByVal")
End Sub
<WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub AfterLineContinuationTest()
VerifyRecommendationsContain(
<ClassDeclaration>Sub Goo(
|</ClassDeclaration>, "ByVal", "ByRef", "Optional", "ParamArray")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/VisualBasic/Portable/Binding/Binder_Delegates.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Binder
''' <summary>
''' Structure is used to store all information which is needed to construct and classify a Delegate creation
''' expression later on.
''' </summary>
Friend Structure DelegateResolutionResult
' we store the DelegateConversions although it could be derived from MethodConversions to improve performance
Public ReadOnly DelegateConversions As ConversionKind
Public ReadOnly Target As MethodSymbol
Public ReadOnly MethodConversions As MethodConversionKind
Public ReadOnly Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
Public Sub New(
DelegateConversions As ConversionKind,
Target As MethodSymbol,
MethodConversions As MethodConversionKind,
Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
)
Me.DelegateConversions = DelegateConversions
Me.Target = Target
Me.Diagnostics = Diagnostics
Me.MethodConversions = MethodConversions
End Sub
End Structure
''' <summary>
''' Binds the AddressOf expression.
''' </summary>
''' <param name="node">The AddressOf expression node.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function BindAddressOfExpression(node As VisualBasicSyntaxNode, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim addressOfSyntax = DirectCast(node, UnaryExpressionSyntax)
Dim boundOperand = BindExpression(addressOfSyntax.Operand, isInvocationOrAddressOf:=True, diagnostics:=diagnostics, isOperandOfConditionalBranch:=False, eventContext:=False)
If boundOperand.Kind = BoundKind.LateMemberAccess Then
Return New BoundLateAddressOfOperator(node, Me, DirectCast(boundOperand, BoundLateMemberAccess), boundOperand.Type)
End If
' only accept MethodGroups as operands. More detailed checks (e.g. for Constructors follow later)
If boundOperand.Kind <> BoundKind.MethodGroup Then
If Not boundOperand.HasErrors Then
ReportDiagnostic(diagnostics, addressOfSyntax.Operand, ERRID.ERR_AddressOfOperandNotMethod)
End If
Return BadExpression(addressOfSyntax, boundOperand, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType)
End If
Dim hasErrors As Boolean = False
Dim group = DirectCast(boundOperand, BoundMethodGroup)
If IsGroupOfConstructors(group) Then
ReportDiagnostic(diagnostics, addressOfSyntax.Operand, ERRID.ERR_InvalidConstructorCall)
hasErrors = True
End If
Return New BoundAddressOfOperator(node, Me, diagnostics.AccumulatesDependencies, group, hasErrors)
End Function
''' <summary>
''' Binds the delegate creation expression.
''' This comes in form of e.g.
''' Dim del as new DelegateType(AddressOf methodName)
''' </summary>
''' <param name="delegateType">Type of the delegate.</param>
''' <param name="argumentListOpt">The argument list.</param>
''' <param name="node">Syntax node to attach diagnostics to in case the argument list is nothing.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function BindDelegateCreationExpression(
delegateType As TypeSymbol,
argumentListOpt As ArgumentListSyntax,
node As VisualBasicSyntaxNode,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim boundFirstArgument As BoundExpression = Nothing
Dim argumentCount = 0
If argumentListOpt IsNot Nothing Then
argumentCount = argumentListOpt.Arguments.Count
End If
Dim hadErrorsInFirstArgument = False
' a delegate creation expression should have exactly one argument.
If argumentCount > 0 Then
Dim argumentSyntax = argumentListOpt.Arguments(0)
Dim expressionSyntax As ExpressionSyntax = Nothing
' a delegate creation expression does not care if what the name of a named argument
' was. Just take whatever was passed.
If argumentSyntax.Kind = SyntaxKind.SimpleArgument Then
expressionSyntax = argumentSyntax.GetExpression()
End If
' omitted argument will leave expressionSyntax as nothing which means no binding, which is fine.
If expressionSyntax IsNot Nothing Then
If expressionSyntax.Kind = SyntaxKind.AddressOfExpression Then
boundFirstArgument = BindAddressOfExpression(expressionSyntax, diagnostics)
ElseIf expressionSyntax.IsLambdaExpressionSyntax() Then
' this covers the legal cases for SyntaxKind.MultiLineFunctionLambdaExpression,
' SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression and
' SyntaxKind.SingleLineSubLambdaExpression, as well as all the other invalid ones.
boundFirstArgument = BindExpression(expressionSyntax, diagnostics)
End If
If boundFirstArgument IsNot Nothing Then
hadErrorsInFirstArgument = boundFirstArgument.HasErrors
Debug.Assert(boundFirstArgument.Kind = BoundKind.BadExpression OrElse
boundFirstArgument.Kind = BoundKind.LateAddressOfOperator OrElse
boundFirstArgument.Kind = BoundKind.AddressOfOperator OrElse
boundFirstArgument.Kind = BoundKind.UnboundLambda)
If argumentCount = 1 Then
boundFirstArgument = ApplyImplicitConversion(node,
delegateType,
boundFirstArgument,
diagnostics:=diagnostics)
If boundFirstArgument.Syntax IsNot node Then
' We must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(boundFirstArgument.Kind <> BoundKind.Conversion, "Associated wrong node with conversion?")
boundFirstArgument = New BoundConversion(node, boundFirstArgument, ConversionKind.Identity, CheckOverflow, True, delegateType)
ElseIf boundFirstArgument.Kind = BoundKind.Conversion Then
Debug.Assert(Not boundFirstArgument.WasCompilerGenerated)
Dim boundConversion = DirectCast(boundFirstArgument, BoundConversion)
boundFirstArgument = boundConversion.Update(boundConversion.Operand,
boundConversion.ConversionKind,
boundConversion.Checked,
True, ' ExplicitCastInCode
boundConversion.ConstantValueOpt,
boundConversion.ExtendedInfoOpt,
boundConversion.Type)
End If
Return boundFirstArgument
End If
End If
Else
boundFirstArgument = New BoundBadExpression(argumentSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundExpression).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
End If
Dim boundArguments(argumentCount - 1) As BoundExpression
If boundFirstArgument IsNot Nothing Then
boundFirstArgument = MakeRValueAndIgnoreDiagnostics(boundFirstArgument)
boundArguments(0) = boundFirstArgument
End If
' bind all arguments and ignore all diagnostics. These bound nodes will be passed to
' a BoundBadNode
For argumentIndex = If(boundFirstArgument Is Nothing, 0, 1) To argumentCount - 1
Dim expressionSyntax As ExpressionSyntax = Nothing
Dim argumentSyntax = argumentListOpt.Arguments(argumentIndex)
If argumentSyntax.Kind = SyntaxKind.SimpleArgument Then
expressionSyntax = argumentSyntax.GetExpression()
End If
If expressionSyntax IsNot Nothing Then
boundArguments(argumentIndex) = BindValue(expressionSyntax, BindingDiagnosticBag.Discarded)
Else
boundArguments(argumentIndex) = New BoundBadExpression(argumentSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundExpression).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
Next
' the default error message in delegate creations if the passed arguments are empty or not a addressOf
' should be ERRID.ERR_NoDirectDelegateConstruction1
' if binding an AddressOf expression caused diagnostics these should be shown instead
If Not hadErrorsInFirstArgument OrElse
argumentCount <> 1 Then
ReportDiagnostic(diagnostics,
If(argumentListOpt, node),
ERRID.ERR_NoDirectDelegateConstruction1,
delegateType)
End If
Return BadExpression(node,
ImmutableArray.Create(boundArguments),
delegateType)
End Function
''' <summary>
''' Resolves the target method for the delegate and classifies the conversion
''' </summary>
''' <param name="addressOfExpression">The bound AddressOf expression itself.</param>
''' <param name="targetType">The delegate type to assign the result of the AddressOf operator to.</param>
''' <returns></returns>
Friend Shared Function InterpretDelegateBinding(
addressOfExpression As BoundAddressOfOperator,
targetType As TypeSymbol,
isForHandles As Boolean
) As DelegateResolutionResult
Debug.Assert(targetType IsNot Nothing)
Dim diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics:=True, addressOfExpression.WithDependencies)
Dim result As OverloadResolution.OverloadResolutionResult = Nothing
Dim fromMethod As MethodSymbol = Nothing
Dim syntaxTree = addressOfExpression.Syntax
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' must be a delegate, and also a concrete delegate
If targetType.SpecialType = SpecialType.System_Delegate OrElse
targetType.SpecialType = SpecialType.System_MulticastDelegate Then
' 'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_AddressOfNotCreatableDelegate1, targetType)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
ElseIf targetType.TypeKind <> TypeKind.Delegate Then
' 'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.
If targetType.TypeKind <> TypeKind.Error Then
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_AddressOfNotDelegate1, targetType)
End If
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
Dim delegateInvoke = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod
If delegateInvoke IsNot Nothing Then
If ReportDelegateInvokeUseSite(diagnostics, syntaxTree, targetType, delegateInvoke) Then
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
' todo(rbeckers) if (IsLateReference(addressOfExpression))
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = ResolveMethodForDelegateInvokeFullAndRelaxed(
addressOfExpression,
delegateInvoke,
False,
diagnostics)
fromMethod = matchingMethod.Key
methodConversions = matchingMethod.Value
End If
Else
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_UnsupportedMethod1, targetType)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
End If
' show diagnostics if the an instance method is used in a shared context.
If fromMethod IsNot Nothing Then
' Generate an error, but continue processing
If addressOfExpression.Binder.CheckSharedSymbolAccess(addressOfExpression.Syntax,
fromMethod.IsShared,
addressOfExpression.MethodGroup.ReceiverOpt,
addressOfExpression.MethodGroup.QualificationKind,
diagnostics) Then
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
End If
' TODO: Check boxing of restricted types, report ERRID_RestrictedConversion1 and continue.
Dim receiver As BoundExpression = addressOfExpression.MethodGroup.ReceiverOpt
If fromMethod IsNot Nothing Then
If fromMethod.IsMustOverride AndAlso receiver IsNot Nothing AndAlso
(receiver.IsMyBaseReference OrElse receiver.IsMyClassReference) Then
' Generate an error, but continue processing
ReportDiagnostic(diagnostics, addressOfExpression.MethodGroup.Syntax,
If(receiver.IsMyBaseReference,
ERRID.ERR_MyBaseAbstractCall1,
ERRID.ERR_MyClassAbstractCall1),
fromMethod)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
If Not fromMethod.IsShared AndAlso
fromMethod.ContainingType.IsNullableType AndAlso
Not fromMethod.IsOverrides Then
Dim addressOfSyntax As SyntaxNode = addressOfExpression.Syntax
Dim addressOfExpressionSyntax = DirectCast(addressOfExpression.Syntax, UnaryExpressionSyntax)
If (addressOfExpressionSyntax IsNot Nothing) Then
addressOfSyntax = addressOfExpressionSyntax.Operand
End If
' Generate an error, but continue processing
ReportDiagnostic(diagnostics,
addressOfSyntax,
ERRID.ERR_AddressOfNullableMethod,
fromMethod.ContainingType,
SyntaxFacts.GetText(SyntaxKind.AddressOfKeyword))
' There's no real need to set MethodConversionKind.Error because there are no overloads of the same method where one
' may be legal to call because it's shared and the other's not.
' However to be future proof, we set it regardless.
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
addressOfExpression.Binder.ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagnostics, fromMethod, addressOfExpression.MethodGroup.Syntax)
End If
Dim delegateConversions As ConversionKind = Conversions.DetermineDelegateRelaxationLevel(methodConversions)
If (delegateConversions And ConversionKind.DelegateRelaxationLevelInvalid) <> ConversionKind.DelegateRelaxationLevelInvalid Then
If Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=Not isForHandles) Then
delegateConversions = delegateConversions Or ConversionKind.Narrowing
Else
delegateConversions = delegateConversions Or ConversionKind.Widening
End If
End If
Return New DelegateResolutionResult(delegateConversions, fromMethod, methodConversions, diagnostics.ToReadOnlyAndFree())
End Function
Friend Shared Function ReportDelegateInvokeUseSite(
diagBag As BindingDiagnosticBag,
syntax As SyntaxNode,
delegateType As TypeSymbol,
invoke As MethodSymbol
) As Boolean
Debug.Assert(delegateType IsNot Nothing)
Debug.Assert(invoke IsNot Nothing)
Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = invoke.GetUseSiteInfo()
If useSiteInfo.DiagnosticInfo?.Code = ERRID.ERR_UnsupportedMethod1 Then
useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedMethod1, delegateType))
End If
Return diagBag.Add(useSiteInfo, syntax)
End Function
''' <summary>
''' Resolves the method for delegate invoke with all or relaxed arguments / return types. It also determines
''' the method conversion kind.
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="toMethod">The delegate invoke method.</param>
''' <param name="ignoreMethodReturnType">Ignore method's return type for the purpose of calculating 'methodConversions'.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <returns>The resolved method if any.</returns>
Friend Shared Function ResolveMethodForDelegateInvokeFullAndRelaxed(
addressOfExpression As BoundAddressOfOperator,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
diagnostics As BindingDiagnosticBag
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim argumentDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics)
Dim couldTryZeroArgumentRelaxation As Boolean = True
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression,
toMethod,
ignoreMethodReturnType,
argumentDiagnostics,
useZeroArgumentRelaxation:=False,
couldTryZeroArgumentRelaxation:=couldTryZeroArgumentRelaxation)
' If there have been parameters and if there was no ambiguous match before, try zero argument relaxation.
If matchingMethod.Key Is Nothing AndAlso couldTryZeroArgumentRelaxation Then
Dim zeroArgumentDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics)
Dim argumentMatchingMethod = matchingMethod
matchingMethod = ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression,
toMethod,
ignoreMethodReturnType,
zeroArgumentDiagnostics,
useZeroArgumentRelaxation:=True,
couldTryZeroArgumentRelaxation:=couldTryZeroArgumentRelaxation)
' if zero relaxation did not find something, we'll report the diagnostics of the
' non zero relaxation try, else the diagnostics of the zero argument relaxation.
If matchingMethod.Key Is Nothing Then
diagnostics.AddRange(argumentDiagnostics)
matchingMethod = argumentMatchingMethod
Else
diagnostics.AddRange(zeroArgumentDiagnostics)
End If
zeroArgumentDiagnostics.Free()
Else
diagnostics.AddRange(argumentDiagnostics)
End If
argumentDiagnostics.Free()
' check that there's not method returned if there is no conversion.
Debug.Assert(matchingMethod.Key Is Nothing OrElse (matchingMethod.Value And MethodConversionKind.AllErrorReasons) = 0)
Return matchingMethod
End Function
''' <summary>
''' Resolves the method for delegate invoke with all or relaxed arguments / return types. It also determines
''' the method conversion kind.
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="toMethod">The delegate invoke method.</param>
''' <param name="ignoreMethodReturnType">Ignore method's return type for the purpose of calculating 'methodConversions'.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <param name="useZeroArgumentRelaxation">if set to <c>true</c> use zero argument relaxation.</param>
''' <returns>The resolved method if any.</returns>
Private Shared Function ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression As BoundAddressOfOperator,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
diagnostics As BindingDiagnosticBag,
useZeroArgumentRelaxation As Boolean,
ByRef couldTryZeroArgumentRelaxation As Boolean
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim boundArguments = ImmutableArray(Of BoundExpression).Empty
If Not useZeroArgumentRelaxation Then
' build array of bound expressions for overload resolution (BoundLocal is easy to create)
Dim toMethodParameters = toMethod.Parameters
Dim parameterCount = toMethodParameters.Length
If parameterCount > 0 Then
Dim boundParameterArguments(parameterCount - 1) As BoundExpression
Dim argumentIndex As Integer = 0
Dim syntaxTree As SyntaxTree
Dim addressOfSyntax = addressOfExpression.Syntax
syntaxTree = addressOfExpression.Binder.SyntaxTree
For Each parameter In toMethodParameters
Dim parameterType = parameter.Type
Dim tempParamSymbol = New SynthesizedLocal(toMethod, parameterType, SynthesizedLocalKind.LoweringTemp)
' TODO: Switch to using BoundValuePlaceholder, but we need it to be able to appear
' as an LValue in case of a ByRef parameter.
Dim tempBoundParameter As BoundExpression = New BoundLocal(addressOfSyntax,
tempParamSymbol,
parameterType)
' don't treat ByVal parameters as lvalues in the following OverloadResolution
If Not parameter.IsByRef Then
tempBoundParameter = tempBoundParameter.MakeRValue()
End If
boundParameterArguments(argumentIndex) = tempBoundParameter
argumentIndex += 1
Next
boundArguments = boundParameterArguments.AsImmutableOrNull()
Else
couldTryZeroArgumentRelaxation = False
End If
End If
Dim delegateReturnType As TypeSymbol
Dim delegateReturnTypeReferenceBoundNode As BoundNode
If ignoreMethodReturnType Then
' Keep them Nothing such that the delegate's return type won't be taken part of in overload resolution
' when we are inferring the return type.
delegateReturnType = Nothing
delegateReturnTypeReferenceBoundNode = Nothing
Else
delegateReturnType = toMethod.ReturnType
delegateReturnTypeReferenceBoundNode = addressOfExpression
End If
' Let's go through overload resolution, pretending that Option Strict is Off and see if it succeeds.
Dim resolutionBinder As Binder
If addressOfExpression.Binder.OptionStrict <> VisualBasic.OptionStrict.Off Then
resolutionBinder = New OptionStrictOffBinder(addressOfExpression.Binder)
Else
resolutionBinder = addressOfExpression.Binder
End If
Debug.Assert(resolutionBinder.OptionStrict = VisualBasic.OptionStrict.Off)
Dim useSiteInfo = addressOfExpression.Binder.GetNewCompoundUseSiteInfo(diagnostics)
Dim resolutionResult = OverloadResolution.MethodInvocationOverloadResolution(
addressOfExpression.MethodGroup,
boundArguments,
Nothing,
resolutionBinder,
includeEliminatedCandidates:=False,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
lateBindingIsAllowed:=False,
callerInfoOpt:=Nothing,
useSiteInfo:=useSiteInfo)
If diagnostics.Add(addressOfExpression.MethodGroup, useSiteInfo) Then
couldTryZeroArgumentRelaxation = False
If addressOfExpression.MethodGroup.ResultKind <> LookupResultKind.Inaccessible Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
Dim addressOfMethodGroup = addressOfExpression.MethodGroup
If resolutionResult.BestResult.HasValue Then
Return ValidateMethodForDelegateInvoke(
addressOfExpression,
resolutionResult.BestResult.Value,
toMethod,
ignoreMethodReturnType,
useZeroArgumentRelaxation,
diagnostics)
End If
' Overload Resolution didn't find a match
If resolutionResult.Candidates.Length = 0 Then
resolutionResult = OverloadResolution.MethodInvocationOverloadResolution(
addressOfMethodGroup,
boundArguments,
Nothing,
resolutionBinder,
includeEliminatedCandidates:=True,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
lateBindingIsAllowed:=False,
callerInfoOpt:=Nothing,
useSiteInfo:=useSiteInfo)
End If
Dim bestCandidates = ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult).GetInstance()
Dim bestSymbols = ImmutableArray(Of Symbol).Empty
Dim commonReturnType As TypeSymbol = GetSetOfTheBestCandidates(resolutionResult, bestCandidates, bestSymbols)
Debug.Assert(bestCandidates.Count > 0 AndAlso bestCandidates.Count > 0)
Dim bestCandidatesState As OverloadResolution.CandidateAnalysisResultState = bestCandidates(0).State
If bestCandidatesState = VisualBasic.OverloadResolution.CandidateAnalysisResultState.Applicable Then
' if there is an applicable candidate in the list, we know it must be an ambiguous match
' (or there are more applicable candidates in this list), otherwise this would have been
' the best match.
Debug.Assert(bestCandidates.Count > 1 AndAlso bestSymbols.Length > 1)
' there are multiple candidates, so it ambiguous and zero argument relaxation will not be tried,
' unless the candidates require narrowing.
If Not bestCandidates(0).RequiresNarrowingConversion Then
couldTryZeroArgumentRelaxation = False
End If
End If
If bestSymbols.Length = 1 AndAlso
(bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch) Then
' Dev10 has squiggles under the operand of the AddressOf. The syntax of addressOfExpression
' is the complete AddressOf expression, so we need to get the operand first.
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics, addressOfOperandSyntax,
addressOfExpression.Binder.GetInaccessibleErrorInfo(
bestSymbols(0)))
Else
Debug.Assert(addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good)
End If
ReportDelegateBindingIncompatible(
addressOfOperandSyntax,
toMethod.ContainingType,
DirectCast(bestSymbols(0), MethodSymbol),
diagnostics)
Else
If bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.HasUseSiteError OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.Ambiguous Then
couldTryZeroArgumentRelaxation = False
End If
Dim unused = resolutionBinder.ReportOverloadResolutionFailureAndProduceBoundNode(
addressOfExpression.MethodGroup.Syntax,
addressOfMethodGroup,
bestCandidates,
bestSymbols,
commonReturnType,
boundArguments,
Nothing,
diagnostics,
delegateSymbol:=toMethod.ContainingType,
callerInfoOpt:=Nothing)
End If
bestCandidates.Free()
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(Nothing, MethodConversionKind.Error_OverloadResolution)
End Function
Private Shared Function ValidateMethodForDelegateInvoke(
addressOfExpression As BoundAddressOfOperator,
analysisResult As OverloadResolution.CandidateAnalysisResult,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
useZeroArgumentRelaxation As Boolean,
diagnostics As BindingDiagnosticBag
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' Dev10 has squiggles under the operand of the AddressOf. The syntax of addressOfExpression
' is the complete AddressOf expression, so we need to get the operand first.
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
' determine conversions based on return type
Dim useSiteInfo = addressOfExpression.Binder.GetNewCompoundUseSiteInfo(diagnostics)
Dim targetMethodSymbol = DirectCast(analysisResult.Candidate.UnderlyingSymbol, MethodSymbol)
If Not ignoreMethodReturnType Then
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnReturn(targetMethodSymbol.ReturnType, targetMethodSymbol.ReturnsByRef,
toMethod.ReturnType, toMethod.ReturnsByRef, useSiteInfo)
If diagnostics.Add(addressOfOperandSyntax, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
If useZeroArgumentRelaxation Then
Debug.Assert(toMethod.ParameterCount > 0)
' special flag for ignoring all arguments (zero argument relaxation)
If targetMethodSymbol.ParameterCount = 0 Then
methodConversions = methodConversions Or MethodConversionKind.AllArgumentsIgnored
Else
' We can get here if all method's parameters are Optional/ParamArray, however,
' according to the language spec, zero arguments relaxation is allowed only
' if target method has no parameters. Here is the quote:
' "method referenced by the method pointer, but it is not applicable due to
' the fact that it has no parameters and the delegate type does, then the method
' is considered applicable and the parameters are simply ignored."
'
' There is a bug in Dev10, sometimes it erroneously allows zero-argument relaxation against
' a method with optional parameters, if parameters of the delegate invoke can be passed to
' the method (i.e. without dropping them). See unit-test Bug12211 for an example.
methodConversions = methodConversions Or MethodConversionKind.Error_IllegalToIgnoreAllArguments
End If
Else
' determine conversions based on arguments
methodConversions = methodConversions Or GetDelegateMethodConversionBasedOnArguments(analysisResult, toMethod, useSiteInfo)
If diagnostics.Add(addressOfOperandSyntax, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
' Stubs for ByRef returning methods are not supported.
' We could easily support a stub for the case when return value is dropped,
' but enabling other kinds of stubs later can lead to breaking changes
' because those relaxations could be "better".
If Not ignoreMethodReturnType AndAlso targetMethodSymbol.ReturnsByRef AndAlso
Conversions.IsDelegateRelaxationSupportedFor(methodConversions) AndAlso
Conversions.IsStubRequiredForMethodConversion(methodConversions) Then
methodConversions = methodConversions Or MethodConversionKind.Error_StubNotSupported
End If
If Conversions.IsDelegateRelaxationSupportedFor(methodConversions) Then
Dim typeArgumentInferenceDiagnosticsOpt = analysisResult.TypeArgumentInferenceDiagnosticsOpt
If typeArgumentInferenceDiagnosticsOpt IsNot Nothing Then
diagnostics.AddRange(typeArgumentInferenceDiagnosticsOpt)
End If
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good Then
addressOfExpression.Binder.CheckMemberTypeAccessibility(diagnostics, addressOfOperandSyntax, targetMethodSymbol)
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(targetMethodSymbol, methodConversions)
End If
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
ReportDelegateBindingIncompatible(
addressOfOperandSyntax,
toMethod.ContainingType,
targetMethodSymbol,
diagnostics)
End If
Debug.Assert((methodConversions And MethodConversionKind.AllErrorReasons) <> 0)
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics, addressOfOperandSyntax,
addressOfExpression.Binder.GetInaccessibleErrorInfo(
analysisResult.Candidate.UnderlyingSymbol))
Else
Debug.Assert(addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good)
End If
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(Nothing, methodConversions)
End Function
Private Shared Sub ReportDelegateBindingMismatchStrictOff(
syntax As SyntaxNode,
delegateType As NamedTypeSymbol,
targetMethodSymbol As MethodSymbol,
diagnostics As BindingDiagnosticBag
)
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
If targetMethodSymbol.ReducedFrom Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingMismatchStrictOff2,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType))
Else
' This is an extension method.
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingMismatchStrictOff3,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType),
targetMethodSymbol.ContainingType)
End If
End Sub
Private Shared Sub ReportDelegateBindingIncompatible(
syntax As SyntaxNode,
delegateType As NamedTypeSymbol,
targetMethodSymbol As MethodSymbol,
diagnostics As BindingDiagnosticBag
)
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
If targetMethodSymbol.ReducedFrom Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingIncompatible2,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType))
Else
' This is an extension method.
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingIncompatible3,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType),
targetMethodSymbol.ContainingType)
End If
End Sub
''' <summary>
''' Determines the method conversion for delegates based on the arguments.
''' </summary>
''' <param name="bestResult">The resolution result.</param>
''' <param name="delegateInvoke">The delegate invoke method.</param>
Private Shared Function GetDelegateMethodConversionBasedOnArguments(
bestResult As OverloadResolution.CandidateAnalysisResult,
delegateInvoke As MethodSymbol,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As MethodConversionKind
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' in contrast to the native compiler we know that there is a legal conversion and we do not
' need to classify invalid conversions.
' however there is still the ParamArray expansion that needs special treatment.
' if there is one conversion needed, the array ConversionsOpt contains all conversions for all used parameters
' (including e.g. identity conversion). If a ParamArray was expanded, there will be a conversion for each
' expanded parameter.
Dim bestCandidate As OverloadResolution.Candidate = bestResult.Candidate
Dim candidateParameterCount = bestCandidate.ParameterCount
Dim candidateLastParameterIndex = candidateParameterCount - 1
Dim delegateParameterCount = delegateInvoke.ParameterCount
Dim lastCommonIndex = Math.Min(candidateParameterCount, delegateParameterCount) - 1
' IsExpandedParamArrayForm is true if there was no, one or more parameters given for the ParamArray
' Note: if an array was passed, IsExpandedParamArrayForm is false.
If bestResult.IsExpandedParamArrayForm Then
' Dev10 always sets the ExcessOptionalArgumentsOnTarget whenever the last parameter of the target was a
' ParamArray. This forces a stub for the ParamArray conversion, that is needed for the ParamArray in any case.
methodConversions = methodConversions Or MethodConversionKind.ExcessOptionalArgumentsOnTarget
ElseIf candidateParameterCount > delegateParameterCount Then
' An omission of optional parameters for expanded ParamArray form doesn't add anything new for
' the method conversion. Non-expanded ParamArray form, would be dismissed by overload resolution
' if there were omitted optional parameters because it is illegal to omit the ParamArray argument
' in non-expanded form.
' there are optional parameters that have not been exercised by the delegate.
' e.g. Delegate Sub(b As Byte) -> Sub Target(b As Byte, Optional c as Byte)
methodConversions = methodConversions Or MethodConversionKind.ExcessOptionalArgumentsOnTarget
#If DEBUG Then
' check that all unused parameters on the target are optional
For parameterIndex = delegateParameterCount To candidateParameterCount - 1
Debug.Assert(bestCandidate.Parameters(parameterIndex).IsOptional)
Next
#End If
ElseIf lastCommonIndex >= 0 AndAlso
bestCandidate.Parameters(lastCommonIndex).IsParamArray AndAlso
delegateInvoke.Parameters(lastCommonIndex).IsByRef AndAlso
bestCandidate.Parameters(lastCommonIndex).IsByRef AndAlso
Not bestResult.ConversionsOpt.IsDefaultOrEmpty AndAlso
Not Conversions.IsIdentityConversion(bestResult.ConversionsOpt(lastCommonIndex).Key) Then
' Dev10 has the following behavior that needs to be re-implemented:
' Using
' Sub Target(ByRef Base())
' with a
' Delegate Sub Del(ByRef ParamArray Base())
' does not create a stub and the values are transported ByRef
' however using a
' Sub Target(ByRef ParamArray Base())
' with a
' Delegate Del(ByRef Derived()) (with or without ParamArray, works with Option Strict Off only)
' creates a stub and transports the values ByVal.
' Note: if the ParamArray is not expanded, the parameter count must match
Debug.Assert(candidateParameterCount = delegateParameterCount)
Debug.Assert(Conversions.IsWideningConversion(bestResult.ConversionsOpt(lastCommonIndex).Key))
Dim conv = Conversions.ClassifyConversion(bestCandidate.Parameters(lastCommonIndex).Type,
delegateInvoke.Parameters(lastCommonIndex).Type,
useSiteInfo)
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conv.Key,
delegateInvoke.Parameters(lastCommonIndex).Type)
End If
' the overload resolution does not consider ByRef/ByVal mismatches, so we need to check the
' parameters here.
' first iterate over the common parameters
For parameterIndex = 0 To lastCommonIndex
If delegateInvoke.Parameters(parameterIndex).IsByRef <> bestCandidate.Parameters(parameterIndex).IsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
Exit For
End If
Next
' after the loop above the remaining parameters on the target can only be optional and/or a ParamArray
If bestResult.IsExpandedParamArrayForm AndAlso
(methodConversions And MethodConversionKind.Error_ByRefByValMismatch) <> MethodConversionKind.Error_ByRefByValMismatch Then
' if delegateParameterCount is smaller than targetParameterCount the for loop does not
' execute
Dim lastTargetParameterIsByRef = bestCandidate.Parameters(candidateLastParameterIndex).IsByRef
Debug.Assert(bestCandidate.Parameters(candidateLastParameterIndex).IsParamArray)
For parameterIndex = lastCommonIndex + 1 To delegateParameterCount - 1
' test against the last parameter of the target method
If delegateInvoke.Parameters(parameterIndex).IsByRef <> lastTargetParameterIsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
Exit For
End If
Next
End If
' there have been conversions, check them all
If Not bestResult.ConversionsOpt.IsDefaultOrEmpty Then
For conversionIndex = 0 To bestResult.ConversionsOpt.Length - 1
Dim conversion = bestResult.ConversionsOpt(conversionIndex)
Dim delegateParameterType = delegateInvoke.Parameters(conversionIndex).Type
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conversion.Key,
delegateParameterType)
Next
End If
' in case of ByRef, there might also be backward conversions
If Not bestResult.ConversionsBackOpt.IsDefaultOrEmpty Then
For conversionIndex = 0 To bestResult.ConversionsBackOpt.Length - 1
Dim conversion = bestResult.ConversionsBackOpt(conversionIndex)
If Not Conversions.IsIdentityConversion(conversion.Key) Then
Dim targetMethodParameterType = bestCandidate.Parameters(conversionIndex).Type
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conversion.Key,
targetMethodParameterType)
End If
Next
End If
Return methodConversions
End Function
''' <summary>
''' Classifies the address of conversion.
''' </summary>
''' <param name="source">The bound AddressOf expression.</param>
''' <param name="destination">The target type to convert this AddressOf expression to.</param><returns></returns>
Friend Shared Function ClassifyAddressOfConversion(
source As BoundAddressOfOperator,
destination As TypeSymbol
) As ConversionKind
Return source.GetConversionClassification(destination)
End Function
Private Shared ReadOnly s_checkDelegateParameterModifierCallback As CheckParameterModifierDelegate = AddressOf CheckDelegateParameterModifier
''' <summary>
''' Checks if a parameter is a ParamArray and reports this as an error.
''' </summary>
''' <param name="container">The containing type.</param>
''' <param name="token">The current parameter token.</param>
''' <param name="flag">The flags of this parameter.</param>
''' <param name="diagnostics">The diagnostics.</param>
Private Shared Function CheckDelegateParameterModifier(
container As Symbol,
token As SyntaxToken,
flag As SourceParameterFlags,
diagnostics As BindingDiagnosticBag
) As SourceParameterFlags
' 9.2.5.4: ParamArray parameters may not be specified in delegate or event declarations.
If (flag And SourceParameterFlags.ParamArray) = SourceParameterFlags.ParamArray Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_ParamArrayIllegal1, location, GetDelegateOrEventKeywordText(container))
flag = flag And (Not SourceParameterFlags.ParamArray)
End If
' 9.2.5.3 Optional parameters may not be specified on delegate or event declarations
If (flag And SourceParameterFlags.Optional) = SourceParameterFlags.Optional Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_OptionalIllegal1, location, GetDelegateOrEventKeywordText(container))
flag = flag And (Not SourceParameterFlags.Optional)
End If
Return flag
End Function
Private Shared Function GetDelegateOrEventKeywordText(sym As Symbol) As String
Dim keyword As SyntaxKind
If sym.Kind = SymbolKind.Event Then
keyword = SyntaxKind.EventKeyword
ElseIf TypeOf sym.ContainingType Is SynthesizedEventDelegateSymbol Then
keyword = SyntaxKind.EventKeyword
Else
keyword = SyntaxKind.DelegateKeyword
End If
Return SyntaxFacts.GetText(keyword)
End Function
''' <summary>
''' Reclassifies the bound address of operator into a delegate creation expression (if there is no delegate
''' relaxation required) or into a bound lambda expression (which gets a delegate creation expression later on)
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="delegateResolutionResult">The delegate resolution result.</param>
''' <param name="targetType">Type of the target.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Friend Function ReclassifyAddressOf(
addressOfExpression As BoundAddressOfOperator,
ByRef delegateResolutionResult As DelegateResolutionResult,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
isForHandles As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean
) As BoundExpression
If addressOfExpression.HasErrors Then
Return addressOfExpression
End If
Dim boundLambda As BoundLambda = Nothing
Dim relaxationReceiverPlaceholder As BoundRValuePlaceholder = Nothing
Dim syntaxNode = addressOfExpression.Syntax
Dim targetMethod As MethodSymbol = delegateResolutionResult.Target
Dim reducedFromDefinition As MethodSymbol = targetMethod.ReducedFrom
Dim sourceMethodGroup = addressOfExpression.MethodGroup
Dim receiver As BoundExpression = sourceMethodGroup.ReceiverOpt
Dim resolvedTypeOrValueReceiver As BoundExpression = Nothing
If receiver IsNot Nothing AndAlso
Not addressOfExpression.HasErrors AndAlso
Not delegateResolutionResult.Diagnostics.Diagnostics.HasAnyErrors Then
receiver = AdjustReceiverTypeOrValue(receiver, receiver.Syntax, targetMethod.IsShared, diagnostics, resolvedTypeOrValueReceiver)
End If
If Me.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingConversion(delegateResolutionResult.DelegateConversions) Then
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
ReportDelegateBindingMismatchStrictOff(addressOfOperandSyntax, DirectCast(targetType, NamedTypeSymbol), targetMethod, diagnostics)
Else
' When the target method is an extension method, we are creating so called curried delegate.
' However, CLR doesn't support creating curried delegates that close over a ByRef 'this' argument.
' A similar problem exists when the 'this' argument is a value type. For these cases we need a stub too,
' but they are not covered by MethodConversionKind.
If Conversions.IsStubRequiredForMethodConversion(delegateResolutionResult.MethodConversions) OrElse
(reducedFromDefinition IsNot Nothing AndAlso
(reducedFromDefinition.Parameters(0).IsByRef OrElse
targetMethod.ReceiverType.IsTypeParameter() OrElse
targetMethod.ReceiverType.IsValueType)) Then
' because of a delegate relaxation there is a conversion needed to create a delegate instance.
' We will create a lambda with the exact signature of the delegate. This lambda itself will
' call the target method.
boundLambda = BuildDelegateRelaxationLambda(syntaxNode, sourceMethodGroup.Syntax, receiver, targetMethod,
sourceMethodGroup.TypeArgumentsOpt, sourceMethodGroup.QualificationKind,
DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod,
delegateResolutionResult.DelegateConversions And ConversionKind.DelegateRelaxationLevelMask,
isZeroArgumentKnownToBeUsed:=(delegateResolutionResult.MethodConversions And MethodConversionKind.AllArgumentsIgnored) <> 0,
diagnostics:=diagnostics,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=warnIfResultOfAsyncMethodIsDroppedDueToRelaxation,
relaxationReceiverPlaceholder:=relaxationReceiverPlaceholder)
End If
End If
Dim target As MethodSymbol = delegateResolutionResult.Target
' Check if the target is a partial method without implementation provided
If Not isForHandles AndAlso target.IsPartialWithoutImplementation Then
ReportDiagnostic(diagnostics, addressOfExpression.MethodGroup.Syntax, ERRID.ERR_NoPartialMethodInAddressOf1, target)
End If
Dim newReceiver As BoundExpression
If receiver IsNot Nothing Then
If receiver.IsPropertyOrXmlPropertyAccess() Then
receiver = MakeRValue(receiver, diagnostics)
End If
newReceiver = Nothing
Else
newReceiver = If(resolvedTypeOrValueReceiver, sourceMethodGroup.ReceiverOpt)
End If
sourceMethodGroup = sourceMethodGroup.Update(sourceMethodGroup.TypeArgumentsOpt,
sourceMethodGroup.Methods,
sourceMethodGroup.PendingExtensionMethodsOpt,
sourceMethodGroup.ResultKind,
newReceiver,
sourceMethodGroup.QualificationKind)
' the delegate creation has the lambda stored internally to not clutter the bound tree with synthesized nodes
' in the first pass. Later on in the DelegateRewriter the node get's rewritten with the lambda if needed.
Return New BoundDelegateCreationExpression(syntaxNode,
receiver,
target,
boundLambda,
relaxationReceiverPlaceholder,
sourceMethodGroup,
targetType,
hasErrors:=False)
End Function
Private Function BuildDelegateRelaxationLambda(
syntaxNode As SyntaxNode,
methodGroupSyntax As SyntaxNode,
receiver As BoundExpression,
targetMethod As MethodSymbol,
typeArgumentsOpt As BoundTypeArguments,
qualificationKind As QualificationKind,
delegateInvoke As MethodSymbol,
delegateRelaxation As ConversionKind,
isZeroArgumentKnownToBeUsed As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean,
diagnostics As BindingDiagnosticBag,
<Out()> ByRef relaxationReceiverPlaceholder As BoundRValuePlaceholder
) As BoundLambda
relaxationReceiverPlaceholder = Nothing
Dim unconstructedTargetMethod As MethodSymbol = targetMethod.ConstructedFrom
If typeArgumentsOpt Is Nothing AndAlso unconstructedTargetMethod.IsGenericMethod Then
typeArgumentsOpt = New BoundTypeArguments(methodGroupSyntax,
targetMethod.TypeArguments)
typeArgumentsOpt.SetWasCompilerGenerated()
End If
Dim actualReceiver As BoundExpression = receiver
' Figure out if we need to capture the receiver in a temp before creating the lambda
' in order to enforce correct semantics.
If actualReceiver IsNot Nothing AndAlso actualReceiver.IsValue() AndAlso Not actualReceiver.HasErrors Then
If actualReceiver.IsInstanceReference() AndAlso targetMethod.ReceiverType.IsReferenceType Then
Debug.Assert(Not actualReceiver.Type.IsTypeParameter())
Debug.Assert(Not actualReceiver.IsLValue) ' See the comment below why this is important.
Else
' Will need to capture the receiver in a temp, rewriter do the job.
relaxationReceiverPlaceholder = New BoundRValuePlaceholder(actualReceiver.Syntax, actualReceiver.Type)
actualReceiver = relaxationReceiverPlaceholder
End If
End If
Dim methodGroup = New BoundMethodGroup(methodGroupSyntax,
typeArgumentsOpt,
ImmutableArray.Create(unconstructedTargetMethod),
LookupResultKind.Good,
actualReceiver,
qualificationKind)
methodGroup.SetWasCompilerGenerated()
Return BuildDelegateRelaxationLambda(syntaxNode,
delegateInvoke,
methodGroup,
delegateRelaxation,
isZeroArgumentKnownToBeUsed,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation,
diagnostics)
End Function
''' <summary>
''' Build a lambda that has a shape of the [delegateInvoke] and calls
''' the only method from the [methodGroup] passing all parameters of the lambda
''' as arguments for the call.
''' Note, that usually the receiver of the [methodGroup] should be captured before entering the
''' relaxation lambda in order to prevent its reevaluation every time the lambda is invoked and
''' prevent its mutation.
'''
''' !!! Therefore, it is not common to call this overload directly. !!!
'''
''' </summary>
''' <param name="syntaxNode">Location to use for various synthetic nodes and symbols.</param>
''' <param name="delegateInvoke">The Invoke method to "implement".</param>
''' <param name="methodGroup">The method group with the only method in it.</param>
''' <param name="delegateRelaxation">Delegate relaxation to store within the new BoundLambda node.</param>
''' <param name="diagnostics"></param>
Private Function BuildDelegateRelaxationLambda(
syntaxNode As SyntaxNode,
delegateInvoke As MethodSymbol,
methodGroup As BoundMethodGroup,
delegateRelaxation As ConversionKind,
isZeroArgumentKnownToBeUsed As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundLambda
Debug.Assert(delegateInvoke.MethodKind = MethodKind.DelegateInvoke)
Debug.Assert(methodGroup.Methods.Length = 1)
Debug.Assert(methodGroup.PendingExtensionMethodsOpt Is Nothing)
Debug.Assert((delegateRelaxation And (Not ConversionKind.DelegateRelaxationLevelMask)) = 0)
' build lambda symbol parameters matching the invocation method exactly. To do this,
' we'll create a BoundLambdaParameterSymbol for each parameter of the invoke method.
Dim delegateInvokeReturnType = delegateInvoke.ReturnType
Dim invokeParameters = delegateInvoke.Parameters
Dim invokeParameterCount = invokeParameters.Length
Dim lambdaSymbolParameters(invokeParameterCount - 1) As BoundLambdaParameterSymbol
Dim addressOfLocation As Location = syntaxNode.GetLocation()
For parameterIndex = 0 To invokeParameterCount - 1
Dim parameter = invokeParameters(parameterIndex)
lambdaSymbolParameters(parameterIndex) = New BoundLambdaParameterSymbol(GeneratedNames.MakeDelegateRelaxationParameterName(parameterIndex),
parameter.Ordinal,
parameter.Type,
parameter.IsByRef,
syntaxNode,
addressOfLocation)
Next
' even if the return value is dropped, we're using the delegate's return type for
' this lambda symbol.
Dim lambdaSymbol = New SynthesizedLambdaSymbol(SynthesizedLambdaKind.DelegateRelaxationStub,
syntaxNode,
lambdaSymbolParameters.AsImmutable(),
delegateInvokeReturnType,
Me)
' the body of the lambda only contains a call to the target (or a return of the return value of
' the call in case of a function)
' for each parameter of the lambda symbol/invoke method we will create a bound parameter, except
' we are implementing a zero argument relaxation.
' These parameters will be used in the method invocation as passed parameters.
Dim method As MethodSymbol = methodGroup.Methods(0)
Dim droppedArguments = isZeroArgumentKnownToBeUsed OrElse (invokeParameterCount > 0 AndAlso method.ParameterCount = 0)
Dim targetParameterCount = If(droppedArguments, 0, invokeParameterCount)
Dim lambdaBoundParameters(targetParameterCount - 1) As BoundExpression
If Not droppedArguments Then
For parameterIndex = 0 To lambdaSymbolParameters.Length - 1
Dim lambdaSymbolParameter = lambdaSymbolParameters(parameterIndex)
Dim boundParameter = New BoundParameter(syntaxNode,
lambdaSymbolParameter,
lambdaSymbolParameter.Type)
boundParameter.SetWasCompilerGenerated()
lambdaBoundParameters(parameterIndex) = boundParameter
Next
End If
'The invocation of the target method must be bound in the context of the lambda
'The reason is that binding the invoke may introduce local symbols and they need
'to be properly parented to the lambda and not to the outer method.
Dim lambdaBinder = New LambdaBodyBinder(lambdaSymbol, Me)
' Dev10 ignores the type characters used in the operand of an AddressOf operator.
' NOTE: we suppress suppressAbstractCallDiagnostics because it
' should have been reported already
Dim boundInvocationExpression As BoundExpression = lambdaBinder.BindInvocationExpression(syntaxNode,
syntaxNode,
TypeCharacter.None,
methodGroup,
lambdaBoundParameters.AsImmutable(),
Nothing,
diagnostics,
suppressAbstractCallDiagnostics:=True,
callerInfoOpt:=Nothing)
boundInvocationExpression.SetWasCompilerGenerated()
' In case of a function target that got assigned to a sub delegate, the return value will be dropped
Dim statementList As ImmutableArray(Of BoundStatement) = Nothing
If lambdaSymbol.IsSub Then
Dim statements(1) As BoundStatement
Dim boundStatement As BoundStatement = New BoundExpressionStatement(syntaxNode, boundInvocationExpression)
boundStatement.SetWasCompilerGenerated()
statements(0) = boundStatement
boundStatement = New BoundReturnStatement(syntaxNode, Nothing, Nothing, Nothing)
boundStatement.SetWasCompilerGenerated()
statements(1) = boundStatement
statementList = statements.AsImmutableOrNull
If warnIfResultOfAsyncMethodIsDroppedDueToRelaxation AndAlso
Not method.IsSub Then
If Not method.IsAsync Then
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = False
If method.MethodKind = MethodKind.DelegateInvoke AndAlso
methodGroup.ReceiverOpt IsNot Nothing AndAlso
methodGroup.ReceiverOpt.Kind = BoundKind.Conversion Then
Dim receiver = DirectCast(methodGroup.ReceiverOpt, BoundConversion)
If Not receiver.ExplicitCastInCode AndAlso
receiver.Operand.Kind = BoundKind.Lambda AndAlso
DirectCast(receiver.Operand, BoundLambda).LambdaSymbol.IsAsync AndAlso
receiver.Type.IsDelegateType() AndAlso
receiver.Type.IsAnonymousType Then
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = True
End If
End If
Else
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = method.ContainingAssembly Is Compilation.Assembly
End If
If warnIfResultOfAsyncMethodIsDroppedDueToRelaxation Then
ReportDiagnostic(diagnostics, syntaxNode, ERRID.WRN_UnobservedAwaitableDelegate)
End If
End If
Else
' process conversions between the return types of the target and invoke function if needed.
boundInvocationExpression = lambdaBinder.ApplyImplicitConversion(syntaxNode,
delegateInvokeReturnType,
boundInvocationExpression,
diagnostics)
Dim returnstmt As BoundStatement = New BoundReturnStatement(syntaxNode,
boundInvocationExpression,
Nothing,
Nothing)
returnstmt.SetWasCompilerGenerated()
statementList = ImmutableArray.Create(returnstmt)
End If
Dim lambdaBody = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
statementList)
lambdaBody.SetWasCompilerGenerated()
Dim boundLambda = New BoundLambda(syntaxNode,
lambdaSymbol,
lambdaBody,
ImmutableBindingDiagnostic(Of AssemblySymbol).Empty,
Nothing,
delegateRelaxation,
MethodConversionKind.Identity)
boundLambda.SetWasCompilerGenerated()
Return boundLambda
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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class Binder
''' <summary>
''' Structure is used to store all information which is needed to construct and classify a Delegate creation
''' expression later on.
''' </summary>
Friend Structure DelegateResolutionResult
' we store the DelegateConversions although it could be derived from MethodConversions to improve performance
Public ReadOnly DelegateConversions As ConversionKind
Public ReadOnly Target As MethodSymbol
Public ReadOnly MethodConversions As MethodConversionKind
Public ReadOnly Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
Public Sub New(
DelegateConversions As ConversionKind,
Target As MethodSymbol,
MethodConversions As MethodConversionKind,
Diagnostics As ImmutableBindingDiagnostic(Of AssemblySymbol)
)
Me.DelegateConversions = DelegateConversions
Me.Target = Target
Me.Diagnostics = Diagnostics
Me.MethodConversions = MethodConversions
End Sub
End Structure
''' <summary>
''' Binds the AddressOf expression.
''' </summary>
''' <param name="node">The AddressOf expression node.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function BindAddressOfExpression(node As VisualBasicSyntaxNode, diagnostics As BindingDiagnosticBag) As BoundExpression
Dim addressOfSyntax = DirectCast(node, UnaryExpressionSyntax)
Dim boundOperand = BindExpression(addressOfSyntax.Operand, isInvocationOrAddressOf:=True, diagnostics:=diagnostics, isOperandOfConditionalBranch:=False, eventContext:=False)
If boundOperand.Kind = BoundKind.LateMemberAccess Then
Return New BoundLateAddressOfOperator(node, Me, DirectCast(boundOperand, BoundLateMemberAccess), boundOperand.Type)
End If
' only accept MethodGroups as operands. More detailed checks (e.g. for Constructors follow later)
If boundOperand.Kind <> BoundKind.MethodGroup Then
If Not boundOperand.HasErrors Then
ReportDiagnostic(diagnostics, addressOfSyntax.Operand, ERRID.ERR_AddressOfOperandNotMethod)
End If
Return BadExpression(addressOfSyntax, boundOperand, LookupResultKind.NotAValue, ErrorTypeSymbol.UnknownResultType)
End If
Dim hasErrors As Boolean = False
Dim group = DirectCast(boundOperand, BoundMethodGroup)
If IsGroupOfConstructors(group) Then
ReportDiagnostic(diagnostics, addressOfSyntax.Operand, ERRID.ERR_InvalidConstructorCall)
hasErrors = True
End If
Return New BoundAddressOfOperator(node, Me, diagnostics.AccumulatesDependencies, group, hasErrors)
End Function
''' <summary>
''' Binds the delegate creation expression.
''' This comes in form of e.g.
''' Dim del as new DelegateType(AddressOf methodName)
''' </summary>
''' <param name="delegateType">Type of the delegate.</param>
''' <param name="argumentListOpt">The argument list.</param>
''' <param name="node">Syntax node to attach diagnostics to in case the argument list is nothing.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Private Function BindDelegateCreationExpression(
delegateType As TypeSymbol,
argumentListOpt As ArgumentListSyntax,
node As VisualBasicSyntaxNode,
diagnostics As BindingDiagnosticBag
) As BoundExpression
Dim boundFirstArgument As BoundExpression = Nothing
Dim argumentCount = 0
If argumentListOpt IsNot Nothing Then
argumentCount = argumentListOpt.Arguments.Count
End If
Dim hadErrorsInFirstArgument = False
' a delegate creation expression should have exactly one argument.
If argumentCount > 0 Then
Dim argumentSyntax = argumentListOpt.Arguments(0)
Dim expressionSyntax As ExpressionSyntax = Nothing
' a delegate creation expression does not care if what the name of a named argument
' was. Just take whatever was passed.
If argumentSyntax.Kind = SyntaxKind.SimpleArgument Then
expressionSyntax = argumentSyntax.GetExpression()
End If
' omitted argument will leave expressionSyntax as nothing which means no binding, which is fine.
If expressionSyntax IsNot Nothing Then
If expressionSyntax.Kind = SyntaxKind.AddressOfExpression Then
boundFirstArgument = BindAddressOfExpression(expressionSyntax, diagnostics)
ElseIf expressionSyntax.IsLambdaExpressionSyntax() Then
' this covers the legal cases for SyntaxKind.MultiLineFunctionLambdaExpression,
' SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression and
' SyntaxKind.SingleLineSubLambdaExpression, as well as all the other invalid ones.
boundFirstArgument = BindExpression(expressionSyntax, diagnostics)
End If
If boundFirstArgument IsNot Nothing Then
hadErrorsInFirstArgument = boundFirstArgument.HasErrors
Debug.Assert(boundFirstArgument.Kind = BoundKind.BadExpression OrElse
boundFirstArgument.Kind = BoundKind.LateAddressOfOperator OrElse
boundFirstArgument.Kind = BoundKind.AddressOfOperator OrElse
boundFirstArgument.Kind = BoundKind.UnboundLambda)
If argumentCount = 1 Then
boundFirstArgument = ApplyImplicitConversion(node,
delegateType,
boundFirstArgument,
diagnostics:=diagnostics)
If boundFirstArgument.Syntax IsNot node Then
' We must have a bound node that corresponds to that syntax node for GetSemanticInfo.
' Insert an identity conversion if necessary.
Debug.Assert(boundFirstArgument.Kind <> BoundKind.Conversion, "Associated wrong node with conversion?")
boundFirstArgument = New BoundConversion(node, boundFirstArgument, ConversionKind.Identity, CheckOverflow, True, delegateType)
ElseIf boundFirstArgument.Kind = BoundKind.Conversion Then
Debug.Assert(Not boundFirstArgument.WasCompilerGenerated)
Dim boundConversion = DirectCast(boundFirstArgument, BoundConversion)
boundFirstArgument = boundConversion.Update(boundConversion.Operand,
boundConversion.ConversionKind,
boundConversion.Checked,
True, ' ExplicitCastInCode
boundConversion.ConstantValueOpt,
boundConversion.ExtendedInfoOpt,
boundConversion.Type)
End If
Return boundFirstArgument
End If
End If
Else
boundFirstArgument = New BoundBadExpression(argumentSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundExpression).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
End If
Dim boundArguments(argumentCount - 1) As BoundExpression
If boundFirstArgument IsNot Nothing Then
boundFirstArgument = MakeRValueAndIgnoreDiagnostics(boundFirstArgument)
boundArguments(0) = boundFirstArgument
End If
' bind all arguments and ignore all diagnostics. These bound nodes will be passed to
' a BoundBadNode
For argumentIndex = If(boundFirstArgument Is Nothing, 0, 1) To argumentCount - 1
Dim expressionSyntax As ExpressionSyntax = Nothing
Dim argumentSyntax = argumentListOpt.Arguments(argumentIndex)
If argumentSyntax.Kind = SyntaxKind.SimpleArgument Then
expressionSyntax = argumentSyntax.GetExpression()
End If
If expressionSyntax IsNot Nothing Then
boundArguments(argumentIndex) = BindValue(expressionSyntax, BindingDiagnosticBag.Discarded)
Else
boundArguments(argumentIndex) = New BoundBadExpression(argumentSyntax,
LookupResultKind.Empty,
ImmutableArray(Of Symbol).Empty,
ImmutableArray(Of BoundExpression).Empty,
ErrorTypeSymbol.UnknownResultType,
hasErrors:=True)
End If
Next
' the default error message in delegate creations if the passed arguments are empty or not a addressOf
' should be ERRID.ERR_NoDirectDelegateConstruction1
' if binding an AddressOf expression caused diagnostics these should be shown instead
If Not hadErrorsInFirstArgument OrElse
argumentCount <> 1 Then
ReportDiagnostic(diagnostics,
If(argumentListOpt, node),
ERRID.ERR_NoDirectDelegateConstruction1,
delegateType)
End If
Return BadExpression(node,
ImmutableArray.Create(boundArguments),
delegateType)
End Function
''' <summary>
''' Resolves the target method for the delegate and classifies the conversion
''' </summary>
''' <param name="addressOfExpression">The bound AddressOf expression itself.</param>
''' <param name="targetType">The delegate type to assign the result of the AddressOf operator to.</param>
''' <returns></returns>
Friend Shared Function InterpretDelegateBinding(
addressOfExpression As BoundAddressOfOperator,
targetType As TypeSymbol,
isForHandles As Boolean
) As DelegateResolutionResult
Debug.Assert(targetType IsNot Nothing)
Dim diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics:=True, addressOfExpression.WithDependencies)
Dim result As OverloadResolution.OverloadResolutionResult = Nothing
Dim fromMethod As MethodSymbol = Nothing
Dim syntaxTree = addressOfExpression.Syntax
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' must be a delegate, and also a concrete delegate
If targetType.SpecialType = SpecialType.System_Delegate OrElse
targetType.SpecialType = SpecialType.System_MulticastDelegate Then
' 'AddressOf' expression cannot be converted to '{0}' because type '{0}' is declared 'MustInherit' and cannot be created.
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_AddressOfNotCreatableDelegate1, targetType)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
ElseIf targetType.TypeKind <> TypeKind.Delegate Then
' 'AddressOf' expression cannot be converted to '{0}' because '{0}' is not a delegate type.
If targetType.TypeKind <> TypeKind.Error Then
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_AddressOfNotDelegate1, targetType)
End If
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
Dim delegateInvoke = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod
If delegateInvoke IsNot Nothing Then
If ReportDelegateInvokeUseSite(diagnostics, syntaxTree, targetType, delegateInvoke) Then
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
' todo(rbeckers) if (IsLateReference(addressOfExpression))
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = ResolveMethodForDelegateInvokeFullAndRelaxed(
addressOfExpression,
delegateInvoke,
False,
diagnostics)
fromMethod = matchingMethod.Key
methodConversions = matchingMethod.Value
End If
Else
ReportDiagnostic(diagnostics, syntaxTree, ERRID.ERR_UnsupportedMethod1, targetType)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
End If
' show diagnostics if the an instance method is used in a shared context.
If fromMethod IsNot Nothing Then
' Generate an error, but continue processing
If addressOfExpression.Binder.CheckSharedSymbolAccess(addressOfExpression.Syntax,
fromMethod.IsShared,
addressOfExpression.MethodGroup.ReceiverOpt,
addressOfExpression.MethodGroup.QualificationKind,
diagnostics) Then
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
End If
' TODO: Check boxing of restricted types, report ERRID_RestrictedConversion1 and continue.
Dim receiver As BoundExpression = addressOfExpression.MethodGroup.ReceiverOpt
If fromMethod IsNot Nothing Then
If fromMethod.IsMustOverride AndAlso receiver IsNot Nothing AndAlso
(receiver.IsMyBaseReference OrElse receiver.IsMyClassReference) Then
' Generate an error, but continue processing
ReportDiagnostic(diagnostics, addressOfExpression.MethodGroup.Syntax,
If(receiver.IsMyBaseReference,
ERRID.ERR_MyBaseAbstractCall1,
ERRID.ERR_MyClassAbstractCall1),
fromMethod)
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
If Not fromMethod.IsShared AndAlso
fromMethod.ContainingType.IsNullableType AndAlso
Not fromMethod.IsOverrides Then
Dim addressOfSyntax As SyntaxNode = addressOfExpression.Syntax
Dim addressOfExpressionSyntax = DirectCast(addressOfExpression.Syntax, UnaryExpressionSyntax)
If (addressOfExpressionSyntax IsNot Nothing) Then
addressOfSyntax = addressOfExpressionSyntax.Operand
End If
' Generate an error, but continue processing
ReportDiagnostic(diagnostics,
addressOfSyntax,
ERRID.ERR_AddressOfNullableMethod,
fromMethod.ContainingType,
SyntaxFacts.GetText(SyntaxKind.AddressOfKeyword))
' There's no real need to set MethodConversionKind.Error because there are no overloads of the same method where one
' may be legal to call because it's shared and the other's not.
' However to be future proof, we set it regardless.
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
End If
addressOfExpression.Binder.ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagnostics, fromMethod, addressOfExpression.MethodGroup.Syntax)
End If
Dim delegateConversions As ConversionKind = Conversions.DetermineDelegateRelaxationLevel(methodConversions)
If (delegateConversions And ConversionKind.DelegateRelaxationLevelInvalid) <> ConversionKind.DelegateRelaxationLevelInvalid Then
If Conversions.IsNarrowingMethodConversion(methodConversions, isForAddressOf:=Not isForHandles) Then
delegateConversions = delegateConversions Or ConversionKind.Narrowing
Else
delegateConversions = delegateConversions Or ConversionKind.Widening
End If
End If
Return New DelegateResolutionResult(delegateConversions, fromMethod, methodConversions, diagnostics.ToReadOnlyAndFree())
End Function
Friend Shared Function ReportDelegateInvokeUseSite(
diagBag As BindingDiagnosticBag,
syntax As SyntaxNode,
delegateType As TypeSymbol,
invoke As MethodSymbol
) As Boolean
Debug.Assert(delegateType IsNot Nothing)
Debug.Assert(invoke IsNot Nothing)
Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = invoke.GetUseSiteInfo()
If useSiteInfo.DiagnosticInfo?.Code = ERRID.ERR_UnsupportedMethod1 Then
useSiteInfo = New UseSiteInfo(Of AssemblySymbol)(ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedMethod1, delegateType))
End If
Return diagBag.Add(useSiteInfo, syntax)
End Function
''' <summary>
''' Resolves the method for delegate invoke with all or relaxed arguments / return types. It also determines
''' the method conversion kind.
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="toMethod">The delegate invoke method.</param>
''' <param name="ignoreMethodReturnType">Ignore method's return type for the purpose of calculating 'methodConversions'.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <returns>The resolved method if any.</returns>
Friend Shared Function ResolveMethodForDelegateInvokeFullAndRelaxed(
addressOfExpression As BoundAddressOfOperator,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
diagnostics As BindingDiagnosticBag
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim argumentDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics)
Dim couldTryZeroArgumentRelaxation As Boolean = True
Dim matchingMethod As KeyValuePair(Of MethodSymbol, MethodConversionKind) = ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression,
toMethod,
ignoreMethodReturnType,
argumentDiagnostics,
useZeroArgumentRelaxation:=False,
couldTryZeroArgumentRelaxation:=couldTryZeroArgumentRelaxation)
' If there have been parameters and if there was no ambiguous match before, try zero argument relaxation.
If matchingMethod.Key Is Nothing AndAlso couldTryZeroArgumentRelaxation Then
Dim zeroArgumentDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics)
Dim argumentMatchingMethod = matchingMethod
matchingMethod = ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression,
toMethod,
ignoreMethodReturnType,
zeroArgumentDiagnostics,
useZeroArgumentRelaxation:=True,
couldTryZeroArgumentRelaxation:=couldTryZeroArgumentRelaxation)
' if zero relaxation did not find something, we'll report the diagnostics of the
' non zero relaxation try, else the diagnostics of the zero argument relaxation.
If matchingMethod.Key Is Nothing Then
diagnostics.AddRange(argumentDiagnostics)
matchingMethod = argumentMatchingMethod
Else
diagnostics.AddRange(zeroArgumentDiagnostics)
End If
zeroArgumentDiagnostics.Free()
Else
diagnostics.AddRange(argumentDiagnostics)
End If
argumentDiagnostics.Free()
' check that there's not method returned if there is no conversion.
Debug.Assert(matchingMethod.Key Is Nothing OrElse (matchingMethod.Value And MethodConversionKind.AllErrorReasons) = 0)
Return matchingMethod
End Function
''' <summary>
''' Resolves the method for delegate invoke with all or relaxed arguments / return types. It also determines
''' the method conversion kind.
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="toMethod">The delegate invoke method.</param>
''' <param name="ignoreMethodReturnType">Ignore method's return type for the purpose of calculating 'methodConversions'.</param>
''' <param name="diagnostics">The diagnostics.</param>
''' <param name="useZeroArgumentRelaxation">if set to <c>true</c> use zero argument relaxation.</param>
''' <returns>The resolved method if any.</returns>
Private Shared Function ResolveMethodForDelegateInvokeFullOrRelaxed(
addressOfExpression As BoundAddressOfOperator,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
diagnostics As BindingDiagnosticBag,
useZeroArgumentRelaxation As Boolean,
ByRef couldTryZeroArgumentRelaxation As Boolean
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim boundArguments = ImmutableArray(Of BoundExpression).Empty
If Not useZeroArgumentRelaxation Then
' build array of bound expressions for overload resolution (BoundLocal is easy to create)
Dim toMethodParameters = toMethod.Parameters
Dim parameterCount = toMethodParameters.Length
If parameterCount > 0 Then
Dim boundParameterArguments(parameterCount - 1) As BoundExpression
Dim argumentIndex As Integer = 0
Dim syntaxTree As SyntaxTree
Dim addressOfSyntax = addressOfExpression.Syntax
syntaxTree = addressOfExpression.Binder.SyntaxTree
For Each parameter In toMethodParameters
Dim parameterType = parameter.Type
Dim tempParamSymbol = New SynthesizedLocal(toMethod, parameterType, SynthesizedLocalKind.LoweringTemp)
' TODO: Switch to using BoundValuePlaceholder, but we need it to be able to appear
' as an LValue in case of a ByRef parameter.
Dim tempBoundParameter As BoundExpression = New BoundLocal(addressOfSyntax,
tempParamSymbol,
parameterType)
' don't treat ByVal parameters as lvalues in the following OverloadResolution
If Not parameter.IsByRef Then
tempBoundParameter = tempBoundParameter.MakeRValue()
End If
boundParameterArguments(argumentIndex) = tempBoundParameter
argumentIndex += 1
Next
boundArguments = boundParameterArguments.AsImmutableOrNull()
Else
couldTryZeroArgumentRelaxation = False
End If
End If
Dim delegateReturnType As TypeSymbol
Dim delegateReturnTypeReferenceBoundNode As BoundNode
If ignoreMethodReturnType Then
' Keep them Nothing such that the delegate's return type won't be taken part of in overload resolution
' when we are inferring the return type.
delegateReturnType = Nothing
delegateReturnTypeReferenceBoundNode = Nothing
Else
delegateReturnType = toMethod.ReturnType
delegateReturnTypeReferenceBoundNode = addressOfExpression
End If
' Let's go through overload resolution, pretending that Option Strict is Off and see if it succeeds.
Dim resolutionBinder As Binder
If addressOfExpression.Binder.OptionStrict <> VisualBasic.OptionStrict.Off Then
resolutionBinder = New OptionStrictOffBinder(addressOfExpression.Binder)
Else
resolutionBinder = addressOfExpression.Binder
End If
Debug.Assert(resolutionBinder.OptionStrict = VisualBasic.OptionStrict.Off)
Dim useSiteInfo = addressOfExpression.Binder.GetNewCompoundUseSiteInfo(diagnostics)
Dim resolutionResult = OverloadResolution.MethodInvocationOverloadResolution(
addressOfExpression.MethodGroup,
boundArguments,
Nothing,
resolutionBinder,
includeEliminatedCandidates:=False,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
lateBindingIsAllowed:=False,
callerInfoOpt:=Nothing,
useSiteInfo:=useSiteInfo)
If diagnostics.Add(addressOfExpression.MethodGroup, useSiteInfo) Then
couldTryZeroArgumentRelaxation = False
If addressOfExpression.MethodGroup.ResultKind <> LookupResultKind.Inaccessible Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
Dim addressOfMethodGroup = addressOfExpression.MethodGroup
If resolutionResult.BestResult.HasValue Then
Return ValidateMethodForDelegateInvoke(
addressOfExpression,
resolutionResult.BestResult.Value,
toMethod,
ignoreMethodReturnType,
useZeroArgumentRelaxation,
diagnostics)
End If
' Overload Resolution didn't find a match
If resolutionResult.Candidates.Length = 0 Then
resolutionResult = OverloadResolution.MethodInvocationOverloadResolution(
addressOfMethodGroup,
boundArguments,
Nothing,
resolutionBinder,
includeEliminatedCandidates:=True,
delegateReturnType:=delegateReturnType,
delegateReturnTypeReferenceBoundNode:=delegateReturnTypeReferenceBoundNode,
lateBindingIsAllowed:=False,
callerInfoOpt:=Nothing,
useSiteInfo:=useSiteInfo)
End If
Dim bestCandidates = ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult).GetInstance()
Dim bestSymbols = ImmutableArray(Of Symbol).Empty
Dim commonReturnType As TypeSymbol = GetSetOfTheBestCandidates(resolutionResult, bestCandidates, bestSymbols)
Debug.Assert(bestCandidates.Count > 0 AndAlso bestCandidates.Count > 0)
Dim bestCandidatesState As OverloadResolution.CandidateAnalysisResultState = bestCandidates(0).State
If bestCandidatesState = VisualBasic.OverloadResolution.CandidateAnalysisResultState.Applicable Then
' if there is an applicable candidate in the list, we know it must be an ambiguous match
' (or there are more applicable candidates in this list), otherwise this would have been
' the best match.
Debug.Assert(bestCandidates.Count > 1 AndAlso bestSymbols.Length > 1)
' there are multiple candidates, so it ambiguous and zero argument relaxation will not be tried,
' unless the candidates require narrowing.
If Not bestCandidates(0).RequiresNarrowingConversion Then
couldTryZeroArgumentRelaxation = False
End If
End If
If bestSymbols.Length = 1 AndAlso
(bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch) Then
' Dev10 has squiggles under the operand of the AddressOf. The syntax of addressOfExpression
' is the complete AddressOf expression, so we need to get the operand first.
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics, addressOfOperandSyntax,
addressOfExpression.Binder.GetInaccessibleErrorInfo(
bestSymbols(0)))
Else
Debug.Assert(addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good)
End If
ReportDelegateBindingIncompatible(
addressOfOperandSyntax,
toMethod.ContainingType,
DirectCast(bestSymbols(0), MethodSymbol),
diagnostics)
Else
If bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.HasUseSiteError OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata OrElse
bestCandidatesState = OverloadResolution.CandidateAnalysisResultState.Ambiguous Then
couldTryZeroArgumentRelaxation = False
End If
Dim unused = resolutionBinder.ReportOverloadResolutionFailureAndProduceBoundNode(
addressOfExpression.MethodGroup.Syntax,
addressOfMethodGroup,
bestCandidates,
bestSymbols,
commonReturnType,
boundArguments,
Nothing,
diagnostics,
delegateSymbol:=toMethod.ContainingType,
callerInfoOpt:=Nothing)
End If
bestCandidates.Free()
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(Nothing, MethodConversionKind.Error_OverloadResolution)
End Function
Private Shared Function ValidateMethodForDelegateInvoke(
addressOfExpression As BoundAddressOfOperator,
analysisResult As OverloadResolution.CandidateAnalysisResult,
toMethod As MethodSymbol,
ignoreMethodReturnType As Boolean,
useZeroArgumentRelaxation As Boolean,
diagnostics As BindingDiagnosticBag
) As KeyValuePair(Of MethodSymbol, MethodConversionKind)
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' Dev10 has squiggles under the operand of the AddressOf. The syntax of addressOfExpression
' is the complete AddressOf expression, so we need to get the operand first.
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
' determine conversions based on return type
Dim useSiteInfo = addressOfExpression.Binder.GetNewCompoundUseSiteInfo(diagnostics)
Dim targetMethodSymbol = DirectCast(analysisResult.Candidate.UnderlyingSymbol, MethodSymbol)
If Not ignoreMethodReturnType Then
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnReturn(targetMethodSymbol.ReturnType, targetMethodSymbol.ReturnsByRef,
toMethod.ReturnType, toMethod.ReturnsByRef, useSiteInfo)
If diagnostics.Add(addressOfOperandSyntax, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
If useZeroArgumentRelaxation Then
Debug.Assert(toMethod.ParameterCount > 0)
' special flag for ignoring all arguments (zero argument relaxation)
If targetMethodSymbol.ParameterCount = 0 Then
methodConversions = methodConversions Or MethodConversionKind.AllArgumentsIgnored
Else
' We can get here if all method's parameters are Optional/ParamArray, however,
' according to the language spec, zero arguments relaxation is allowed only
' if target method has no parameters. Here is the quote:
' "method referenced by the method pointer, but it is not applicable due to
' the fact that it has no parameters and the delegate type does, then the method
' is considered applicable and the parameters are simply ignored."
'
' There is a bug in Dev10, sometimes it erroneously allows zero-argument relaxation against
' a method with optional parameters, if parameters of the delegate invoke can be passed to
' the method (i.e. without dropping them). See unit-test Bug12211 for an example.
methodConversions = methodConversions Or MethodConversionKind.Error_IllegalToIgnoreAllArguments
End If
Else
' determine conversions based on arguments
methodConversions = methodConversions Or GetDelegateMethodConversionBasedOnArguments(analysisResult, toMethod, useSiteInfo)
If diagnostics.Add(addressOfOperandSyntax, useSiteInfo) Then
' Suppress additional diagnostics
diagnostics = BindingDiagnosticBag.Discarded
End If
End If
' Stubs for ByRef returning methods are not supported.
' We could easily support a stub for the case when return value is dropped,
' but enabling other kinds of stubs later can lead to breaking changes
' because those relaxations could be "better".
If Not ignoreMethodReturnType AndAlso targetMethodSymbol.ReturnsByRef AndAlso
Conversions.IsDelegateRelaxationSupportedFor(methodConversions) AndAlso
Conversions.IsStubRequiredForMethodConversion(methodConversions) Then
methodConversions = methodConversions Or MethodConversionKind.Error_StubNotSupported
End If
If Conversions.IsDelegateRelaxationSupportedFor(methodConversions) Then
Dim typeArgumentInferenceDiagnosticsOpt = analysisResult.TypeArgumentInferenceDiagnosticsOpt
If typeArgumentInferenceDiagnosticsOpt IsNot Nothing Then
diagnostics.AddRange(typeArgumentInferenceDiagnosticsOpt)
End If
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good Then
addressOfExpression.Binder.CheckMemberTypeAccessibility(diagnostics, addressOfOperandSyntax, targetMethodSymbol)
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(targetMethodSymbol, methodConversions)
End If
methodConversions = methodConversions Or MethodConversionKind.Error_Unspecified
Else
ReportDelegateBindingIncompatible(
addressOfOperandSyntax,
toMethod.ContainingType,
targetMethodSymbol,
diagnostics)
End If
Debug.Assert((methodConversions And MethodConversionKind.AllErrorReasons) <> 0)
If addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Inaccessible Then
ReportDiagnostic(diagnostics, addressOfOperandSyntax,
addressOfExpression.Binder.GetInaccessibleErrorInfo(
analysisResult.Candidate.UnderlyingSymbol))
Else
Debug.Assert(addressOfExpression.MethodGroup.ResultKind = LookupResultKind.Good)
End If
Return New KeyValuePair(Of MethodSymbol, MethodConversionKind)(Nothing, methodConversions)
End Function
Private Shared Sub ReportDelegateBindingMismatchStrictOff(
syntax As SyntaxNode,
delegateType As NamedTypeSymbol,
targetMethodSymbol As MethodSymbol,
diagnostics As BindingDiagnosticBag
)
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
If targetMethodSymbol.ReducedFrom Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingMismatchStrictOff2,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType))
Else
' This is an extension method.
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingMismatchStrictOff3,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType),
targetMethodSymbol.ContainingType)
End If
End Sub
Private Shared Sub ReportDelegateBindingIncompatible(
syntax As SyntaxNode,
delegateType As NamedTypeSymbol,
targetMethodSymbol As MethodSymbol,
diagnostics As BindingDiagnosticBag
)
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
If targetMethodSymbol.ReducedFrom Is Nothing Then
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingIncompatible2,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType))
Else
' This is an extension method.
ReportDiagnostic(diagnostics,
syntax,
ERRID.ERR_DelegateBindingIncompatible3,
targetMethodSymbol,
CustomSymbolDisplayFormatter.DelegateSignature(delegateType),
targetMethodSymbol.ContainingType)
End If
End Sub
''' <summary>
''' Determines the method conversion for delegates based on the arguments.
''' </summary>
''' <param name="bestResult">The resolution result.</param>
''' <param name="delegateInvoke">The delegate invoke method.</param>
Private Shared Function GetDelegateMethodConversionBasedOnArguments(
bestResult As OverloadResolution.CandidateAnalysisResult,
delegateInvoke As MethodSymbol,
<[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)
) As MethodConversionKind
Dim methodConversions As MethodConversionKind = MethodConversionKind.Identity
' in contrast to the native compiler we know that there is a legal conversion and we do not
' need to classify invalid conversions.
' however there is still the ParamArray expansion that needs special treatment.
' if there is one conversion needed, the array ConversionsOpt contains all conversions for all used parameters
' (including e.g. identity conversion). If a ParamArray was expanded, there will be a conversion for each
' expanded parameter.
Dim bestCandidate As OverloadResolution.Candidate = bestResult.Candidate
Dim candidateParameterCount = bestCandidate.ParameterCount
Dim candidateLastParameterIndex = candidateParameterCount - 1
Dim delegateParameterCount = delegateInvoke.ParameterCount
Dim lastCommonIndex = Math.Min(candidateParameterCount, delegateParameterCount) - 1
' IsExpandedParamArrayForm is true if there was no, one or more parameters given for the ParamArray
' Note: if an array was passed, IsExpandedParamArrayForm is false.
If bestResult.IsExpandedParamArrayForm Then
' Dev10 always sets the ExcessOptionalArgumentsOnTarget whenever the last parameter of the target was a
' ParamArray. This forces a stub for the ParamArray conversion, that is needed for the ParamArray in any case.
methodConversions = methodConversions Or MethodConversionKind.ExcessOptionalArgumentsOnTarget
ElseIf candidateParameterCount > delegateParameterCount Then
' An omission of optional parameters for expanded ParamArray form doesn't add anything new for
' the method conversion. Non-expanded ParamArray form, would be dismissed by overload resolution
' if there were omitted optional parameters because it is illegal to omit the ParamArray argument
' in non-expanded form.
' there are optional parameters that have not been exercised by the delegate.
' e.g. Delegate Sub(b As Byte) -> Sub Target(b As Byte, Optional c as Byte)
methodConversions = methodConversions Or MethodConversionKind.ExcessOptionalArgumentsOnTarget
#If DEBUG Then
' check that all unused parameters on the target are optional
For parameterIndex = delegateParameterCount To candidateParameterCount - 1
Debug.Assert(bestCandidate.Parameters(parameterIndex).IsOptional)
Next
#End If
ElseIf lastCommonIndex >= 0 AndAlso
bestCandidate.Parameters(lastCommonIndex).IsParamArray AndAlso
delegateInvoke.Parameters(lastCommonIndex).IsByRef AndAlso
bestCandidate.Parameters(lastCommonIndex).IsByRef AndAlso
Not bestResult.ConversionsOpt.IsDefaultOrEmpty AndAlso
Not Conversions.IsIdentityConversion(bestResult.ConversionsOpt(lastCommonIndex).Key) Then
' Dev10 has the following behavior that needs to be re-implemented:
' Using
' Sub Target(ByRef Base())
' with a
' Delegate Sub Del(ByRef ParamArray Base())
' does not create a stub and the values are transported ByRef
' however using a
' Sub Target(ByRef ParamArray Base())
' with a
' Delegate Del(ByRef Derived()) (with or without ParamArray, works with Option Strict Off only)
' creates a stub and transports the values ByVal.
' Note: if the ParamArray is not expanded, the parameter count must match
Debug.Assert(candidateParameterCount = delegateParameterCount)
Debug.Assert(Conversions.IsWideningConversion(bestResult.ConversionsOpt(lastCommonIndex).Key))
Dim conv = Conversions.ClassifyConversion(bestCandidate.Parameters(lastCommonIndex).Type,
delegateInvoke.Parameters(lastCommonIndex).Type,
useSiteInfo)
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conv.Key,
delegateInvoke.Parameters(lastCommonIndex).Type)
End If
' the overload resolution does not consider ByRef/ByVal mismatches, so we need to check the
' parameters here.
' first iterate over the common parameters
For parameterIndex = 0 To lastCommonIndex
If delegateInvoke.Parameters(parameterIndex).IsByRef <> bestCandidate.Parameters(parameterIndex).IsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
Exit For
End If
Next
' after the loop above the remaining parameters on the target can only be optional and/or a ParamArray
If bestResult.IsExpandedParamArrayForm AndAlso
(methodConversions And MethodConversionKind.Error_ByRefByValMismatch) <> MethodConversionKind.Error_ByRefByValMismatch Then
' if delegateParameterCount is smaller than targetParameterCount the for loop does not
' execute
Dim lastTargetParameterIsByRef = bestCandidate.Parameters(candidateLastParameterIndex).IsByRef
Debug.Assert(bestCandidate.Parameters(candidateLastParameterIndex).IsParamArray)
For parameterIndex = lastCommonIndex + 1 To delegateParameterCount - 1
' test against the last parameter of the target method
If delegateInvoke.Parameters(parameterIndex).IsByRef <> lastTargetParameterIsByRef Then
methodConversions = methodConversions Or MethodConversionKind.Error_ByRefByValMismatch
Exit For
End If
Next
End If
' there have been conversions, check them all
If Not bestResult.ConversionsOpt.IsDefaultOrEmpty Then
For conversionIndex = 0 To bestResult.ConversionsOpt.Length - 1
Dim conversion = bestResult.ConversionsOpt(conversionIndex)
Dim delegateParameterType = delegateInvoke.Parameters(conversionIndex).Type
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conversion.Key,
delegateParameterType)
Next
End If
' in case of ByRef, there might also be backward conversions
If Not bestResult.ConversionsBackOpt.IsDefaultOrEmpty Then
For conversionIndex = 0 To bestResult.ConversionsBackOpt.Length - 1
Dim conversion = bestResult.ConversionsBackOpt(conversionIndex)
If Not Conversions.IsIdentityConversion(conversion.Key) Then
Dim targetMethodParameterType = bestCandidate.Parameters(conversionIndex).Type
methodConversions = methodConversions Or
Conversions.ClassifyMethodConversionBasedOnArgumentConversion(conversion.Key,
targetMethodParameterType)
End If
Next
End If
Return methodConversions
End Function
''' <summary>
''' Classifies the address of conversion.
''' </summary>
''' <param name="source">The bound AddressOf expression.</param>
''' <param name="destination">The target type to convert this AddressOf expression to.</param><returns></returns>
Friend Shared Function ClassifyAddressOfConversion(
source As BoundAddressOfOperator,
destination As TypeSymbol
) As ConversionKind
Return source.GetConversionClassification(destination)
End Function
Private Shared ReadOnly s_checkDelegateParameterModifierCallback As CheckParameterModifierDelegate = AddressOf CheckDelegateParameterModifier
''' <summary>
''' Checks if a parameter is a ParamArray and reports this as an error.
''' </summary>
''' <param name="container">The containing type.</param>
''' <param name="token">The current parameter token.</param>
''' <param name="flag">The flags of this parameter.</param>
''' <param name="diagnostics">The diagnostics.</param>
Private Shared Function CheckDelegateParameterModifier(
container As Symbol,
token As SyntaxToken,
flag As SourceParameterFlags,
diagnostics As BindingDiagnosticBag
) As SourceParameterFlags
' 9.2.5.4: ParamArray parameters may not be specified in delegate or event declarations.
If (flag And SourceParameterFlags.ParamArray) = SourceParameterFlags.ParamArray Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_ParamArrayIllegal1, location, GetDelegateOrEventKeywordText(container))
flag = flag And (Not SourceParameterFlags.ParamArray)
End If
' 9.2.5.3 Optional parameters may not be specified on delegate or event declarations
If (flag And SourceParameterFlags.Optional) = SourceParameterFlags.Optional Then
Dim location = token.GetLocation()
diagnostics.Add(ERRID.ERR_OptionalIllegal1, location, GetDelegateOrEventKeywordText(container))
flag = flag And (Not SourceParameterFlags.Optional)
End If
Return flag
End Function
Private Shared Function GetDelegateOrEventKeywordText(sym As Symbol) As String
Dim keyword As SyntaxKind
If sym.Kind = SymbolKind.Event Then
keyword = SyntaxKind.EventKeyword
ElseIf TypeOf sym.ContainingType Is SynthesizedEventDelegateSymbol Then
keyword = SyntaxKind.EventKeyword
Else
keyword = SyntaxKind.DelegateKeyword
End If
Return SyntaxFacts.GetText(keyword)
End Function
''' <summary>
''' Reclassifies the bound address of operator into a delegate creation expression (if there is no delegate
''' relaxation required) or into a bound lambda expression (which gets a delegate creation expression later on)
''' </summary>
''' <param name="addressOfExpression">The AddressOf expression.</param>
''' <param name="delegateResolutionResult">The delegate resolution result.</param>
''' <param name="targetType">Type of the target.</param>
''' <param name="diagnostics">The diagnostics.</param><returns></returns>
Friend Function ReclassifyAddressOf(
addressOfExpression As BoundAddressOfOperator,
ByRef delegateResolutionResult As DelegateResolutionResult,
targetType As TypeSymbol,
diagnostics As BindingDiagnosticBag,
isForHandles As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean
) As BoundExpression
If addressOfExpression.HasErrors Then
Return addressOfExpression
End If
Dim boundLambda As BoundLambda = Nothing
Dim relaxationReceiverPlaceholder As BoundRValuePlaceholder = Nothing
Dim syntaxNode = addressOfExpression.Syntax
Dim targetMethod As MethodSymbol = delegateResolutionResult.Target
Dim reducedFromDefinition As MethodSymbol = targetMethod.ReducedFrom
Dim sourceMethodGroup = addressOfExpression.MethodGroup
Dim receiver As BoundExpression = sourceMethodGroup.ReceiverOpt
Dim resolvedTypeOrValueReceiver As BoundExpression = Nothing
If receiver IsNot Nothing AndAlso
Not addressOfExpression.HasErrors AndAlso
Not delegateResolutionResult.Diagnostics.Diagnostics.HasAnyErrors Then
receiver = AdjustReceiverTypeOrValue(receiver, receiver.Syntax, targetMethod.IsShared, diagnostics, resolvedTypeOrValueReceiver)
End If
If Me.OptionStrict = OptionStrict.On AndAlso Conversions.IsNarrowingConversion(delegateResolutionResult.DelegateConversions) Then
Dim addressOfOperandSyntax = addressOfExpression.Syntax
If addressOfOperandSyntax.Kind = SyntaxKind.AddressOfExpression Then
addressOfOperandSyntax = DirectCast(addressOfOperandSyntax, UnaryExpressionSyntax).Operand
End If
' Option Strict On does not allow narrowing in implicit type conversion between method '{0}' and delegate "{1}".
ReportDelegateBindingMismatchStrictOff(addressOfOperandSyntax, DirectCast(targetType, NamedTypeSymbol), targetMethod, diagnostics)
Else
' When the target method is an extension method, we are creating so called curried delegate.
' However, CLR doesn't support creating curried delegates that close over a ByRef 'this' argument.
' A similar problem exists when the 'this' argument is a value type. For these cases we need a stub too,
' but they are not covered by MethodConversionKind.
If Conversions.IsStubRequiredForMethodConversion(delegateResolutionResult.MethodConversions) OrElse
(reducedFromDefinition IsNot Nothing AndAlso
(reducedFromDefinition.Parameters(0).IsByRef OrElse
targetMethod.ReceiverType.IsTypeParameter() OrElse
targetMethod.ReceiverType.IsValueType)) Then
' because of a delegate relaxation there is a conversion needed to create a delegate instance.
' We will create a lambda with the exact signature of the delegate. This lambda itself will
' call the target method.
boundLambda = BuildDelegateRelaxationLambda(syntaxNode, sourceMethodGroup.Syntax, receiver, targetMethod,
sourceMethodGroup.TypeArgumentsOpt, sourceMethodGroup.QualificationKind,
DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod,
delegateResolutionResult.DelegateConversions And ConversionKind.DelegateRelaxationLevelMask,
isZeroArgumentKnownToBeUsed:=(delegateResolutionResult.MethodConversions And MethodConversionKind.AllArgumentsIgnored) <> 0,
diagnostics:=diagnostics,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=warnIfResultOfAsyncMethodIsDroppedDueToRelaxation,
relaxationReceiverPlaceholder:=relaxationReceiverPlaceholder)
End If
End If
Dim target As MethodSymbol = delegateResolutionResult.Target
' Check if the target is a partial method without implementation provided
If Not isForHandles AndAlso target.IsPartialWithoutImplementation Then
ReportDiagnostic(diagnostics, addressOfExpression.MethodGroup.Syntax, ERRID.ERR_NoPartialMethodInAddressOf1, target)
End If
Dim newReceiver As BoundExpression
If receiver IsNot Nothing Then
If receiver.IsPropertyOrXmlPropertyAccess() Then
receiver = MakeRValue(receiver, diagnostics)
End If
newReceiver = Nothing
Else
newReceiver = If(resolvedTypeOrValueReceiver, sourceMethodGroup.ReceiverOpt)
End If
sourceMethodGroup = sourceMethodGroup.Update(sourceMethodGroup.TypeArgumentsOpt,
sourceMethodGroup.Methods,
sourceMethodGroup.PendingExtensionMethodsOpt,
sourceMethodGroup.ResultKind,
newReceiver,
sourceMethodGroup.QualificationKind)
' the delegate creation has the lambda stored internally to not clutter the bound tree with synthesized nodes
' in the first pass. Later on in the DelegateRewriter the node get's rewritten with the lambda if needed.
Return New BoundDelegateCreationExpression(syntaxNode,
receiver,
target,
boundLambda,
relaxationReceiverPlaceholder,
sourceMethodGroup,
targetType,
hasErrors:=False)
End Function
Private Function BuildDelegateRelaxationLambda(
syntaxNode As SyntaxNode,
methodGroupSyntax As SyntaxNode,
receiver As BoundExpression,
targetMethod As MethodSymbol,
typeArgumentsOpt As BoundTypeArguments,
qualificationKind As QualificationKind,
delegateInvoke As MethodSymbol,
delegateRelaxation As ConversionKind,
isZeroArgumentKnownToBeUsed As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean,
diagnostics As BindingDiagnosticBag,
<Out()> ByRef relaxationReceiverPlaceholder As BoundRValuePlaceholder
) As BoundLambda
relaxationReceiverPlaceholder = Nothing
Dim unconstructedTargetMethod As MethodSymbol = targetMethod.ConstructedFrom
If typeArgumentsOpt Is Nothing AndAlso unconstructedTargetMethod.IsGenericMethod Then
typeArgumentsOpt = New BoundTypeArguments(methodGroupSyntax,
targetMethod.TypeArguments)
typeArgumentsOpt.SetWasCompilerGenerated()
End If
Dim actualReceiver As BoundExpression = receiver
' Figure out if we need to capture the receiver in a temp before creating the lambda
' in order to enforce correct semantics.
If actualReceiver IsNot Nothing AndAlso actualReceiver.IsValue() AndAlso Not actualReceiver.HasErrors Then
If actualReceiver.IsInstanceReference() AndAlso targetMethod.ReceiverType.IsReferenceType Then
Debug.Assert(Not actualReceiver.Type.IsTypeParameter())
Debug.Assert(Not actualReceiver.IsLValue) ' See the comment below why this is important.
Else
' Will need to capture the receiver in a temp, rewriter do the job.
relaxationReceiverPlaceholder = New BoundRValuePlaceholder(actualReceiver.Syntax, actualReceiver.Type)
actualReceiver = relaxationReceiverPlaceholder
End If
End If
Dim methodGroup = New BoundMethodGroup(methodGroupSyntax,
typeArgumentsOpt,
ImmutableArray.Create(unconstructedTargetMethod),
LookupResultKind.Good,
actualReceiver,
qualificationKind)
methodGroup.SetWasCompilerGenerated()
Return BuildDelegateRelaxationLambda(syntaxNode,
delegateInvoke,
methodGroup,
delegateRelaxation,
isZeroArgumentKnownToBeUsed,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation,
diagnostics)
End Function
''' <summary>
''' Build a lambda that has a shape of the [delegateInvoke] and calls
''' the only method from the [methodGroup] passing all parameters of the lambda
''' as arguments for the call.
''' Note, that usually the receiver of the [methodGroup] should be captured before entering the
''' relaxation lambda in order to prevent its reevaluation every time the lambda is invoked and
''' prevent its mutation.
'''
''' !!! Therefore, it is not common to call this overload directly. !!!
'''
''' </summary>
''' <param name="syntaxNode">Location to use for various synthetic nodes and symbols.</param>
''' <param name="delegateInvoke">The Invoke method to "implement".</param>
''' <param name="methodGroup">The method group with the only method in it.</param>
''' <param name="delegateRelaxation">Delegate relaxation to store within the new BoundLambda node.</param>
''' <param name="diagnostics"></param>
Private Function BuildDelegateRelaxationLambda(
syntaxNode As SyntaxNode,
delegateInvoke As MethodSymbol,
methodGroup As BoundMethodGroup,
delegateRelaxation As ConversionKind,
isZeroArgumentKnownToBeUsed As Boolean,
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation As Boolean,
diagnostics As BindingDiagnosticBag
) As BoundLambda
Debug.Assert(delegateInvoke.MethodKind = MethodKind.DelegateInvoke)
Debug.Assert(methodGroup.Methods.Length = 1)
Debug.Assert(methodGroup.PendingExtensionMethodsOpt Is Nothing)
Debug.Assert((delegateRelaxation And (Not ConversionKind.DelegateRelaxationLevelMask)) = 0)
' build lambda symbol parameters matching the invocation method exactly. To do this,
' we'll create a BoundLambdaParameterSymbol for each parameter of the invoke method.
Dim delegateInvokeReturnType = delegateInvoke.ReturnType
Dim invokeParameters = delegateInvoke.Parameters
Dim invokeParameterCount = invokeParameters.Length
Dim lambdaSymbolParameters(invokeParameterCount - 1) As BoundLambdaParameterSymbol
Dim addressOfLocation As Location = syntaxNode.GetLocation()
For parameterIndex = 0 To invokeParameterCount - 1
Dim parameter = invokeParameters(parameterIndex)
lambdaSymbolParameters(parameterIndex) = New BoundLambdaParameterSymbol(GeneratedNames.MakeDelegateRelaxationParameterName(parameterIndex),
parameter.Ordinal,
parameter.Type,
parameter.IsByRef,
syntaxNode,
addressOfLocation)
Next
' even if the return value is dropped, we're using the delegate's return type for
' this lambda symbol.
Dim lambdaSymbol = New SynthesizedLambdaSymbol(SynthesizedLambdaKind.DelegateRelaxationStub,
syntaxNode,
lambdaSymbolParameters.AsImmutable(),
delegateInvokeReturnType,
Me)
' the body of the lambda only contains a call to the target (or a return of the return value of
' the call in case of a function)
' for each parameter of the lambda symbol/invoke method we will create a bound parameter, except
' we are implementing a zero argument relaxation.
' These parameters will be used in the method invocation as passed parameters.
Dim method As MethodSymbol = methodGroup.Methods(0)
Dim droppedArguments = isZeroArgumentKnownToBeUsed OrElse (invokeParameterCount > 0 AndAlso method.ParameterCount = 0)
Dim targetParameterCount = If(droppedArguments, 0, invokeParameterCount)
Dim lambdaBoundParameters(targetParameterCount - 1) As BoundExpression
If Not droppedArguments Then
For parameterIndex = 0 To lambdaSymbolParameters.Length - 1
Dim lambdaSymbolParameter = lambdaSymbolParameters(parameterIndex)
Dim boundParameter = New BoundParameter(syntaxNode,
lambdaSymbolParameter,
lambdaSymbolParameter.Type)
boundParameter.SetWasCompilerGenerated()
lambdaBoundParameters(parameterIndex) = boundParameter
Next
End If
'The invocation of the target method must be bound in the context of the lambda
'The reason is that binding the invoke may introduce local symbols and they need
'to be properly parented to the lambda and not to the outer method.
Dim lambdaBinder = New LambdaBodyBinder(lambdaSymbol, Me)
' Dev10 ignores the type characters used in the operand of an AddressOf operator.
' NOTE: we suppress suppressAbstractCallDiagnostics because it
' should have been reported already
Dim boundInvocationExpression As BoundExpression = lambdaBinder.BindInvocationExpression(syntaxNode,
syntaxNode,
TypeCharacter.None,
methodGroup,
lambdaBoundParameters.AsImmutable(),
Nothing,
diagnostics,
suppressAbstractCallDiagnostics:=True,
callerInfoOpt:=Nothing)
boundInvocationExpression.SetWasCompilerGenerated()
' In case of a function target that got assigned to a sub delegate, the return value will be dropped
Dim statementList As ImmutableArray(Of BoundStatement) = Nothing
If lambdaSymbol.IsSub Then
Dim statements(1) As BoundStatement
Dim boundStatement As BoundStatement = New BoundExpressionStatement(syntaxNode, boundInvocationExpression)
boundStatement.SetWasCompilerGenerated()
statements(0) = boundStatement
boundStatement = New BoundReturnStatement(syntaxNode, Nothing, Nothing, Nothing)
boundStatement.SetWasCompilerGenerated()
statements(1) = boundStatement
statementList = statements.AsImmutableOrNull
If warnIfResultOfAsyncMethodIsDroppedDueToRelaxation AndAlso
Not method.IsSub Then
If Not method.IsAsync Then
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = False
If method.MethodKind = MethodKind.DelegateInvoke AndAlso
methodGroup.ReceiverOpt IsNot Nothing AndAlso
methodGroup.ReceiverOpt.Kind = BoundKind.Conversion Then
Dim receiver = DirectCast(methodGroup.ReceiverOpt, BoundConversion)
If Not receiver.ExplicitCastInCode AndAlso
receiver.Operand.Kind = BoundKind.Lambda AndAlso
DirectCast(receiver.Operand, BoundLambda).LambdaSymbol.IsAsync AndAlso
receiver.Type.IsDelegateType() AndAlso
receiver.Type.IsAnonymousType Then
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = True
End If
End If
Else
warnIfResultOfAsyncMethodIsDroppedDueToRelaxation = method.ContainingAssembly Is Compilation.Assembly
End If
If warnIfResultOfAsyncMethodIsDroppedDueToRelaxation Then
ReportDiagnostic(diagnostics, syntaxNode, ERRID.WRN_UnobservedAwaitableDelegate)
End If
End If
Else
' process conversions between the return types of the target and invoke function if needed.
boundInvocationExpression = lambdaBinder.ApplyImplicitConversion(syntaxNode,
delegateInvokeReturnType,
boundInvocationExpression,
diagnostics)
Dim returnstmt As BoundStatement = New BoundReturnStatement(syntaxNode,
boundInvocationExpression,
Nothing,
Nothing)
returnstmt.SetWasCompilerGenerated()
statementList = ImmutableArray.Create(returnstmt)
End If
Dim lambdaBody = New BoundBlock(syntaxNode,
Nothing,
ImmutableArray(Of LocalSymbol).Empty,
statementList)
lambdaBody.SetWasCompilerGenerated()
Dim boundLambda = New BoundLambda(syntaxNode,
lambdaSymbol,
lambdaBody,
ImmutableBindingDiagnostic(Of AssemblySymbol).Empty,
Nothing,
delegateRelaxation,
MethodConversionKind.Identity)
boundLambda.SetWasCompilerGenerated()
Return boundLambda
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/VisualStudio/CSharp/Test/PersistentStorage/SQLiteV2PersistentStorageTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SQLite.v2;
using Microsoft.CodeAnalysis.Storage;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices
{
/// <remarks>
/// Tests are inherited from <see cref="AbstractPersistentStorageTests"/>. That way we can
/// write tests once and have them run against all <see cref="IPersistentStorageService"/>
/// implementations.
/// </remarks>
public class SQLiteV2PersistentStorageTests : AbstractPersistentStorageTests
{
internal override AbstractPersistentStorageService GetStorageService(OptionSet options, IMefHostExportProvider exportProvider, IPersistentStorageLocationService locationService, IPersistentStorageFaultInjector? faultInjector, string relativePathBase)
=> new SQLitePersistentStorageService(
options,
exportProvider.GetExports<SQLiteConnectionPoolService>().Single().Value,
locationService,
exportProvider.GetExports<IAsynchronousOperationListenerProvider>().Single().Value.GetListener(FeatureAttribute.PersistentStorage),
faultInjector);
[Fact]
public async Task TestCrashInNewConnection()
{
var solution = CreateOrOpenSolution(nullPaths: true);
var hitInjector = false;
var faultInjector = new PersistentStorageFaultInjector(
onNewConnection: () =>
{
hitInjector = true;
throw new Exception();
},
onFatalError: e => throw e);
// Because instantiating the connection will fail, we will not get back
// a working persistent storage.
await using (var storage = await GetStorageAsync(solution, faultInjector))
using (var memStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memStream))
{
streamWriter.WriteLine("contents");
streamWriter.Flush();
memStream.Position = 0;
await storage.WriteStreamAsync("temp", memStream);
var readStream = await storage.ReadStreamAsync("temp");
// Because we don't have a real storage service, we should get back
// null even when trying to read something we just wrote.
Assert.Null(readStream);
}
Assert.True(hitInjector);
// Ensure we don't get a crash due to SqlConnection's finalizer running.
for (var i = 0; i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
private class PersistentStorageFaultInjector : IPersistentStorageFaultInjector
{
private readonly Action? _onNewConnection;
private readonly Action<Exception>? _onFatalError;
public PersistentStorageFaultInjector(
Action? onNewConnection = null,
Action<Exception>? onFatalError = null)
{
_onNewConnection = onNewConnection;
_onFatalError = onFatalError;
}
public void OnNewConnection()
=> _onNewConnection?.Invoke();
public void OnFatalError(Exception ex)
=> _onFatalError?.Invoke(ex);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SQLite.v2;
using Microsoft.CodeAnalysis.Storage;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices
{
/// <remarks>
/// Tests are inherited from <see cref="AbstractPersistentStorageTests"/>. That way we can
/// write tests once and have them run against all <see cref="IPersistentStorageService"/>
/// implementations.
/// </remarks>
public class SQLiteV2PersistentStorageTests : AbstractPersistentStorageTests
{
internal override AbstractPersistentStorageService GetStorageService(OptionSet options, IMefHostExportProvider exportProvider, IPersistentStorageLocationService locationService, IPersistentStorageFaultInjector? faultInjector, string relativePathBase)
=> new SQLitePersistentStorageService(
options,
exportProvider.GetExports<SQLiteConnectionPoolService>().Single().Value,
locationService,
exportProvider.GetExports<IAsynchronousOperationListenerProvider>().Single().Value.GetListener(FeatureAttribute.PersistentStorage),
faultInjector);
[Fact]
public async Task TestCrashInNewConnection()
{
var solution = CreateOrOpenSolution(nullPaths: true);
var hitInjector = false;
var faultInjector = new PersistentStorageFaultInjector(
onNewConnection: () =>
{
hitInjector = true;
throw new Exception();
},
onFatalError: e => throw e);
// Because instantiating the connection will fail, we will not get back
// a working persistent storage.
await using (var storage = await GetStorageAsync(solution, faultInjector))
using (var memStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memStream))
{
streamWriter.WriteLine("contents");
streamWriter.Flush();
memStream.Position = 0;
await storage.WriteStreamAsync("temp", memStream);
var readStream = await storage.ReadStreamAsync("temp");
// Because we don't have a real storage service, we should get back
// null even when trying to read something we just wrote.
Assert.Null(readStream);
}
Assert.True(hitInjector);
// Ensure we don't get a crash due to SqlConnection's finalizer running.
for (var i = 0; i < 10; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
private class PersistentStorageFaultInjector : IPersistentStorageFaultInjector
{
private readonly Action? _onNewConnection;
private readonly Action<Exception>? _onFatalError;
public PersistentStorageFaultInjector(
Action? onNewConnection = null,
Action<Exception>? onFatalError = null)
{
_onNewConnection = onNewConnection;
_onFatalError = onFatalError;
}
public void OnNewConnection()
=> _onNewConnection?.Invoke();
public void OnFatalError(Exception ex)
=> _onFatalError?.Invoke(ex);
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/Core/Portable/Shared/Utilities/ExtensionOrderer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal static partial class ExtensionOrderer
{
internal static IList<Lazy<TExtension, TMetadata>> Order<TExtension, TMetadata>(
IEnumerable<Lazy<TExtension, TMetadata>> extensions)
where TMetadata : OrderableMetadata
{
var graph = GetGraph(extensions);
return graph.TopologicalSort();
}
private static Graph<TExtension, TMetadata> GetGraph<TExtension, TMetadata>(
IEnumerable<Lazy<TExtension, TMetadata>> extensions)
where TMetadata : OrderableMetadata
{
var list = extensions.ToList();
var graph = new Graph<TExtension, TMetadata>();
foreach (var extension in list)
{
graph.Nodes.Add(extension, new Node<TExtension, TMetadata>(extension));
}
foreach (var extension in list)
{
var extensionNode = graph.Nodes[extension];
foreach (var before in extension.Metadata.BeforeTyped)
{
foreach (var beforeExtension in graph.FindExtensions(before))
{
var otherExtensionNode = graph.Nodes[beforeExtension];
otherExtensionNode.ExtensionsBeforeMeSet.Add(extensionNode);
}
}
foreach (var after in extension.Metadata.AfterTyped)
{
foreach (var afterExtension in graph.FindExtensions(after))
{
var otherExtensionNode = graph.Nodes[afterExtension];
extensionNode.ExtensionsBeforeMeSet.Add(otherExtensionNode);
}
}
}
return graph;
}
internal static class TestAccessor
{
/// <summary>
/// Helper for checking whether cycles exist in the extension ordering.
/// Throws <see cref="ArgumentException"/> if a cycle is detected.
/// </summary>
/// <exception cref="ArgumentException">A cycle was detected in the extension ordering.</exception>
internal static void CheckForCycles<TExtension, TMetadata>(
IEnumerable<Lazy<TExtension, TMetadata>> extensions)
where TMetadata : OrderableMetadata
{
var graph = GetGraph(extensions);
graph.CheckForCycles();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal static partial class ExtensionOrderer
{
internal static IList<Lazy<TExtension, TMetadata>> Order<TExtension, TMetadata>(
IEnumerable<Lazy<TExtension, TMetadata>> extensions)
where TMetadata : OrderableMetadata
{
var graph = GetGraph(extensions);
return graph.TopologicalSort();
}
private static Graph<TExtension, TMetadata> GetGraph<TExtension, TMetadata>(
IEnumerable<Lazy<TExtension, TMetadata>> extensions)
where TMetadata : OrderableMetadata
{
var list = extensions.ToList();
var graph = new Graph<TExtension, TMetadata>();
foreach (var extension in list)
{
graph.Nodes.Add(extension, new Node<TExtension, TMetadata>(extension));
}
foreach (var extension in list)
{
var extensionNode = graph.Nodes[extension];
foreach (var before in extension.Metadata.BeforeTyped)
{
foreach (var beforeExtension in graph.FindExtensions(before))
{
var otherExtensionNode = graph.Nodes[beforeExtension];
otherExtensionNode.ExtensionsBeforeMeSet.Add(extensionNode);
}
}
foreach (var after in extension.Metadata.AfterTyped)
{
foreach (var afterExtension in graph.FindExtensions(after))
{
var otherExtensionNode = graph.Nodes[afterExtension];
extensionNode.ExtensionsBeforeMeSet.Add(otherExtensionNode);
}
}
}
return graph;
}
internal static class TestAccessor
{
/// <summary>
/// Helper for checking whether cycles exist in the extension ordering.
/// Throws <see cref="ArgumentException"/> if a cycle is detected.
/// </summary>
/// <exception cref="ArgumentException">A cycle was detected in the extension ordering.</exception>
internal static void CheckForCycles<TExtension, TMetadata>(
IEnumerable<Lazy<TExtension, TMetadata>> extensions)
where TMetadata : OrderableMetadata
{
var graph = GetGraph(extensions);
graph.CheckForCycles();
}
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/Core/Shared/Utilities/ForegroundThreadAffinitizedObject.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
/// <summary>
/// Base class that allows some helpers for detecting whether we're on the main WPF foreground thread, or
/// a background thread. It also allows scheduling work to the foreground thread at below input priority.
/// </summary>
internal class ForegroundThreadAffinitizedObject
{
private readonly IThreadingContext _threadingContext;
internal IThreadingContext ThreadingContext => _threadingContext;
public ForegroundThreadAffinitizedObject(IThreadingContext threadingContext, bool assertIsForeground = false)
{
_threadingContext = threadingContext ?? throw new ArgumentNullException(nameof(threadingContext));
// ForegroundThreadAffinitizedObject might not necessarily be created on a foreground thread.
// AssertIsForeground here only if the object must be created on a foreground thread.
if (assertIsForeground)
{
// Assert we have some kind of foreground thread
Contract.ThrowIfFalse(threadingContext.HasMainThread);
AssertIsForeground();
}
}
public bool IsForeground()
=> _threadingContext.JoinableTaskContext.IsOnMainThread;
public void AssertIsForeground()
{
var whenCreatedThread = _threadingContext.JoinableTaskContext.MainThread;
var currentThread = Thread.CurrentThread;
// In debug, provide a lot more information so that we can track down unit test flakiness.
// This is too expensive to do in retail as it creates way too many allocations.
Debug.Assert(currentThread == whenCreatedThread,
"When created thread id : " + whenCreatedThread?.ManagedThreadId + "\r\n" +
"When created thread name: " + whenCreatedThread?.Name + "\r\n" +
"Current thread id : " + currentThread?.ManagedThreadId + "\r\n" +
"Current thread name : " + currentThread?.Name);
// But, in retail, do the check as well, so that we can catch problems that happen in the wild.
Contract.ThrowIfFalse(_threadingContext.JoinableTaskContext.IsOnMainThread);
}
public void AssertIsBackground()
=> Contract.ThrowIfTrue(IsForeground());
/// <summary>
/// A helpful marker method that can be used by deriving classes to indicate that a
/// method can be called from any thread and is not foreground or background affinitized.
/// This is useful so that every method in deriving class can have some sort of marker
/// on each method stating the threading constraints (FG-only/BG-only/Any-thread).
/// </summary>
public static void ThisCanBeCalledOnAnyThread()
{
// Does nothing.
}
public Task InvokeBelowInputPriorityAsync(Action action, CancellationToken cancellationToken = default)
{
if (IsForeground() && !IsInputPending())
{
// Optimize to inline the action if we're already on the foreground thread
// and there's no pending user input.
action();
return Task.CompletedTask;
}
else
{
return Task.Factory.SafeStartNewFromAsync(
async () =>
{
await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
action();
},
cancellationToken,
TaskScheduler.Default);
}
}
/// <summary>
/// Returns true if any keyboard or mouse button input is pending on the message queue.
/// </summary>
protected static bool IsInputPending()
{
// The code below invokes into user32.dll, which is not available in non-Windows.
if (PlatformInformation.IsUnix)
{
return false;
}
// The return value of GetQueueStatus is HIWORD:LOWORD.
// A non-zero value in HIWORD indicates some input message in the queue.
var result = NativeMethods.GetQueueStatus(NativeMethods.QS_INPUT);
const uint InputMask = NativeMethods.QS_INPUT | (NativeMethods.QS_INPUT << 16);
return (result & InputMask) != 0;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
/// <summary>
/// Base class that allows some helpers for detecting whether we're on the main WPF foreground thread, or
/// a background thread. It also allows scheduling work to the foreground thread at below input priority.
/// </summary>
internal class ForegroundThreadAffinitizedObject
{
private readonly IThreadingContext _threadingContext;
internal IThreadingContext ThreadingContext => _threadingContext;
public ForegroundThreadAffinitizedObject(IThreadingContext threadingContext, bool assertIsForeground = false)
{
_threadingContext = threadingContext ?? throw new ArgumentNullException(nameof(threadingContext));
// ForegroundThreadAffinitizedObject might not necessarily be created on a foreground thread.
// AssertIsForeground here only if the object must be created on a foreground thread.
if (assertIsForeground)
{
// Assert we have some kind of foreground thread
Contract.ThrowIfFalse(threadingContext.HasMainThread);
AssertIsForeground();
}
}
public bool IsForeground()
=> _threadingContext.JoinableTaskContext.IsOnMainThread;
public void AssertIsForeground()
{
var whenCreatedThread = _threadingContext.JoinableTaskContext.MainThread;
var currentThread = Thread.CurrentThread;
// In debug, provide a lot more information so that we can track down unit test flakiness.
// This is too expensive to do in retail as it creates way too many allocations.
Debug.Assert(currentThread == whenCreatedThread,
"When created thread id : " + whenCreatedThread?.ManagedThreadId + "\r\n" +
"When created thread name: " + whenCreatedThread?.Name + "\r\n" +
"Current thread id : " + currentThread?.ManagedThreadId + "\r\n" +
"Current thread name : " + currentThread?.Name);
// But, in retail, do the check as well, so that we can catch problems that happen in the wild.
Contract.ThrowIfFalse(_threadingContext.JoinableTaskContext.IsOnMainThread);
}
public void AssertIsBackground()
=> Contract.ThrowIfTrue(IsForeground());
/// <summary>
/// A helpful marker method that can be used by deriving classes to indicate that a
/// method can be called from any thread and is not foreground or background affinitized.
/// This is useful so that every method in deriving class can have some sort of marker
/// on each method stating the threading constraints (FG-only/BG-only/Any-thread).
/// </summary>
public static void ThisCanBeCalledOnAnyThread()
{
// Does nothing.
}
public Task InvokeBelowInputPriorityAsync(Action action, CancellationToken cancellationToken = default)
{
if (IsForeground() && !IsInputPending())
{
// Optimize to inline the action if we're already on the foreground thread
// and there's no pending user input.
action();
return Task.CompletedTask;
}
else
{
return Task.Factory.SafeStartNewFromAsync(
async () =>
{
await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
action();
},
cancellationToken,
TaskScheduler.Default);
}
}
/// <summary>
/// Returns true if any keyboard or mouse button input is pending on the message queue.
/// </summary>
protected static bool IsInputPending()
{
// The code below invokes into user32.dll, which is not available in non-Windows.
if (PlatformInformation.IsUnix)
{
return false;
}
// The return value of GetQueueStatus is HIWORD:LOWORD.
// A non-zero value in HIWORD indicates some input message in the queue.
var result = NativeMethods.GetQueueStatus(NativeMethods.QS_INPUT);
const uint InputMask = NativeMethods.QS_INPUT | (NativeMethods.QS_INPUT << 16);
return (result & InputMask) != 0;
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Portable/Syntax/SyntaxNodeRemover.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
internal static class SyntaxNodeRemover
{
internal static TRoot? RemoveNodes<TRoot>(TRoot root,
IEnumerable<SyntaxNode> nodes,
SyntaxRemoveOptions options)
where TRoot : SyntaxNode
{
if (nodes == null)
{
return root;
}
var nodeArray = nodes.ToArray();
if (nodeArray.Length == 0)
{
return root;
}
var remover = new SyntaxRemover(nodes.ToArray(), options);
var result = remover.Visit(root);
var residualTrivia = remover.ResidualTrivia;
// the result of the SyntaxRemover will be null when the root node is removed.
if (result != null && residualTrivia.Count > 0)
{
result = result.WithTrailingTrivia(result.GetTrailingTrivia().Concat(residualTrivia));
}
return (TRoot?)result;
}
private class SyntaxRemover : CSharpSyntaxRewriter
{
private readonly HashSet<SyntaxNode> _nodesToRemove;
private readonly SyntaxRemoveOptions _options;
private readonly TextSpan _searchSpan;
private readonly SyntaxTriviaListBuilder _residualTrivia;
private HashSet<SyntaxNode>? _directivesToKeep;
public SyntaxRemover(
SyntaxNode[] nodesToRemove,
SyntaxRemoveOptions options)
: base(nodesToRemove.Any(n => n.IsPartOfStructuredTrivia()))
{
_nodesToRemove = new HashSet<SyntaxNode>(nodesToRemove);
_options = options;
_searchSpan = ComputeTotalSpan(nodesToRemove);
_residualTrivia = SyntaxTriviaListBuilder.Create();
}
private static TextSpan ComputeTotalSpan(SyntaxNode[] nodes)
{
var span0 = nodes[0].FullSpan;
int start = span0.Start;
int end = span0.End;
for (int i = 1; i < nodes.Length; i++)
{
var span = nodes[i].FullSpan;
start = Math.Min(start, span.Start);
end = Math.Max(end, span.End);
}
return new TextSpan(start, end - start);
}
internal SyntaxTriviaList ResidualTrivia
{
get
{
if (_residualTrivia != null)
{
return _residualTrivia.ToList();
}
else
{
return default(SyntaxTriviaList);
}
}
}
private void AddResidualTrivia(SyntaxTriviaList trivia, bool requiresNewLine = false)
{
if (requiresNewLine)
{
this.AddEndOfLine(GetEndOfLine(trivia) ?? SyntaxFactory.CarriageReturnLineFeed);
}
_residualTrivia.Add(trivia);
}
private void AddEndOfLine(SyntaxTrivia? eolTrivia)
{
if (!eolTrivia.HasValue)
{
return;
}
if (_residualTrivia.Count == 0 || !IsEndOfLine(_residualTrivia[_residualTrivia.Count - 1]))
{
_residualTrivia.Add(eolTrivia.Value);
}
}
/// <summary>
/// Returns whether the specified <see cref="SyntaxTrivia"/> token is also the end of the line. This will
/// be true for <see cref="SyntaxKind.EndOfLineTrivia"/>, <see cref="SyntaxKind.SingleLineCommentTrivia"/>,
/// and all preprocessor directives.
/// </summary>
private static bool IsEndOfLine(SyntaxTrivia trivia)
{
return trivia.Kind() == SyntaxKind.EndOfLineTrivia
|| trivia.Kind() == SyntaxKind.SingleLineCommentTrivia
|| trivia.IsDirective;
}
/// <summary>
/// Returns the first end of line found in a <see cref="SyntaxTriviaList"/>.
/// </summary>
private static SyntaxTrivia? GetEndOfLine(SyntaxTriviaList list)
{
foreach (var trivia in list)
{
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
return trivia;
}
if (trivia.IsDirective && trivia.GetStructure() is DirectiveTriviaSyntax directive)
{
return GetEndOfLine(directive.EndOfDirectiveToken.TrailingTrivia);
}
}
return null;
}
private bool IsForRemoval(SyntaxNode node)
{
return _nodesToRemove.Contains(node);
}
private bool ShouldVisit(SyntaxNode node)
{
return node.FullSpan.IntersectsWith(_searchSpan) || (_residualTrivia != null && _residualTrivia.Count > 0);
}
[return: NotNullIfNotNull("node")]
public override SyntaxNode? Visit(SyntaxNode? node)
{
SyntaxNode? result = node;
if (node != null)
{
if (this.IsForRemoval(node))
{
this.AddTrivia(node);
result = null;
}
else if (this.ShouldVisit(node))
{
result = base.Visit(node);
}
}
return result;
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
SyntaxToken result = token;
// only bother visiting trivia if we are removing a node in structured trivia
if (this.VisitIntoStructuredTrivia)
{
result = base.VisitToken(token);
}
// the next token gets the accrued trivia.
if (result.Kind() != SyntaxKind.None && _residualTrivia != null && _residualTrivia.Count > 0)
{
_residualTrivia.Add(result.LeadingTrivia);
result = result.WithLeadingTrivia(_residualTrivia.ToList());
_residualTrivia.Clear();
}
return result;
}
// deal with separated lists and removal of associated separators
public override SeparatedSyntaxList<TNode> VisitList<TNode>(SeparatedSyntaxList<TNode> list)
{
var withSeps = list.GetWithSeparators();
bool removeNextSeparator = false;
SyntaxNodeOrTokenListBuilder? alternate = null;
for (int i = 0, n = withSeps.Count; i < n; i++)
{
var item = withSeps[i];
SyntaxNodeOrToken visited;
if (item.IsToken) // separator
{
if (removeNextSeparator)
{
removeNextSeparator = false;
visited = default(SyntaxNodeOrToken);
}
else
{
visited = this.VisitListSeparator(item.AsToken());
}
}
else
{
var node = (TNode)item.AsNode()!;
if (this.IsForRemoval(node))
{
if (alternate == null)
{
alternate = new SyntaxNodeOrTokenListBuilder(n);
alternate.Add(withSeps, 0, i);
}
CommonSyntaxNodeRemover.GetSeparatorInfo(
withSeps, i, (int)SyntaxKind.EndOfLineTrivia,
out bool nextTokenIsSeparator, out bool nextSeparatorBelongsToNode);
if (!nextSeparatorBelongsToNode &&
alternate.Count > 0 &&
alternate[alternate.Count - 1].IsToken)
{
var separator = alternate[alternate.Count - 1].AsToken();
this.AddTrivia(separator, node);
alternate.RemoveLast();
}
else if (nextTokenIsSeparator)
{
var separator = withSeps[i + 1].AsToken();
this.AddTrivia(node, separator);
removeNextSeparator = true;
}
else
{
this.AddTrivia(node);
}
visited = default;
}
else
{
visited = this.VisitListElement(node);
}
}
if (item != visited && alternate == null)
{
alternate = new SyntaxNodeOrTokenListBuilder(n);
alternate.Add(withSeps, 0, i);
}
if (alternate != null && visited.Kind() != SyntaxKind.None)
{
alternate.Add(visited);
}
}
if (alternate != null)
{
return alternate.ToList().AsSeparatedList<TNode>();
}
return list;
}
private void AddTrivia(SyntaxNode node)
{
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetLeadingTrivia()));
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
this.AddDirectives(node, GetRemovedSpan(node.Span, node.FullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetTrailingTrivia()));
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private void AddTrivia(SyntaxToken token, SyntaxNode node)
{
Debug.Assert(node.Parent is object);
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(token.LeadingTrivia);
this.AddResidualTrivia(token.TrailingTrivia);
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
// For retrieving an EOL we don't need to check the node leading trivia as
// it can be always retrieved from the token trailing trivia, if one exists.
var eol = GetEndOfLine(token.LeadingTrivia) ??
GetEndOfLine(token.TrailingTrivia);
this.AddEndOfLine(eol);
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
var span = TextSpan.FromBounds(token.Span.Start, node.Span.End);
var fullSpan = TextSpan.FromBounds(token.FullSpan.Start, node.FullSpan.End);
this.AddDirectives(node.Parent, GetRemovedSpan(span, fullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetTrailingTrivia()));
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private void AddTrivia(SyntaxNode node, SyntaxToken token)
{
Debug.Assert(node.Parent is object);
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetLeadingTrivia()));
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
var span = TextSpan.FromBounds(node.Span.Start, token.Span.End);
var fullSpan = TextSpan.FromBounds(node.FullSpan.Start, token.FullSpan.End);
this.AddDirectives(node.Parent, GetRemovedSpan(span, fullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
this.AddResidualTrivia(token.LeadingTrivia);
this.AddResidualTrivia(token.TrailingTrivia);
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
// For retrieving an EOL we don't need to check the token leading trivia as
// it can be always retrieved from the node trailing trivia, if one exists.
var eol = GetEndOfLine(node.GetTrailingTrivia()) ??
GetEndOfLine(token.TrailingTrivia);
this.AddEndOfLine(eol);
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private TextSpan GetRemovedSpan(TextSpan span, TextSpan fullSpan)
{
var removedSpan = fullSpan;
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
removedSpan = TextSpan.FromBounds(span.Start, removedSpan.End);
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
removedSpan = TextSpan.FromBounds(removedSpan.Start, span.End);
}
return removedSpan;
}
private void AddDirectives(SyntaxNode node, TextSpan span)
{
if (node.ContainsDirectives)
{
if (_directivesToKeep == null)
{
_directivesToKeep = new HashSet<SyntaxNode>();
}
else
{
_directivesToKeep.Clear();
}
var directivesInSpan = node.DescendantTrivia(span, n => n.ContainsDirectives, descendIntoTrivia: true)
.Where(tr => tr.IsDirective)
.Select(tr => (DirectiveTriviaSyntax)tr.GetStructure()!);
foreach (var directive in directivesInSpan)
{
if ((_options & SyntaxRemoveOptions.KeepDirectives) != 0)
{
_directivesToKeep.Add(directive);
}
else if (directive.Kind() == SyntaxKind.DefineDirectiveTrivia ||
directive.Kind() == SyntaxKind.UndefDirectiveTrivia)
{
// always keep #define and #undef, even if we are only keeping unbalanced directives
_directivesToKeep.Add(directive);
}
else if (HasRelatedDirectives(directive))
{
// a balanced directive with respect to a given node has all related directives rooted under that node
var relatedDirectives = directive.GetRelatedDirectives();
var balanced = relatedDirectives.All(rd => rd.FullSpan.OverlapsWith(span));
if (!balanced)
{
// if not fully balanced, all related directives under the node are considered unbalanced.
foreach (var unbalancedDirective in relatedDirectives.Where(rd => rd.FullSpan.OverlapsWith(span)))
{
_directivesToKeep.Add(unbalancedDirective);
}
}
}
if (_directivesToKeep.Contains(directive))
{
AddResidualTrivia(SyntaxFactory.TriviaList(directive.ParentTrivia), requiresNewLine: true);
}
}
}
}
private static bool HasRelatedDirectives(DirectiveTriviaSyntax directive)
{
switch (directive.Kind())
{
case SyntaxKind.IfDirectiveTrivia:
case SyntaxKind.ElseDirectiveTrivia:
case SyntaxKind.ElifDirectiveTrivia:
case SyntaxKind.EndIfDirectiveTrivia:
case SyntaxKind.RegionDirectiveTrivia:
case SyntaxKind.EndRegionDirectiveTrivia:
return true;
default:
return false;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
internal static class SyntaxNodeRemover
{
internal static TRoot? RemoveNodes<TRoot>(TRoot root,
IEnumerable<SyntaxNode> nodes,
SyntaxRemoveOptions options)
where TRoot : SyntaxNode
{
if (nodes == null)
{
return root;
}
var nodeArray = nodes.ToArray();
if (nodeArray.Length == 0)
{
return root;
}
var remover = new SyntaxRemover(nodes.ToArray(), options);
var result = remover.Visit(root);
var residualTrivia = remover.ResidualTrivia;
// the result of the SyntaxRemover will be null when the root node is removed.
if (result != null && residualTrivia.Count > 0)
{
result = result.WithTrailingTrivia(result.GetTrailingTrivia().Concat(residualTrivia));
}
return (TRoot?)result;
}
private class SyntaxRemover : CSharpSyntaxRewriter
{
private readonly HashSet<SyntaxNode> _nodesToRemove;
private readonly SyntaxRemoveOptions _options;
private readonly TextSpan _searchSpan;
private readonly SyntaxTriviaListBuilder _residualTrivia;
private HashSet<SyntaxNode>? _directivesToKeep;
public SyntaxRemover(
SyntaxNode[] nodesToRemove,
SyntaxRemoveOptions options)
: base(nodesToRemove.Any(n => n.IsPartOfStructuredTrivia()))
{
_nodesToRemove = new HashSet<SyntaxNode>(nodesToRemove);
_options = options;
_searchSpan = ComputeTotalSpan(nodesToRemove);
_residualTrivia = SyntaxTriviaListBuilder.Create();
}
private static TextSpan ComputeTotalSpan(SyntaxNode[] nodes)
{
var span0 = nodes[0].FullSpan;
int start = span0.Start;
int end = span0.End;
for (int i = 1; i < nodes.Length; i++)
{
var span = nodes[i].FullSpan;
start = Math.Min(start, span.Start);
end = Math.Max(end, span.End);
}
return new TextSpan(start, end - start);
}
internal SyntaxTriviaList ResidualTrivia
{
get
{
if (_residualTrivia != null)
{
return _residualTrivia.ToList();
}
else
{
return default(SyntaxTriviaList);
}
}
}
private void AddResidualTrivia(SyntaxTriviaList trivia, bool requiresNewLine = false)
{
if (requiresNewLine)
{
this.AddEndOfLine(GetEndOfLine(trivia) ?? SyntaxFactory.CarriageReturnLineFeed);
}
_residualTrivia.Add(trivia);
}
private void AddEndOfLine(SyntaxTrivia? eolTrivia)
{
if (!eolTrivia.HasValue)
{
return;
}
if (_residualTrivia.Count == 0 || !IsEndOfLine(_residualTrivia[_residualTrivia.Count - 1]))
{
_residualTrivia.Add(eolTrivia.Value);
}
}
/// <summary>
/// Returns whether the specified <see cref="SyntaxTrivia"/> token is also the end of the line. This will
/// be true for <see cref="SyntaxKind.EndOfLineTrivia"/>, <see cref="SyntaxKind.SingleLineCommentTrivia"/>,
/// and all preprocessor directives.
/// </summary>
private static bool IsEndOfLine(SyntaxTrivia trivia)
{
return trivia.Kind() == SyntaxKind.EndOfLineTrivia
|| trivia.Kind() == SyntaxKind.SingleLineCommentTrivia
|| trivia.IsDirective;
}
/// <summary>
/// Returns the first end of line found in a <see cref="SyntaxTriviaList"/>.
/// </summary>
private static SyntaxTrivia? GetEndOfLine(SyntaxTriviaList list)
{
foreach (var trivia in list)
{
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
return trivia;
}
if (trivia.IsDirective && trivia.GetStructure() is DirectiveTriviaSyntax directive)
{
return GetEndOfLine(directive.EndOfDirectiveToken.TrailingTrivia);
}
}
return null;
}
private bool IsForRemoval(SyntaxNode node)
{
return _nodesToRemove.Contains(node);
}
private bool ShouldVisit(SyntaxNode node)
{
return node.FullSpan.IntersectsWith(_searchSpan) || (_residualTrivia != null && _residualTrivia.Count > 0);
}
[return: NotNullIfNotNull("node")]
public override SyntaxNode? Visit(SyntaxNode? node)
{
SyntaxNode? result = node;
if (node != null)
{
if (this.IsForRemoval(node))
{
this.AddTrivia(node);
result = null;
}
else if (this.ShouldVisit(node))
{
result = base.Visit(node);
}
}
return result;
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
SyntaxToken result = token;
// only bother visiting trivia if we are removing a node in structured trivia
if (this.VisitIntoStructuredTrivia)
{
result = base.VisitToken(token);
}
// the next token gets the accrued trivia.
if (result.Kind() != SyntaxKind.None && _residualTrivia != null && _residualTrivia.Count > 0)
{
_residualTrivia.Add(result.LeadingTrivia);
result = result.WithLeadingTrivia(_residualTrivia.ToList());
_residualTrivia.Clear();
}
return result;
}
// deal with separated lists and removal of associated separators
public override SeparatedSyntaxList<TNode> VisitList<TNode>(SeparatedSyntaxList<TNode> list)
{
var withSeps = list.GetWithSeparators();
bool removeNextSeparator = false;
SyntaxNodeOrTokenListBuilder? alternate = null;
for (int i = 0, n = withSeps.Count; i < n; i++)
{
var item = withSeps[i];
SyntaxNodeOrToken visited;
if (item.IsToken) // separator
{
if (removeNextSeparator)
{
removeNextSeparator = false;
visited = default(SyntaxNodeOrToken);
}
else
{
visited = this.VisitListSeparator(item.AsToken());
}
}
else
{
var node = (TNode)item.AsNode()!;
if (this.IsForRemoval(node))
{
if (alternate == null)
{
alternate = new SyntaxNodeOrTokenListBuilder(n);
alternate.Add(withSeps, 0, i);
}
CommonSyntaxNodeRemover.GetSeparatorInfo(
withSeps, i, (int)SyntaxKind.EndOfLineTrivia,
out bool nextTokenIsSeparator, out bool nextSeparatorBelongsToNode);
if (!nextSeparatorBelongsToNode &&
alternate.Count > 0 &&
alternate[alternate.Count - 1].IsToken)
{
var separator = alternate[alternate.Count - 1].AsToken();
this.AddTrivia(separator, node);
alternate.RemoveLast();
}
else if (nextTokenIsSeparator)
{
var separator = withSeps[i + 1].AsToken();
this.AddTrivia(node, separator);
removeNextSeparator = true;
}
else
{
this.AddTrivia(node);
}
visited = default;
}
else
{
visited = this.VisitListElement(node);
}
}
if (item != visited && alternate == null)
{
alternate = new SyntaxNodeOrTokenListBuilder(n);
alternate.Add(withSeps, 0, i);
}
if (alternate != null && visited.Kind() != SyntaxKind.None)
{
alternate.Add(visited);
}
}
if (alternate != null)
{
return alternate.ToList().AsSeparatedList<TNode>();
}
return list;
}
private void AddTrivia(SyntaxNode node)
{
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetLeadingTrivia()));
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
this.AddDirectives(node, GetRemovedSpan(node.Span, node.FullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetTrailingTrivia()));
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private void AddTrivia(SyntaxToken token, SyntaxNode node)
{
Debug.Assert(node.Parent is object);
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(token.LeadingTrivia);
this.AddResidualTrivia(token.TrailingTrivia);
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
// For retrieving an EOL we don't need to check the node leading trivia as
// it can be always retrieved from the token trailing trivia, if one exists.
var eol = GetEndOfLine(token.LeadingTrivia) ??
GetEndOfLine(token.TrailingTrivia);
this.AddEndOfLine(eol);
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
var span = TextSpan.FromBounds(token.Span.Start, node.Span.End);
var fullSpan = TextSpan.FromBounds(token.FullSpan.Start, node.FullSpan.End);
this.AddDirectives(node.Parent, GetRemovedSpan(span, fullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetTrailingTrivia()));
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private void AddTrivia(SyntaxNode node, SyntaxToken token)
{
Debug.Assert(node.Parent is object);
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
this.AddResidualTrivia(node.GetLeadingTrivia());
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
this.AddEndOfLine(GetEndOfLine(node.GetLeadingTrivia()));
}
if ((_options & (SyntaxRemoveOptions.KeepDirectives | SyntaxRemoveOptions.KeepUnbalancedDirectives)) != 0)
{
var span = TextSpan.FromBounds(node.Span.Start, token.Span.End);
var fullSpan = TextSpan.FromBounds(node.FullSpan.Start, token.FullSpan.End);
this.AddDirectives(node.Parent, GetRemovedSpan(span, fullSpan));
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
this.AddResidualTrivia(node.GetTrailingTrivia());
this.AddResidualTrivia(token.LeadingTrivia);
this.AddResidualTrivia(token.TrailingTrivia);
}
else if ((_options & SyntaxRemoveOptions.KeepEndOfLine) != 0)
{
// For retrieving an EOL we don't need to check the token leading trivia as
// it can be always retrieved from the node trailing trivia, if one exists.
var eol = GetEndOfLine(node.GetTrailingTrivia()) ??
GetEndOfLine(token.TrailingTrivia);
this.AddEndOfLine(eol);
}
if ((_options & SyntaxRemoveOptions.AddElasticMarker) != 0)
{
this.AddResidualTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker));
}
}
private TextSpan GetRemovedSpan(TextSpan span, TextSpan fullSpan)
{
var removedSpan = fullSpan;
if ((_options & SyntaxRemoveOptions.KeepLeadingTrivia) != 0)
{
removedSpan = TextSpan.FromBounds(span.Start, removedSpan.End);
}
if ((_options & SyntaxRemoveOptions.KeepTrailingTrivia) != 0)
{
removedSpan = TextSpan.FromBounds(removedSpan.Start, span.End);
}
return removedSpan;
}
private void AddDirectives(SyntaxNode node, TextSpan span)
{
if (node.ContainsDirectives)
{
if (_directivesToKeep == null)
{
_directivesToKeep = new HashSet<SyntaxNode>();
}
else
{
_directivesToKeep.Clear();
}
var directivesInSpan = node.DescendantTrivia(span, n => n.ContainsDirectives, descendIntoTrivia: true)
.Where(tr => tr.IsDirective)
.Select(tr => (DirectiveTriviaSyntax)tr.GetStructure()!);
foreach (var directive in directivesInSpan)
{
if ((_options & SyntaxRemoveOptions.KeepDirectives) != 0)
{
_directivesToKeep.Add(directive);
}
else if (directive.Kind() == SyntaxKind.DefineDirectiveTrivia ||
directive.Kind() == SyntaxKind.UndefDirectiveTrivia)
{
// always keep #define and #undef, even if we are only keeping unbalanced directives
_directivesToKeep.Add(directive);
}
else if (HasRelatedDirectives(directive))
{
// a balanced directive with respect to a given node has all related directives rooted under that node
var relatedDirectives = directive.GetRelatedDirectives();
var balanced = relatedDirectives.All(rd => rd.FullSpan.OverlapsWith(span));
if (!balanced)
{
// if not fully balanced, all related directives under the node are considered unbalanced.
foreach (var unbalancedDirective in relatedDirectives.Where(rd => rd.FullSpan.OverlapsWith(span)))
{
_directivesToKeep.Add(unbalancedDirective);
}
}
}
if (_directivesToKeep.Contains(directive))
{
AddResidualTrivia(SyntaxFactory.TriviaList(directive.ParentTrivia), requiresNewLine: true);
}
}
}
}
private static bool HasRelatedDirectives(DirectiveTriviaSyntax directive)
{
switch (directive.Kind())
{
case SyntaxKind.IfDirectiveTrivia:
case SyntaxKind.ElseDirectiveTrivia:
case SyntaxKind.ElifDirectiveTrivia:
case SyntaxKind.EndIfDirectiveTrivia:
case SyntaxKind.RegionDirectiveTrivia:
case SyntaxKind.EndRegionDirectiveTrivia:
return true;
default:
return false;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Portable/Symbols/DynamicTypeSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed partial class DynamicTypeSymbol : TypeSymbol
{
internal static readonly DynamicTypeSymbol Instance = new DynamicTypeSymbol();
private DynamicTypeSymbol()
{
}
public override string Name
{
get
{
return "dynamic";
}
}
public override bool IsAbstract
{
get
{
return false;
}
}
public override bool IsReferenceType
{
get
{
return true;
}
}
public override bool IsSealed
{
get
{
return false;
}
}
public override SymbolKind Kind
{
get
{
return SymbolKind.DynamicType;
}
}
public override TypeKind TypeKind
{
get
{
return TypeKind.Dynamic;
}
}
public override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray<Location>.Empty;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null;
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override bool IsStatic
{
get
{
return false;
}
}
public override bool IsValueType
{
get
{
return false;
}
}
internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => ManagedKind.Managed;
public sealed override bool IsRefLikeType
{
get
{
return false;
}
}
public sealed override bool IsReadOnly
{
get
{
return false;
}
}
internal sealed override ObsoleteAttributeData? ObsoleteAttributeData
{
get { return null; }
}
public override ImmutableArray<Symbol> GetMembers()
{
return ImmutableArray<Symbol>.Empty;
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
return ImmutableArray<Symbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument)
{
return visitor.VisitDynamicType(this, argument);
}
public override void Accept(CSharpSymbolVisitor visitor)
{
visitor.VisitDynamicType(this);
}
public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor)
{
return visitor.VisitDynamicType(this);
}
public override Symbol? ContainingSymbol
{
get
{
return null;
}
}
public override Accessibility DeclaredAccessibility
{
get
{
return Accessibility.NotApplicable;
}
}
internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes)
{
return false;
}
public override int GetHashCode()
{
// return the distinguished value for 'object' because the hash code ignores the distinction
// between dynamic and object. It also ignores custom modifiers.
return (int)Microsoft.CodeAnalysis.SpecialType.System_Object;
}
internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison)
{
if ((object?)t2 == null)
{
return false;
}
if (ReferenceEquals(this, t2) || t2.TypeKind == TypeKind.Dynamic)
{
return true;
}
if ((comparison & TypeCompareKind.IgnoreDynamic) != 0)
{
var other = t2 as NamedTypeSymbol;
return (object?)other != null && other.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object;
}
return false;
}
internal override void AddNullableTransforms(ArrayBuilder<byte> transforms)
{
}
internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result)
{
result = this;
return true;
}
internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform)
{
return this;
}
internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance)
{
Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes));
return this;
}
protected override ISymbol CreateISymbol()
{
return new PublicModel.DynamicTypeSymbol(this, DefaultNullableAnnotation);
}
protected sealed override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
Debug.Assert(nullableAnnotation != DefaultNullableAnnotation);
return new PublicModel.DynamicTypeSymbol(this, nullableAnnotation);
}
internal override bool IsRecord => false;
internal override bool IsRecordStruct => false;
internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed partial class DynamicTypeSymbol : TypeSymbol
{
internal static readonly DynamicTypeSymbol Instance = new DynamicTypeSymbol();
private DynamicTypeSymbol()
{
}
public override string Name
{
get
{
return "dynamic";
}
}
public override bool IsAbstract
{
get
{
return false;
}
}
public override bool IsReferenceType
{
get
{
return true;
}
}
public override bool IsSealed
{
get
{
return false;
}
}
public override SymbolKind Kind
{
get
{
return SymbolKind.DynamicType;
}
}
public override TypeKind TypeKind
{
get
{
return TypeKind.Dynamic;
}
}
public override ImmutableArray<Location> Locations
{
get
{
return ImmutableArray<Location>.Empty;
}
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return ImmutableArray<SyntaxReference>.Empty;
}
}
internal override NamedTypeSymbol? BaseTypeNoUseSiteDiagnostics => null;
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol>? basesBeingResolved)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override bool IsStatic
{
get
{
return false;
}
}
public override bool IsValueType
{
get
{
return false;
}
}
internal sealed override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => ManagedKind.Managed;
public sealed override bool IsRefLikeType
{
get
{
return false;
}
}
public sealed override bool IsReadOnly
{
get
{
return false;
}
}
internal sealed override ObsoleteAttributeData? ObsoleteAttributeData
{
get { return null; }
}
public override ImmutableArray<Symbol> GetMembers()
{
return ImmutableArray<Symbol>.Empty;
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
return ImmutableArray<Symbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return ImmutableArray<NamedTypeSymbol>.Empty;
}
internal override TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument argument)
{
return visitor.VisitDynamicType(this, argument);
}
public override void Accept(CSharpSymbolVisitor visitor)
{
visitor.VisitDynamicType(this);
}
public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor)
{
return visitor.VisitDynamicType(this);
}
public override Symbol? ContainingSymbol
{
get
{
return null;
}
}
public override Accessibility DeclaredAccessibility
{
get
{
return Accessibility.NotApplicable;
}
}
internal override bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, Symbol owner, ref HashSet<TypeSymbol> checkedTypes)
{
return false;
}
public override int GetHashCode()
{
// return the distinguished value for 'object' because the hash code ignores the distinction
// between dynamic and object. It also ignores custom modifiers.
return (int)Microsoft.CodeAnalysis.SpecialType.System_Object;
}
internal override bool Equals(TypeSymbol? t2, TypeCompareKind comparison)
{
if ((object?)t2 == null)
{
return false;
}
if (ReferenceEquals(this, t2) || t2.TypeKind == TypeKind.Dynamic)
{
return true;
}
if ((comparison & TypeCompareKind.IgnoreDynamic) != 0)
{
var other = t2 as NamedTypeSymbol;
return (object?)other != null && other.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object;
}
return false;
}
internal override void AddNullableTransforms(ArrayBuilder<byte> transforms)
{
}
internal override bool ApplyNullableTransforms(byte defaultTransformFlag, ImmutableArray<byte> transforms, ref int position, out TypeSymbol result)
{
result = this;
return true;
}
internal override TypeSymbol SetNullabilityForReferenceTypes(Func<TypeWithAnnotations, TypeWithAnnotations> transform)
{
return this;
}
internal override TypeSymbol MergeEquivalentTypes(TypeSymbol other, VarianceKind variance)
{
Debug.Assert(this.Equals(other, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes));
return this;
}
protected override ISymbol CreateISymbol()
{
return new PublicModel.DynamicTypeSymbol(this, DefaultNullableAnnotation);
}
protected sealed override ITypeSymbol CreateITypeSymbol(CodeAnalysis.NullableAnnotation nullableAnnotation)
{
Debug.Assert(nullableAnnotation != DefaultNullableAnnotation);
return new PublicModel.DynamicTypeSymbol(this, nullableAnnotation);
}
internal override bool IsRecord => false;
internal override bool IsRecordStruct => false;
internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>();
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncLocalsTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenAsyncLocalsTests : EmitMetadataTestBase
{
private static readonly MetadataReference[] s_asyncRefs = new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 };
public CodeGenAsyncLocalsTests()
{
}
private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null, Verification verify = Verification.Passes)
{
references = (references != null) ? references.Concat(s_asyncRefs) : s_asyncRefs;
return base.CompileAndVerify(source, targetFramework: TargetFramework.Empty, expectedOutput: expectedOutput, references: references, options: options, verify: verify);
}
private string GetFieldLoadsAndStores(CompilationVerifier c, string qualifiedMethodName)
{
var actualLines = c.VisualizeIL(qualifiedMethodName).Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
return string.Join(Environment.NewLine,
from pair in actualLines.Zip(actualLines.Skip(1), (line1, line2) => new { line1, line2 })
where pair.line2.Contains("ldfld") || pair.line2.Contains("stfld")
select pair.line1.Trim() + Environment.NewLine + pair.line2.Trim());
}
[Fact]
public void AsyncWithLocals()
{
var source = @"
using System;
using System.Threading.Tasks;
class Test
{
public static async Task<int> F(int x)
{
return await Task.Factory.StartNew(() => { return x; });
}
public static async Task<int> G(int x)
{
int c = 0;
await F(x);
c += x;
await F(x);
c += x;
return c;
}
public static void Main()
{
Task<int> t = G(21);
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
[WorkItem(13867, "https://github.com/dotnet/roslyn/issues/13867")]
public void AsyncWithLotsLocals()
{
var source = @"
using System;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
DoItAsync().Wait();
}
public static async Task DoItAsync()
{
var var1 = 0;
var var2 = 0;
var var3 = 0;
var var4 = 0;
var var5 = 0;
var var6 = 0;
var var7 = 0;
var var8 = 0;
var var9 = 0;
var var10 = 0;
var var11 = 0;
var var12 = 0;
var var13 = 0;
var var14 = 0;
var var15 = 0;
var var16 = 0;
var var17 = 0;
var var18 = 0;
var var19 = 0;
var var20 = 0;
var var21 = 0;
var var22 = 0;
var var23 = 0;
var var24 = 0;
var var25 = 0;
var var26 = 0;
var var27 = 0;
var var28 = 0;
var var29 = 0;
var var30 = 0;
var var31 = 0;
string s;
if (true)
{
s = ""a"";
await Task.Yield();
}
else
{
s = ""b"";
}
Console.WriteLine(s ?? ""null""); // should be ""a"" always, somehow is ""null""
}
}
}";
var expected = @"
a
";
CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expected);
CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: expected);
}
[Fact]
public void AsyncWithParam()
{
var source = @"
using System;
using System.Threading.Tasks;
class Test
{
public static async Task<int> G(int x)
{
await Task.Factory.StartNew(() => { return x; });
x += 21;
await Task.Factory.StartNew(() => { return x; });
x += 21;
return x;
}
public static void Main()
{
Task<int> t = G(0);
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void AsyncWithParamsAndLocals_Unhoisted()
{
var source = @"
using System;
using System.Threading.Tasks;
class Test
{
public static async Task<int> F(int x)
{
return await Task.Factory.StartNew(() => { return x; });
}
public static async Task<int> G(int x)
{
int c = 0;
c = await F(x);
return c;
}
public static void Main()
{
Task<int> t = G(21);
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
21
";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void HoistedParameters()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
public static Task<int> G() => null;
public static async Task M(int x, int y, int z)
{
x = z;
await G();
y = 1;
}
}";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>t__builder",
"x",
"z",
"y",
"<>u__1",
}, module.GetFieldNames("C.<M>d__1"));
});
CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>t__builder",
"x",
"y",
"z",
"<>u__1",
}, module.GetFieldNames("C.<M>d__1"));
});
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SynthesizedVariables1()
{
var source =
@"
using System;
using System.Threading.Tasks;
class C
{
public static Task<int> H() => null;
public static Task<int> G(int a, int b, int c) => null;
public static int F(int a) => 1;
public async Task M(IDisposable disposable)
{
foreach (var item in new[] { 1, 2, 3 }) { using (disposable) { await H(); } }
foreach (var item in new[] { 1, 2, 3 }) { }
using (disposable) { await H(); }
if (disposable != null) { using (disposable) { await G(F(1), F(2), await G(F(3), F(4), await H())); } }
using (disposable) { await H(); }
if (disposable != null) { using (disposable) { } }
lock (this) { }
}
}";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>t__builder",
"disposable",
"<>4__this",
"<>7__wrap1",
"<>7__wrap2",
"<>7__wrap3",
"<>u__1",
"<>7__wrap4",
"<>7__wrap5",
"<>7__wrap6",
}, module.GetFieldNames("C.<M>d__3"));
});
var vd = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>t__builder",
"disposable",
"<>4__this",
"<>s__1",
"<>s__2",
"<item>5__3",
"<>s__4",
"<>s__5",
"<>s__6",
"<item>5__7",
"<>s__8",
"<>s__9",
"<>s__10",
"<>s__11",
"<>s__12",
"<>s__13",
"<>s__14",
"<>s__15",
"<>s__16",
"<>s__17",
"<>s__18",
"<>s__19",
"<>u__1",
}, module.GetFieldNames("C.<M>d__3"));
});
vd.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""disposable"">
<customDebugInfo>
<forwardIterator name=""<M>d__3"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""4"" offset=""53"" />
<slot kind=""6"" offset=""98"" />
<slot kind=""8"" offset=""98"" />
<slot kind=""0"" offset=""98"" />
<slot kind=""4"" offset=""151"" />
<slot kind=""4"" offset=""220"" />
<slot kind=""28"" offset=""261"" />
<slot kind=""28"" offset=""261"" ordinal=""1"" />
<slot kind=""28"" offset=""261"" ordinal=""2"" />
<slot kind=""28"" offset=""281"" />
<slot kind=""28"" offset=""281"" ordinal=""1"" />
<slot kind=""28"" offset=""281"" ordinal=""2"" />
<slot kind=""4"" offset=""307"" />
<slot kind=""4"" offset=""376"" />
<slot kind=""3"" offset=""410"" />
<slot kind=""2"" offset=""410"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[Fact]
public void CaptureThis()
{
var source = @"
using System.Threading;
using System.Threading.Tasks;
using System;
struct TestCase
{
public async Task<int> Run()
{
return await Goo();
}
public async Task<int> Goo()
{
return await Task.Factory.StartNew(() => 42);
}
}
class Driver
{
static void Main()
{
var t = new TestCase();
var task = t.Run();
task.Wait();
Console.WriteLine(task.Result);
}
}";
var expected = @"
42
";
CompileAndVerify(source, expected);
}
[Fact]
public void CaptureThis2()
{
var source = @"
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System;
struct TestCase
{
public IEnumerable<int> Run()
{
yield return Goo();
}
public int Goo()
{
return 42;
}
}
class Driver
{
static void Main()
{
var t = new TestCase();
foreach (var x in t.Run())
{
Console.WriteLine(x);
}
}
}";
var expected = @"
42
";
CompileAndVerify(source, expected);
}
[Fact]
public void AsyncWithDynamic()
{
var source = @"
using System;
using System.Threading.Tasks;
class Test
{
public static async Task<int> F(dynamic t)
{
return await t;
}
public static void Main()
{
Task<int> t = F(Task.Factory.StartNew(() => { return 42; }));
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
CompileAndVerify(source, expectedOutput: expected, references: new[] { CSharpRef });
}
[Fact]
public void AsyncWithThisRef()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
int x = 42;
public async Task<int> F()
{
int c = this.x;
return await Task.Factory.StartNew(() => c);
}
}
class Test
{
public static void Main()
{
Task<int> t = new C().F();
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
var verifier = CompileAndVerify(source, expectedOutput: expected);
verifier.VerifyIL("C.<F>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 191 (0xbf)
.maxstack 3
.locals init (int V_0,
C V_1,
int V_2,
C.<>c__DisplayClass1_0 V_3, //CS$<>8__locals0
System.Runtime.CompilerServices.TaskAwaiter<int> V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__1.<>1__state""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldfld ""C C.<F>d__1.<>4__this""
IL_000d: stloc.1
.try
{
IL_000e: ldloc.0
IL_000f: brfalse.s IL_006a
IL_0011: newobj ""C.<>c__DisplayClass1_0..ctor()""
IL_0016: stloc.3
IL_0017: ldloc.3
IL_0018: ldloc.1
IL_0019: ldfld ""int C.x""
IL_001e: stfld ""int C.<>c__DisplayClass1_0.c""
IL_0023: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get""
IL_0028: ldloc.3
IL_0029: ldftn ""int C.<>c__DisplayClass1_0.<F>b__0()""
IL_002f: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0034: callvirt ""System.Threading.Tasks.Task<int> System.Threading.Tasks.TaskFactory.StartNew<int>(System.Func<int>)""
IL_0039: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_003e: stloc.s V_4
IL_0040: ldloca.s V_4
IL_0042: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0047: brtrue.s IL_0087
IL_0049: ldarg.0
IL_004a: ldc.i4.0
IL_004b: dup
IL_004c: stloc.0
IL_004d: stfld ""int C.<F>d__1.<>1__state""
IL_0052: ldarg.0
IL_0053: ldloc.s V_4
IL_0055: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__1""
IL_005a: ldarg.0
IL_005b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_0060: ldloca.s V_4
IL_0062: ldarg.0
IL_0063: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__1)""
IL_0068: leave.s IL_00be
IL_006a: ldarg.0
IL_006b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__1""
IL_0070: stloc.s V_4
IL_0072: ldarg.0
IL_0073: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__1""
IL_0078: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_007e: ldarg.0
IL_007f: ldc.i4.m1
IL_0080: dup
IL_0081: stloc.0
IL_0082: stfld ""int C.<F>d__1.<>1__state""
IL_0087: ldloca.s V_4
IL_0089: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_008e: stloc.2
IL_008f: leave.s IL_00aa
}
catch System.Exception
{
IL_0091: stloc.s V_5
IL_0093: ldarg.0
IL_0094: ldc.i4.s -2
IL_0096: stfld ""int C.<F>d__1.<>1__state""
IL_009b: ldarg.0
IL_009c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_00a1: ldloc.s V_5
IL_00a3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00a8: leave.s IL_00be
}
IL_00aa: ldarg.0
IL_00ab: ldc.i4.s -2
IL_00ad: stfld ""int C.<F>d__1.<>1__state""
IL_00b2: ldarg.0
IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_00b8: ldloc.2
IL_00b9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00be: ret
}
");
}
[Fact]
public void AsyncWithThisRef01()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
int x => 14;
public async Task<int> F()
{
int c = this.x;
await Task.Yield();
c += this.x;
await Task.Yield();
c += this.x;
await Task.Yield();
await Task.Yield();
await Task.Yield();
return c;
}
}
class Test
{
public static void Main()
{
Task<int> t = new C().F();
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
var verifier = CompileAndVerify(source, expectedOutput: expected);
verifier.VerifyIL("C.<F>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 612 (0x264)
.maxstack 3
.locals init (int V_0,
C V_1,
int V_2,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_3,
System.Runtime.CompilerServices.YieldAwaitable V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__2.<>1__state""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldfld ""C C.<F>d__2.<>4__this""
IL_000d: stloc.1
.try
{
IL_000e: ldloc.0
IL_000f: switch (
IL_006f,
IL_00e0,
IL_0151,
IL_01af,
IL_020a)
IL_0028: ldarg.0
IL_0029: ldloc.1
IL_002a: call ""int C.x.get""
IL_002f: stfld ""int C.<F>d__2.<c>5__2""
IL_0034: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0039: stloc.s V_4
IL_003b: ldloca.s V_4
IL_003d: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_0042: stloc.3
IL_0043: ldloca.s V_3
IL_0045: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_004a: brtrue.s IL_008b
IL_004c: ldarg.0
IL_004d: ldc.i4.0
IL_004e: dup
IL_004f: stloc.0
IL_0050: stfld ""int C.<F>d__2.<>1__state""
IL_0055: ldarg.0
IL_0056: ldloc.3
IL_0057: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_005c: ldarg.0
IL_005d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_0062: ldloca.s V_3
IL_0064: ldarg.0
IL_0065: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__2>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__2)""
IL_006a: leave IL_0263
IL_006f: ldarg.0
IL_0070: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_0075: stloc.3
IL_0076: ldarg.0
IL_0077: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_007c: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0082: ldarg.0
IL_0083: ldc.i4.m1
IL_0084: dup
IL_0085: stloc.0
IL_0086: stfld ""int C.<F>d__2.<>1__state""
IL_008b: ldloca.s V_3
IL_008d: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_0092: ldarg.0
IL_0093: ldarg.0
IL_0094: ldfld ""int C.<F>d__2.<c>5__2""
IL_0099: ldloc.1
IL_009a: call ""int C.x.get""
IL_009f: add
IL_00a0: stfld ""int C.<F>d__2.<c>5__2""
IL_00a5: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_00aa: stloc.s V_4
IL_00ac: ldloca.s V_4
IL_00ae: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_00b3: stloc.3
IL_00b4: ldloca.s V_3
IL_00b6: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00bb: brtrue.s IL_00fc
IL_00bd: ldarg.0
IL_00be: ldc.i4.1
IL_00bf: dup
IL_00c0: stloc.0
IL_00c1: stfld ""int C.<F>d__2.<>1__state""
IL_00c6: ldarg.0
IL_00c7: ldloc.3
IL_00c8: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_00cd: ldarg.0
IL_00ce: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_00d3: ldloca.s V_3
IL_00d5: ldarg.0
IL_00d6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__2>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__2)""
IL_00db: leave IL_0263
IL_00e0: ldarg.0
IL_00e1: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_00e6: stloc.3
IL_00e7: ldarg.0
IL_00e8: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_00ed: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_00f3: ldarg.0
IL_00f4: ldc.i4.m1
IL_00f5: dup
IL_00f6: stloc.0
IL_00f7: stfld ""int C.<F>d__2.<>1__state""
IL_00fc: ldloca.s V_3
IL_00fe: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_0103: ldarg.0
IL_0104: ldarg.0
IL_0105: ldfld ""int C.<F>d__2.<c>5__2""
IL_010a: ldloc.1
IL_010b: call ""int C.x.get""
IL_0110: add
IL_0111: stfld ""int C.<F>d__2.<c>5__2""
IL_0116: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_011b: stloc.s V_4
IL_011d: ldloca.s V_4
IL_011f: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_0124: stloc.3
IL_0125: ldloca.s V_3
IL_0127: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_012c: brtrue.s IL_016d
IL_012e: ldarg.0
IL_012f: ldc.i4.2
IL_0130: dup
IL_0131: stloc.0
IL_0132: stfld ""int C.<F>d__2.<>1__state""
IL_0137: ldarg.0
IL_0138: ldloc.3
IL_0139: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_013e: ldarg.0
IL_013f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_0144: ldloca.s V_3
IL_0146: ldarg.0
IL_0147: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__2>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__2)""
IL_014c: leave IL_0263
IL_0151: ldarg.0
IL_0152: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_0157: stloc.3
IL_0158: ldarg.0
IL_0159: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_015e: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0164: ldarg.0
IL_0165: ldc.i4.m1
IL_0166: dup
IL_0167: stloc.0
IL_0168: stfld ""int C.<F>d__2.<>1__state""
IL_016d: ldloca.s V_3
IL_016f: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_0174: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0179: stloc.s V_4
IL_017b: ldloca.s V_4
IL_017d: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_0182: stloc.3
IL_0183: ldloca.s V_3
IL_0185: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_018a: brtrue.s IL_01cb
IL_018c: ldarg.0
IL_018d: ldc.i4.3
IL_018e: dup
IL_018f: stloc.0
IL_0190: stfld ""int C.<F>d__2.<>1__state""
IL_0195: ldarg.0
IL_0196: ldloc.3
IL_0197: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_019c: ldarg.0
IL_019d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_01a2: ldloca.s V_3
IL_01a4: ldarg.0
IL_01a5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__2>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__2)""
IL_01aa: leave IL_0263
IL_01af: ldarg.0
IL_01b0: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_01b5: stloc.3
IL_01b6: ldarg.0
IL_01b7: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_01bc: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_01c2: ldarg.0
IL_01c3: ldc.i4.m1
IL_01c4: dup
IL_01c5: stloc.0
IL_01c6: stfld ""int C.<F>d__2.<>1__state""
IL_01cb: ldloca.s V_3
IL_01cd: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_01d2: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_01d7: stloc.s V_4
IL_01d9: ldloca.s V_4
IL_01db: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_01e0: stloc.3
IL_01e1: ldloca.s V_3
IL_01e3: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_01e8: brtrue.s IL_0226
IL_01ea: ldarg.0
IL_01eb: ldc.i4.4
IL_01ec: dup
IL_01ed: stloc.0
IL_01ee: stfld ""int C.<F>d__2.<>1__state""
IL_01f3: ldarg.0
IL_01f4: ldloc.3
IL_01f5: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_01fa: ldarg.0
IL_01fb: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_0200: ldloca.s V_3
IL_0202: ldarg.0
IL_0203: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__2>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__2)""
IL_0208: leave.s IL_0263
IL_020a: ldarg.0
IL_020b: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_0210: stloc.3
IL_0211: ldarg.0
IL_0212: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_0217: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_021d: ldarg.0
IL_021e: ldc.i4.m1
IL_021f: dup
IL_0220: stloc.0
IL_0221: stfld ""int C.<F>d__2.<>1__state""
IL_0226: ldloca.s V_3
IL_0228: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_022d: ldarg.0
IL_022e: ldfld ""int C.<F>d__2.<c>5__2""
IL_0233: stloc.2
IL_0234: leave.s IL_024f
}
catch System.Exception
{
IL_0236: stloc.s V_5
IL_0238: ldarg.0
IL_0239: ldc.i4.s -2
IL_023b: stfld ""int C.<F>d__2.<>1__state""
IL_0240: ldarg.0
IL_0241: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_0246: ldloc.s V_5
IL_0248: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_024d: leave.s IL_0263
}
IL_024f: ldarg.0
IL_0250: ldc.i4.s -2
IL_0252: stfld ""int C.<F>d__2.<>1__state""
IL_0257: ldarg.0
IL_0258: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_025d: ldloc.2
IL_025e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_0263: ret
}
");
}
[Fact]
public void AsyncWithBaseRef()
{
var source = @"
using System;
using System.Threading.Tasks;
class B
{
protected int x = 42;
}
class C : B
{
public async Task<int> F()
{
int c = base.x;
return await Task.Factory.StartNew(() => c);
}
}
class Test
{
public static void Main()
{
Task<int> t = new C().F();
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void ReuseFields_SpillTemps()
{
var source = @"
using System.Threading.Tasks;
class Test
{
static void F1(int x, int y)
{
}
async static Task<int> F2()
{
return await Task.Factory.StartNew(() => 42);
}
public static async void Run()
{
int x = 1;
F1(x, await F2());
int y = 2;
F1(y, await F2());
int z = 3;
F1(z, await F2());
}
public static void Main()
{
Run();
}
}";
var reference = CreateCompilationWithMscorlib45(source, references: new MetadataReference[] { SystemRef_v4_0_30319_17929 }).EmitToImageReference();
var comp = CreateCompilationWithMscorlib45("", new[] { reference }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
var testClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var stateMachineClass = (NamedTypeSymbol)testClass.GetMembers().Single(s => s.Name.StartsWith("<Run>", StringComparison.Ordinal));
IEnumerable<IGrouping<TypeSymbol, FieldSymbol>> spillFieldsByType = stateMachineClass.GetMembers().Where(m => m.Kind == SymbolKind.Field && m.Name.StartsWith("<>7__wrap", StringComparison.Ordinal)).Cast<FieldSymbol>().GroupBy(x => x.Type);
Assert.Equal(1, spillFieldsByType.Count());
Assert.Equal(1, spillFieldsByType.Single(x => TypeSymbol.Equals(x.Key, comp.GetSpecialType(SpecialType.System_Int32), TypeCompareKind.ConsiderEverything2)).Count());
}
[Fact]
public void ReuseFields_Generic()
{
var source = @"
using System.Collections.Generic;
using System.Threading.Tasks;
class Test<U>
{
static IEnumerable<T> GetEnum<T>() => null;
static Task<int> F(int a) => null;
public static async void M<S, T>()
{
foreach (var x in GetEnum<T>()) await F(1);
foreach (var x in GetEnum<S>()) await F(2);
foreach (var x in GetEnum<T>()) await F(3);
foreach (var x in GetEnum<U>()) await F(4);
foreach (var x in GetEnum<U>()) await F(5);
}
}";
var c = CompileAndVerify(source, expectedOutput: null, options: TestOptions.ReleaseDll);
var actual = GetFieldLoadsAndStores(c, "Test<U>.<M>d__2<S, T>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext");
// make sure we are reusing synthesized iterator locals and that the locals are nulled:
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
IL_0000: ldarg.0
IL_0001: ldfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0027: callvirt ""System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator()""
IL_002c: stfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_0037: ldarg.0
IL_0038: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_005b: stloc.0
IL_005c: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0062: ldloc.1
IL_0063: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0068: ldarg.0
IL_0069: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_007b: ldarg.0
IL_007c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0082: ldarg.0
IL_0083: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0091: stloc.0
IL_0092: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_009f: ldarg.0
IL_00a0: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_00b2: ldarg.0
IL_00b3: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_00ba: ldarg.0
IL_00bb: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_00c7: ldnull
IL_00c8: stfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_00d3: callvirt ""System.Collections.Generic.IEnumerator<S> System.Collections.Generic.IEnumerable<S>.GetEnumerator()""
IL_00d8: stfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_00e4: ldarg.0
IL_00e5: ldfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_0108: stloc.0
IL_0109: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_010f: ldloc.1
IL_0110: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0115: ldarg.0
IL_0116: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_0128: ldarg.0
IL_0129: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_012f: ldarg.0
IL_0130: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_013e: stloc.0
IL_013f: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_014c: ldarg.0
IL_014d: ldfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_015f: ldarg.0
IL_0160: ldfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_0167: ldarg.0
IL_0168: ldfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_0174: ldnull
IL_0175: stfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_0180: callvirt ""System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator()""
IL_0185: stfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_0191: ldarg.0
IL_0192: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_01b5: stloc.0
IL_01b6: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_01bc: ldloc.1
IL_01bd: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_01c2: ldarg.0
IL_01c3: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_01d5: ldarg.0
IL_01d6: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_01dc: ldarg.0
IL_01dd: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_01eb: stloc.0
IL_01ec: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_01f9: ldarg.0
IL_01fa: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_020c: ldarg.0
IL_020d: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_0214: ldarg.0
IL_0215: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_0221: ldnull
IL_0222: stfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_022d: callvirt ""System.Collections.Generic.IEnumerator<U> System.Collections.Generic.IEnumerable<U>.GetEnumerator()""
IL_0232: stfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_023e: ldarg.0
IL_023f: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_0262: stloc.0
IL_0263: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0269: ldloc.1
IL_026a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_026f: ldarg.0
IL_0270: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_0282: ldarg.0
IL_0283: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0289: ldarg.0
IL_028a: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0298: stloc.0
IL_0299: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_02a6: ldarg.0
IL_02a7: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_02b9: ldarg.0
IL_02ba: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_02c1: ldarg.0
IL_02c2: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_02ce: ldnull
IL_02cf: stfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_02da: callvirt ""System.Collections.Generic.IEnumerator<U> System.Collections.Generic.IEnumerable<U>.GetEnumerator()""
IL_02df: stfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_02eb: ldarg.0
IL_02ec: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_030f: stloc.0
IL_0310: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0316: ldloc.1
IL_0317: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_031c: ldarg.0
IL_031d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_032c: ldarg.0
IL_032d: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0333: ldarg.0
IL_0334: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0342: stloc.0
IL_0343: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0350: ldarg.0
IL_0351: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_0363: ldarg.0
IL_0364: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_036b: ldarg.0
IL_036c: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_0378: ldnull
IL_0379: stfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_0382: ldc.i4.s -2
IL_0384: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0389: ldarg.0
IL_038a: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_0398: ldc.i4.s -2
IL_039a: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_039f: ldarg.0
IL_03a0: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
", actual);
}
[Fact]
public void ReuseFields_Dynamic()
{
var source = @"
using System.Collections.Generic;
using System.Threading.Tasks;
class Test
{
static IEnumerable<dynamic> GetDynamicEnum() => null;
static IEnumerable<object> GetObjectEnum() => null;
static Task<int> F(int a) => null;
public static async void M()
{
foreach (var x in GetDynamicEnum()) await F(1);
foreach (var x in GetObjectEnum()) await F(2);
}
}";
var c = CompileAndVerify(source, expectedOutput: null, options: TestOptions.ReleaseDll);
var actual = GetFieldLoadsAndStores(c, "Test.<M>d__3.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext");
// make sure we are reusing synthesized iterator locals and that the locals are nulled:
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
IL_0000: ldarg.0
IL_0001: ldfld ""int Test.<M>d__3.<>1__state""
IL_0017: callvirt ""System.Collections.Generic.IEnumerator<dynamic> System.Collections.Generic.IEnumerable<dynamic>.GetEnumerator()""
IL_001c: stfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_0027: ldarg.0
IL_0028: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_004b: stloc.0
IL_004c: stfld ""int Test.<M>d__3.<>1__state""
IL_0052: ldloc.1
IL_0053: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_0058: ldarg.0
IL_0059: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<M>d__3.<>t__builder""
IL_006b: ldarg.0
IL_006c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_0072: ldarg.0
IL_0073: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_0081: stloc.0
IL_0082: stfld ""int Test.<M>d__3.<>1__state""
IL_008f: ldarg.0
IL_0090: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00a2: ldarg.0
IL_00a3: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00aa: ldarg.0
IL_00ab: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00b7: ldnull
IL_00b8: stfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00c3: callvirt ""System.Collections.Generic.IEnumerator<object> System.Collections.Generic.IEnumerable<object>.GetEnumerator()""
IL_00c8: stfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00d4: ldarg.0
IL_00d5: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00f8: stloc.0
IL_00f9: stfld ""int Test.<M>d__3.<>1__state""
IL_00ff: ldloc.1
IL_0100: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_0105: ldarg.0
IL_0106: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<M>d__3.<>t__builder""
IL_0115: ldarg.0
IL_0116: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_011c: ldarg.0
IL_011d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_012b: stloc.0
IL_012c: stfld ""int Test.<M>d__3.<>1__state""
IL_0139: ldarg.0
IL_013a: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_014c: ldarg.0
IL_014d: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_0154: ldarg.0
IL_0155: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_0161: ldnull
IL_0162: stfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_016b: ldc.i4.s -2
IL_016d: stfld ""int Test.<M>d__3.<>1__state""
IL_0172: ldarg.0
IL_0173: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<M>d__3.<>t__builder""
IL_0181: ldc.i4.s -2
IL_0183: stfld ""int Test.<M>d__3.<>1__state""
IL_0188: ldarg.0
IL_0189: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<M>d__3.<>t__builder""
", actual);
}
[Fact]
public void ManySynthesizedNames()
{
string source = @"
using System;
using System.Threading.Tasks;
public class C
{
public async Task F()
{
var a1 = await Task.FromResult(default(Tuple<char, char, char>));
var a2 = await Task.FromResult(default(Tuple<char, char, byte>));
var a3 = await Task.FromResult(default(Tuple<char, byte, char>));
var a4 = await Task.FromResult(default(Tuple<char, byte, byte>));
var a5 = await Task.FromResult(default(Tuple<byte, char, char>));
var a6 = await Task.FromResult(default(Tuple<byte, char, byte>));
var a7 = await Task.FromResult(default(Tuple<byte, byte, char>));
var a8 = await Task.FromResult(default(Tuple<byte, byte, byte>));
var b1 = await Task.FromResult(default(Tuple<int, int, int>));
var b2 = await Task.FromResult(default(Tuple<int, int, long>));
var b3 = await Task.FromResult(default(Tuple<int, long, int>));
var b4 = await Task.FromResult(default(Tuple<int, long, long>));
var b5 = await Task.FromResult(default(Tuple<long, int, int>));
var b6 = await Task.FromResult(default(Tuple<long, int, long>));
var b7 = await Task.FromResult(default(Tuple<long, long, int>));
var b8 = await Task.FromResult(default(Tuple<long, long, long>));
}
}";
CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: s_asyncRefs, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<>u__1",
"<>u__2",
"<>u__3",
"<>u__4",
"<>u__5",
"<>u__6",
"<>u__7",
"<>u__8",
"<>u__9",
"<>u__10",
"<>u__11",
"<>u__12",
"<>u__13",
"<>u__14",
"<>u__15",
"<>u__16",
}, module.GetFieldNames("C.<F>d__0"));
});
}
[WorkItem(9775, "https://github.com/dotnet/roslyn/issues/9775")]
[Fact]
public void Fixed_Debug()
{
var text =
@"using System;
using System.Threading.Tasks;
class C
{
static async Task<int> F(byte[] b)
{
int i;
unsafe
{
fixed (byte* p = b)
{
i = *p;
}
}
await Task.Yield();
return i;
}
static void Main()
{
var i = F(new byte[] { 1, 2, 3 }).Result;
Console.Write(i);
}
}";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"1", verify: Verification.Fails);
verifier.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 198 (0xc6)
.maxstack 3
.locals init (int V_0,
int V_1,
byte* V_2, //p
pinned byte[] V_3,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_4,
System.Runtime.CompilerServices.YieldAwaitable V_5,
System.Exception V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_006b
IL_000a: ldarg.0
IL_000b: ldfld ""byte[] C.<F>d__0.b""
IL_0010: dup
IL_0011: stloc.3
IL_0012: brfalse.s IL_0019
IL_0014: ldloc.3
IL_0015: ldlen
IL_0016: conv.i4
IL_0017: brtrue.s IL_001e
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.2
IL_001c: br.s IL_0027
IL_001e: ldloc.3
IL_001f: ldc.i4.0
IL_0020: ldelema ""byte""
IL_0025: conv.u
IL_0026: stloc.2
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: ldind.u1
IL_002a: stfld ""int C.<F>d__0.<i>5__2""
IL_002f: ldnull
IL_0030: stloc.3
IL_0031: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0036: stloc.s V_5
IL_0038: ldloca.s V_5
IL_003a: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_003f: stloc.s V_4
IL_0041: ldloca.s V_4
IL_0043: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0048: brtrue.s IL_0088
IL_004a: ldarg.0
IL_004b: ldc.i4.0
IL_004c: dup
IL_004d: stloc.0
IL_004e: stfld ""int C.<F>d__0.<>1__state""
IL_0053: ldarg.0
IL_0054: ldloc.s V_4
IL_0056: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_005b: ldarg.0
IL_005c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0061: ldloca.s V_4
IL_0063: ldarg.0
IL_0064: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__0)""
IL_0069: leave.s IL_00c5
IL_006b: ldarg.0
IL_006c: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_0071: stloc.s V_4
IL_0073: ldarg.0
IL_0074: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_0079: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_007f: ldarg.0
IL_0080: ldc.i4.m1
IL_0081: dup
IL_0082: stloc.0
IL_0083: stfld ""int C.<F>d__0.<>1__state""
IL_0088: ldloca.s V_4
IL_008a: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_008f: ldarg.0
IL_0090: ldfld ""int C.<F>d__0.<i>5__2""
IL_0095: stloc.1
IL_0096: leave.s IL_00b1
}
catch System.Exception
{
IL_0098: stloc.s V_6
IL_009a: ldarg.0
IL_009b: ldc.i4.s -2
IL_009d: stfld ""int C.<F>d__0.<>1__state""
IL_00a2: ldarg.0
IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00a8: ldloc.s V_6
IL_00aa: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00af: leave.s IL_00c5
}
IL_00b1: ldarg.0
IL_00b2: ldc.i4.s -2
IL_00b4: stfld ""int C.<F>d__0.<>1__state""
IL_00b9: ldarg.0
IL_00ba: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00bf: ldloc.1
IL_00c0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00c5: ret
}");
verifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"1", verify: Verification.Fails);
verifier.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 227 (0xe3)
.maxstack 3
.locals init (int V_0,
int V_1,
pinned byte[] V_2,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_3,
System.Runtime.CompilerServices.YieldAwaitable V_4,
C.<F>d__0 V_5,
System.Exception V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0086
IL_000e: nop
IL_000f: nop
IL_0010: ldarg.0
IL_0011: ldfld ""byte[] C.<F>d__0.b""
IL_0016: dup
IL_0017: stloc.2
IL_0018: brfalse.s IL_001f
IL_001a: ldloc.2
IL_001b: ldlen
IL_001c: conv.i4
IL_001d: brtrue.s IL_0029
IL_001f: ldarg.0
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stfld ""byte* C.<F>d__0.<p>5__2""
IL_0027: br.s IL_0037
IL_0029: ldarg.0
IL_002a: ldloc.2
IL_002b: ldc.i4.0
IL_002c: ldelema ""byte""
IL_0031: conv.u
IL_0032: stfld ""byte* C.<F>d__0.<p>5__2""
IL_0037: nop
IL_0038: ldarg.0
IL_0039: ldarg.0
IL_003a: ldfld ""byte* C.<F>d__0.<p>5__2""
IL_003f: ldind.u1
IL_0040: stfld ""int C.<F>d__0.<i>5__1""
IL_0045: nop
IL_0046: ldnull
IL_0047: stloc.2
IL_0048: nop
IL_0049: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_004e: stloc.s V_4
IL_0050: ldloca.s V_4
IL_0052: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_0057: stloc.3
IL_0058: ldloca.s V_3
IL_005a: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_005f: brtrue.s IL_00a2
IL_0061: ldarg.0
IL_0062: ldc.i4.0
IL_0063: dup
IL_0064: stloc.0
IL_0065: stfld ""int C.<F>d__0.<>1__state""
IL_006a: ldarg.0
IL_006b: ldloc.3
IL_006c: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_0071: ldarg.0
IL_0072: stloc.s V_5
IL_0074: ldarg.0
IL_0075: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_007a: ldloca.s V_3
IL_007c: ldloca.s V_5
IL_007e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__0)""
IL_0083: nop
IL_0084: leave.s IL_00e2
IL_0086: ldarg.0
IL_0087: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_008c: stloc.3
IL_008d: ldarg.0
IL_008e: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_0093: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0099: ldarg.0
IL_009a: ldc.i4.m1
IL_009b: dup
IL_009c: stloc.0
IL_009d: stfld ""int C.<F>d__0.<>1__state""
IL_00a2: ldloca.s V_3
IL_00a4: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_00a9: nop
IL_00aa: ldarg.0
IL_00ab: ldfld ""int C.<F>d__0.<i>5__1""
IL_00b0: stloc.1
IL_00b1: leave.s IL_00cd
}
catch System.Exception
{
IL_00b3: stloc.s V_6
IL_00b5: ldarg.0
IL_00b6: ldc.i4.s -2
IL_00b8: stfld ""int C.<F>d__0.<>1__state""
IL_00bd: ldarg.0
IL_00be: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00c3: ldloc.s V_6
IL_00c5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00ca: nop
IL_00cb: leave.s IL_00e2
}
IL_00cd: ldarg.0
IL_00ce: ldc.i4.s -2
IL_00d0: stfld ""int C.<F>d__0.<>1__state""
IL_00d5: ldarg.0
IL_00d6: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00db: ldloc.1
IL_00dc: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00e1: nop
IL_00e2: ret
}");
}
[WorkItem(15290, "https://github.com/dotnet/roslyn/issues/15290")]
[Fact]
public void ReuseLocals()
{
var text =
@"
using System;
using System.Threading.Tasks;
class Test
{
public static void Main(string[] args) => MainAsync(args).GetAwaiter().GetResult();
private static async Task MainAsync(string[] args)
{
if (args.Length > 0)
{
int a = 1;
await Task.Yield();
Console.WriteLine(a);
}
else
{
int b = 2;
await Task.Yield();
Console.WriteLine(b);
}
}
}";
var verifier = CompileAndVerify(text, options: TestOptions.ReleaseExe, expectedOutput: @"2");
// NOTE: only one hoisted int local:
// int Test.<MainAsync>d__1.<a>5__2
verifier.VerifyIL("Test.<MainAsync>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 292 (0x124)
.maxstack 3
.locals init (int V_0,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_1,
System.Runtime.CompilerServices.YieldAwaitable V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_005b
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq IL_00c9
IL_0011: ldarg.0
IL_0012: ldfld ""string[] Test.<MainAsync>d__1.args""
IL_0017: ldlen
IL_0018: brfalse.s IL_008b
IL_001a: ldarg.0
IL_001b: ldc.i4.1
IL_001c: stfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0021: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0026: stloc.2
IL_0027: ldloca.s V_2
IL_0029: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_002e: stloc.1
IL_002f: ldloca.s V_1
IL_0031: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0036: brtrue.s IL_0077
IL_0038: ldarg.0
IL_0039: ldc.i4.0
IL_003a: dup
IL_003b: stloc.0
IL_003c: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0041: ldarg.0
IL_0042: ldloc.1
IL_0043: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0048: ldarg.0
IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_004e: ldloca.s V_1
IL_0050: ldarg.0
IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_0056: leave IL_0123
IL_005b: ldarg.0
IL_005c: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0061: stloc.1
IL_0062: ldarg.0
IL_0063: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0068: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_006e: ldarg.0
IL_006f: ldc.i4.m1
IL_0070: dup
IL_0071: stloc.0
IL_0072: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0077: ldloca.s V_1
IL_0079: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_007e: ldarg.0
IL_007f: ldfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0084: call ""void System.Console.WriteLine(int)""
IL_0089: br.s IL_00f7
IL_008b: ldarg.0
IL_008c: ldc.i4.2
IL_008d: stfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0092: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0097: stloc.2
IL_0098: ldloca.s V_2
IL_009a: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_009f: stloc.1
IL_00a0: ldloca.s V_1
IL_00a2: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00a7: brtrue.s IL_00e5
IL_00a9: ldarg.0
IL_00aa: ldc.i4.1
IL_00ab: dup
IL_00ac: stloc.0
IL_00ad: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00b2: ldarg.0
IL_00b3: ldloc.1
IL_00b4: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00b9: ldarg.0
IL_00ba: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_00bf: ldloca.s V_1
IL_00c1: ldarg.0
IL_00c2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_00c7: leave.s IL_0123
IL_00c9: ldarg.0
IL_00ca: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00cf: stloc.1
IL_00d0: ldarg.0
IL_00d1: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00d6: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_00dc: ldarg.0
IL_00dd: ldc.i4.m1
IL_00de: dup
IL_00df: stloc.0
IL_00e0: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00e5: ldloca.s V_1
IL_00e7: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_00ec: ldarg.0
IL_00ed: ldfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_00f2: call ""void System.Console.WriteLine(int)""
IL_00f7: leave.s IL_0110
}
catch System.Exception
{
IL_00f9: stloc.3
IL_00fa: ldarg.0
IL_00fb: ldc.i4.s -2
IL_00fd: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0102: ldarg.0
IL_0103: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0108: ldloc.3
IL_0109: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_010e: leave.s IL_0123
}
IL_0110: ldarg.0
IL_0111: ldc.i4.s -2
IL_0113: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0118: ldarg.0
IL_0119: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_011e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0123: ret
}");
verifier = CompileAndVerify(text, options: TestOptions.DebugExe, expectedOutput: @"2");
// NOTE: two separate hoisted int locals:
// int Test.<MainAsync>d__1.<a>5__1 and
// int Test.<MainAsync>d__1.<b>5__2
verifier.VerifyIL("Test.<MainAsync>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 331 (0x14b)
.maxstack 3
.locals init (int V_0,
bool V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
Test.<MainAsync>d__1 V_4,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_5,
System.Exception V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0019
IL_0012: br.s IL_006f
IL_0014: br IL_00e8
IL_0019: nop
IL_001a: ldarg.0
IL_001b: ldfld ""string[] Test.<MainAsync>d__1.args""
IL_0020: ldlen
IL_0021: ldc.i4.0
IL_0022: cgt.un
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: brfalse.s IL_00a2
IL_0028: nop
IL_0029: ldarg.0
IL_002a: ldc.i4.1
IL_002b: stfld ""int Test.<MainAsync>d__1.<a>5__1""
IL_0030: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0035: stloc.3
IL_0036: ldloca.s V_3
IL_0038: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_003d: stloc.2
IL_003e: ldloca.s V_2
IL_0040: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0045: brtrue.s IL_008b
IL_0047: ldarg.0
IL_0048: ldc.i4.0
IL_0049: dup
IL_004a: stloc.0
IL_004b: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0050: ldarg.0
IL_0051: ldloc.2
IL_0052: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0057: ldarg.0
IL_0058: stloc.s V_4
IL_005a: ldarg.0
IL_005b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0060: ldloca.s V_2
IL_0062: ldloca.s V_4
IL_0064: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_0069: nop
IL_006a: leave IL_014a
IL_006f: ldarg.0
IL_0070: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0075: stloc.2
IL_0076: ldarg.0
IL_0077: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_007c: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0082: ldarg.0
IL_0083: ldc.i4.m1
IL_0084: dup
IL_0085: stloc.0
IL_0086: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_008b: ldloca.s V_2
IL_008d: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_0092: nop
IL_0093: ldarg.0
IL_0094: ldfld ""int Test.<MainAsync>d__1.<a>5__1""
IL_0099: call ""void System.Console.WriteLine(int)""
IL_009e: nop
IL_009f: nop
IL_00a0: br.s IL_011a
IL_00a2: nop
IL_00a3: ldarg.0
IL_00a4: ldc.i4.2
IL_00a5: stfld ""int Test.<MainAsync>d__1.<b>5__2""
IL_00aa: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_00af: stloc.3
IL_00b0: ldloca.s V_3
IL_00b2: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_00b7: stloc.s V_5
IL_00b9: ldloca.s V_5
IL_00bb: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00c0: brtrue.s IL_0105
IL_00c2: ldarg.0
IL_00c3: ldc.i4.1
IL_00c4: dup
IL_00c5: stloc.0
IL_00c6: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00cb: ldarg.0
IL_00cc: ldloc.s V_5
IL_00ce: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00d3: ldarg.0
IL_00d4: stloc.s V_4
IL_00d6: ldarg.0
IL_00d7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_00dc: ldloca.s V_5
IL_00de: ldloca.s V_4
IL_00e0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_00e5: nop
IL_00e6: leave.s IL_014a
IL_00e8: ldarg.0
IL_00e9: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00ee: stloc.s V_5
IL_00f0: ldarg.0
IL_00f1: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00f6: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_00fc: ldarg.0
IL_00fd: ldc.i4.m1
IL_00fe: dup
IL_00ff: stloc.0
IL_0100: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0105: ldloca.s V_5
IL_0107: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_010c: nop
IL_010d: ldarg.0
IL_010e: ldfld ""int Test.<MainAsync>d__1.<b>5__2""
IL_0113: call ""void System.Console.WriteLine(int)""
IL_0118: nop
IL_0119: nop
IL_011a: leave.s IL_0136
}
catch System.Exception
{
IL_011c: stloc.s V_6
IL_011e: ldarg.0
IL_011f: ldc.i4.s -2
IL_0121: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0126: ldarg.0
IL_0127: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_012c: ldloc.s V_6
IL_012e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0133: nop
IL_0134: leave.s IL_014a
}
IL_0136: ldarg.0
IL_0137: ldc.i4.s -2
IL_0139: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_013e: ldarg.0
IL_013f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0144: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0149: nop
IL_014a: ret
}");
}
[WorkItem(15290, "https://github.com/dotnet/roslyn/issues/15290")]
[Fact]
public void ReuseLocalsSynthetic()
{
var text =
@"
using System;
using System.Threading.Tasks;
class Test
{
public static void Main(string[] args) => MainAsync(args).GetAwaiter().GetResult();
private static async Task MainAsync(string[] args)
{
if (args.Length > 0)
{
int a = 1;
await Task.Yield();
Console.WriteLine(a);
}
else
{
int b = 2;
await Task.Yield();
Console.WriteLine(b);
}
}
}";
var verifier = CompileAndVerify(text, options: TestOptions.ReleaseExe, expectedOutput: @"2");
// NOTE: only one hoisted int local:
// int Test.<MainAsync>d__1.<a>5__2
verifier.VerifyIL("Test.<MainAsync>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 292 (0x124)
.maxstack 3
.locals init (int V_0,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_1,
System.Runtime.CompilerServices.YieldAwaitable V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_005b
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq IL_00c9
IL_0011: ldarg.0
IL_0012: ldfld ""string[] Test.<MainAsync>d__1.args""
IL_0017: ldlen
IL_0018: brfalse.s IL_008b
IL_001a: ldarg.0
IL_001b: ldc.i4.1
IL_001c: stfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0021: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0026: stloc.2
IL_0027: ldloca.s V_2
IL_0029: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_002e: stloc.1
IL_002f: ldloca.s V_1
IL_0031: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0036: brtrue.s IL_0077
IL_0038: ldarg.0
IL_0039: ldc.i4.0
IL_003a: dup
IL_003b: stloc.0
IL_003c: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0041: ldarg.0
IL_0042: ldloc.1
IL_0043: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0048: ldarg.0
IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_004e: ldloca.s V_1
IL_0050: ldarg.0
IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_0056: leave IL_0123
IL_005b: ldarg.0
IL_005c: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0061: stloc.1
IL_0062: ldarg.0
IL_0063: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0068: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_006e: ldarg.0
IL_006f: ldc.i4.m1
IL_0070: dup
IL_0071: stloc.0
IL_0072: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0077: ldloca.s V_1
IL_0079: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_007e: ldarg.0
IL_007f: ldfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0084: call ""void System.Console.WriteLine(int)""
IL_0089: br.s IL_00f7
IL_008b: ldarg.0
IL_008c: ldc.i4.2
IL_008d: stfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0092: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0097: stloc.2
IL_0098: ldloca.s V_2
IL_009a: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_009f: stloc.1
IL_00a0: ldloca.s V_1
IL_00a2: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00a7: brtrue.s IL_00e5
IL_00a9: ldarg.0
IL_00aa: ldc.i4.1
IL_00ab: dup
IL_00ac: stloc.0
IL_00ad: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00b2: ldarg.0
IL_00b3: ldloc.1
IL_00b4: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00b9: ldarg.0
IL_00ba: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_00bf: ldloca.s V_1
IL_00c1: ldarg.0
IL_00c2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_00c7: leave.s IL_0123
IL_00c9: ldarg.0
IL_00ca: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00cf: stloc.1
IL_00d0: ldarg.0
IL_00d1: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00d6: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_00dc: ldarg.0
IL_00dd: ldc.i4.m1
IL_00de: dup
IL_00df: stloc.0
IL_00e0: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00e5: ldloca.s V_1
IL_00e7: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_00ec: ldarg.0
IL_00ed: ldfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_00f2: call ""void System.Console.WriteLine(int)""
IL_00f7: leave.s IL_0110
}
catch System.Exception
{
IL_00f9: stloc.3
IL_00fa: ldarg.0
IL_00fb: ldc.i4.s -2
IL_00fd: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0102: ldarg.0
IL_0103: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0108: ldloc.3
IL_0109: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_010e: leave.s IL_0123
}
IL_0110: ldarg.0
IL_0111: ldc.i4.s -2
IL_0113: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0118: ldarg.0
IL_0119: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_011e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0123: ret
}");
verifier = CompileAndVerify(text, options: TestOptions.DebugExe, expectedOutput: @"2");
// NOTE: two separate hoisted int locals:
// int Test.<MainAsync>d__1.<a>5__1 and
// int Test.<MainAsync>d__1.<b>5__2
verifier.VerifyIL("Test.<MainAsync>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 331 (0x14b)
.maxstack 3
.locals init (int V_0,
bool V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
Test.<MainAsync>d__1 V_4,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_5,
System.Exception V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0019
IL_0012: br.s IL_006f
IL_0014: br IL_00e8
IL_0019: nop
IL_001a: ldarg.0
IL_001b: ldfld ""string[] Test.<MainAsync>d__1.args""
IL_0020: ldlen
IL_0021: ldc.i4.0
IL_0022: cgt.un
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: brfalse.s IL_00a2
IL_0028: nop
IL_0029: ldarg.0
IL_002a: ldc.i4.1
IL_002b: stfld ""int Test.<MainAsync>d__1.<a>5__1""
IL_0030: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0035: stloc.3
IL_0036: ldloca.s V_3
IL_0038: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_003d: stloc.2
IL_003e: ldloca.s V_2
IL_0040: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0045: brtrue.s IL_008b
IL_0047: ldarg.0
IL_0048: ldc.i4.0
IL_0049: dup
IL_004a: stloc.0
IL_004b: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0050: ldarg.0
IL_0051: ldloc.2
IL_0052: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0057: ldarg.0
IL_0058: stloc.s V_4
IL_005a: ldarg.0
IL_005b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0060: ldloca.s V_2
IL_0062: ldloca.s V_4
IL_0064: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_0069: nop
IL_006a: leave IL_014a
IL_006f: ldarg.0
IL_0070: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0075: stloc.2
IL_0076: ldarg.0
IL_0077: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_007c: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0082: ldarg.0
IL_0083: ldc.i4.m1
IL_0084: dup
IL_0085: stloc.0
IL_0086: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_008b: ldloca.s V_2
IL_008d: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_0092: nop
IL_0093: ldarg.0
IL_0094: ldfld ""int Test.<MainAsync>d__1.<a>5__1""
IL_0099: call ""void System.Console.WriteLine(int)""
IL_009e: nop
IL_009f: nop
IL_00a0: br.s IL_011a
IL_00a2: nop
IL_00a3: ldarg.0
IL_00a4: ldc.i4.2
IL_00a5: stfld ""int Test.<MainAsync>d__1.<b>5__2""
IL_00aa: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_00af: stloc.3
IL_00b0: ldloca.s V_3
IL_00b2: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_00b7: stloc.s V_5
IL_00b9: ldloca.s V_5
IL_00bb: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00c0: brtrue.s IL_0105
IL_00c2: ldarg.0
IL_00c3: ldc.i4.1
IL_00c4: dup
IL_00c5: stloc.0
IL_00c6: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00cb: ldarg.0
IL_00cc: ldloc.s V_5
IL_00ce: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00d3: ldarg.0
IL_00d4: stloc.s V_4
IL_00d6: ldarg.0
IL_00d7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_00dc: ldloca.s V_5
IL_00de: ldloca.s V_4
IL_00e0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_00e5: nop
IL_00e6: leave.s IL_014a
IL_00e8: ldarg.0
IL_00e9: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00ee: stloc.s V_5
IL_00f0: ldarg.0
IL_00f1: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00f6: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_00fc: ldarg.0
IL_00fd: ldc.i4.m1
IL_00fe: dup
IL_00ff: stloc.0
IL_0100: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0105: ldloca.s V_5
IL_0107: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_010c: nop
IL_010d: ldarg.0
IL_010e: ldfld ""int Test.<MainAsync>d__1.<b>5__2""
IL_0113: call ""void System.Console.WriteLine(int)""
IL_0118: nop
IL_0119: nop
IL_011a: leave.s IL_0136
}
catch System.Exception
{
IL_011c: stloc.s V_6
IL_011e: ldarg.0
IL_011f: ldc.i4.s -2
IL_0121: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0126: ldarg.0
IL_0127: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_012c: ldloc.s V_6
IL_012e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0133: nop
IL_0134: leave.s IL_014a
}
IL_0136: ldarg.0
IL_0137: ldc.i4.s -2
IL_0139: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_013e: ldarg.0
IL_013f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0144: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0149: nop
IL_014a: ret
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenAsyncLocalsTests : EmitMetadataTestBase
{
private static readonly MetadataReference[] s_asyncRefs = new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 };
public CodeGenAsyncLocalsTests()
{
}
private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null, Verification verify = Verification.Passes)
{
references = (references != null) ? references.Concat(s_asyncRefs) : s_asyncRefs;
return base.CompileAndVerify(source, targetFramework: TargetFramework.Empty, expectedOutput: expectedOutput, references: references, options: options, verify: verify);
}
private string GetFieldLoadsAndStores(CompilationVerifier c, string qualifiedMethodName)
{
var actualLines = c.VisualizeIL(qualifiedMethodName).Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
return string.Join(Environment.NewLine,
from pair in actualLines.Zip(actualLines.Skip(1), (line1, line2) => new { line1, line2 })
where pair.line2.Contains("ldfld") || pair.line2.Contains("stfld")
select pair.line1.Trim() + Environment.NewLine + pair.line2.Trim());
}
[Fact]
public void AsyncWithLocals()
{
var source = @"
using System;
using System.Threading.Tasks;
class Test
{
public static async Task<int> F(int x)
{
return await Task.Factory.StartNew(() => { return x; });
}
public static async Task<int> G(int x)
{
int c = 0;
await F(x);
c += x;
await F(x);
c += x;
return c;
}
public static void Main()
{
Task<int> t = G(21);
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
[WorkItem(13867, "https://github.com/dotnet/roslyn/issues/13867")]
public void AsyncWithLotsLocals()
{
var source = @"
using System;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
DoItAsync().Wait();
}
public static async Task DoItAsync()
{
var var1 = 0;
var var2 = 0;
var var3 = 0;
var var4 = 0;
var var5 = 0;
var var6 = 0;
var var7 = 0;
var var8 = 0;
var var9 = 0;
var var10 = 0;
var var11 = 0;
var var12 = 0;
var var13 = 0;
var var14 = 0;
var var15 = 0;
var var16 = 0;
var var17 = 0;
var var18 = 0;
var var19 = 0;
var var20 = 0;
var var21 = 0;
var var22 = 0;
var var23 = 0;
var var24 = 0;
var var25 = 0;
var var26 = 0;
var var27 = 0;
var var28 = 0;
var var29 = 0;
var var30 = 0;
var var31 = 0;
string s;
if (true)
{
s = ""a"";
await Task.Yield();
}
else
{
s = ""b"";
}
Console.WriteLine(s ?? ""null""); // should be ""a"" always, somehow is ""null""
}
}
}";
var expected = @"
a
";
CompileAndVerify(source, options: TestOptions.ReleaseExe, expectedOutput: expected);
CompileAndVerify(source, options: TestOptions.DebugExe, expectedOutput: expected);
}
[Fact]
public void AsyncWithParam()
{
var source = @"
using System;
using System.Threading.Tasks;
class Test
{
public static async Task<int> G(int x)
{
await Task.Factory.StartNew(() => { return x; });
x += 21;
await Task.Factory.StartNew(() => { return x; });
x += 21;
return x;
}
public static void Main()
{
Task<int> t = G(0);
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void AsyncWithParamsAndLocals_Unhoisted()
{
var source = @"
using System;
using System.Threading.Tasks;
class Test
{
public static async Task<int> F(int x)
{
return await Task.Factory.StartNew(() => { return x; });
}
public static async Task<int> G(int x)
{
int c = 0;
c = await F(x);
return c;
}
public static void Main()
{
Task<int> t = G(21);
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
21
";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void HoistedParameters()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
public static Task<int> G() => null;
public static async Task M(int x, int y, int z)
{
x = z;
await G();
y = 1;
}
}";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>t__builder",
"x",
"z",
"y",
"<>u__1",
}, module.GetFieldNames("C.<M>d__1"));
});
CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>t__builder",
"x",
"y",
"z",
"<>u__1",
}, module.GetFieldNames("C.<M>d__1"));
});
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void SynthesizedVariables1()
{
var source =
@"
using System;
using System.Threading.Tasks;
class C
{
public static Task<int> H() => null;
public static Task<int> G(int a, int b, int c) => null;
public static int F(int a) => 1;
public async Task M(IDisposable disposable)
{
foreach (var item in new[] { 1, 2, 3 }) { using (disposable) { await H(); } }
foreach (var item in new[] { 1, 2, 3 }) { }
using (disposable) { await H(); }
if (disposable != null) { using (disposable) { await G(F(1), F(2), await G(F(3), F(4), await H())); } }
using (disposable) { await H(); }
if (disposable != null) { using (disposable) { } }
lock (this) { }
}
}";
CompileAndVerify(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>t__builder",
"disposable",
"<>4__this",
"<>7__wrap1",
"<>7__wrap2",
"<>7__wrap3",
"<>u__1",
"<>7__wrap4",
"<>7__wrap5",
"<>7__wrap6",
}, module.GetFieldNames("C.<M>d__3"));
});
var vd = CompileAndVerify(source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>t__builder",
"disposable",
"<>4__this",
"<>s__1",
"<>s__2",
"<item>5__3",
"<>s__4",
"<>s__5",
"<>s__6",
"<item>5__7",
"<>s__8",
"<>s__9",
"<>s__10",
"<>s__11",
"<>s__12",
"<>s__13",
"<>s__14",
"<>s__15",
"<>s__16",
"<>s__17",
"<>s__18",
"<>s__19",
"<>u__1",
}, module.GetFieldNames("C.<M>d__3"));
});
vd.VerifyPdb("C.M", @"
<symbols>
<files>
<file id=""1"" name="""" language=""C#"" />
</files>
<methods>
<method containingType=""C"" name=""M"" parameterNames=""disposable"">
<customDebugInfo>
<forwardIterator name=""<M>d__3"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""11"" />
<slot kind=""8"" offset=""11"" />
<slot kind=""0"" offset=""11"" />
<slot kind=""4"" offset=""53"" />
<slot kind=""6"" offset=""98"" />
<slot kind=""8"" offset=""98"" />
<slot kind=""0"" offset=""98"" />
<slot kind=""4"" offset=""151"" />
<slot kind=""4"" offset=""220"" />
<slot kind=""28"" offset=""261"" />
<slot kind=""28"" offset=""261"" ordinal=""1"" />
<slot kind=""28"" offset=""261"" ordinal=""2"" />
<slot kind=""28"" offset=""281"" />
<slot kind=""28"" offset=""281"" ordinal=""1"" />
<slot kind=""28"" offset=""281"" ordinal=""2"" />
<slot kind=""4"" offset=""307"" />
<slot kind=""4"" offset=""376"" />
<slot kind=""3"" offset=""410"" />
<slot kind=""2"" offset=""410"" />
</encLocalSlotMap>
</customDebugInfo>
</method>
</methods>
</symbols>
");
}
[Fact]
public void CaptureThis()
{
var source = @"
using System.Threading;
using System.Threading.Tasks;
using System;
struct TestCase
{
public async Task<int> Run()
{
return await Goo();
}
public async Task<int> Goo()
{
return await Task.Factory.StartNew(() => 42);
}
}
class Driver
{
static void Main()
{
var t = new TestCase();
var task = t.Run();
task.Wait();
Console.WriteLine(task.Result);
}
}";
var expected = @"
42
";
CompileAndVerify(source, expected);
}
[Fact]
public void CaptureThis2()
{
var source = @"
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System;
struct TestCase
{
public IEnumerable<int> Run()
{
yield return Goo();
}
public int Goo()
{
return 42;
}
}
class Driver
{
static void Main()
{
var t = new TestCase();
foreach (var x in t.Run())
{
Console.WriteLine(x);
}
}
}";
var expected = @"
42
";
CompileAndVerify(source, expected);
}
[Fact]
public void AsyncWithDynamic()
{
var source = @"
using System;
using System.Threading.Tasks;
class Test
{
public static async Task<int> F(dynamic t)
{
return await t;
}
public static void Main()
{
Task<int> t = F(Task.Factory.StartNew(() => { return 42; }));
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
CompileAndVerify(source, expectedOutput: expected, references: new[] { CSharpRef });
}
[Fact]
public void AsyncWithThisRef()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
int x = 42;
public async Task<int> F()
{
int c = this.x;
return await Task.Factory.StartNew(() => c);
}
}
class Test
{
public static void Main()
{
Task<int> t = new C().F();
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
var verifier = CompileAndVerify(source, expectedOutput: expected);
verifier.VerifyIL("C.<F>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 191 (0xbf)
.maxstack 3
.locals init (int V_0,
C V_1,
int V_2,
C.<>c__DisplayClass1_0 V_3, //CS$<>8__locals0
System.Runtime.CompilerServices.TaskAwaiter<int> V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__1.<>1__state""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldfld ""C C.<F>d__1.<>4__this""
IL_000d: stloc.1
.try
{
IL_000e: ldloc.0
IL_000f: brfalse.s IL_006a
IL_0011: newobj ""C.<>c__DisplayClass1_0..ctor()""
IL_0016: stloc.3
IL_0017: ldloc.3
IL_0018: ldloc.1
IL_0019: ldfld ""int C.x""
IL_001e: stfld ""int C.<>c__DisplayClass1_0.c""
IL_0023: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get""
IL_0028: ldloc.3
IL_0029: ldftn ""int C.<>c__DisplayClass1_0.<F>b__0()""
IL_002f: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_0034: callvirt ""System.Threading.Tasks.Task<int> System.Threading.Tasks.TaskFactory.StartNew<int>(System.Func<int>)""
IL_0039: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()""
IL_003e: stloc.s V_4
IL_0040: ldloca.s V_4
IL_0042: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get""
IL_0047: brtrue.s IL_0087
IL_0049: ldarg.0
IL_004a: ldc.i4.0
IL_004b: dup
IL_004c: stloc.0
IL_004d: stfld ""int C.<F>d__1.<>1__state""
IL_0052: ldarg.0
IL_0053: ldloc.s V_4
IL_0055: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__1""
IL_005a: ldarg.0
IL_005b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_0060: ldloca.s V_4
IL_0062: ldarg.0
IL_0063: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<F>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<F>d__1)""
IL_0068: leave.s IL_00be
IL_006a: ldarg.0
IL_006b: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__1""
IL_0070: stloc.s V_4
IL_0072: ldarg.0
IL_0073: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<F>d__1.<>u__1""
IL_0078: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>""
IL_007e: ldarg.0
IL_007f: ldc.i4.m1
IL_0080: dup
IL_0081: stloc.0
IL_0082: stfld ""int C.<F>d__1.<>1__state""
IL_0087: ldloca.s V_4
IL_0089: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()""
IL_008e: stloc.2
IL_008f: leave.s IL_00aa
}
catch System.Exception
{
IL_0091: stloc.s V_5
IL_0093: ldarg.0
IL_0094: ldc.i4.s -2
IL_0096: stfld ""int C.<F>d__1.<>1__state""
IL_009b: ldarg.0
IL_009c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_00a1: ldloc.s V_5
IL_00a3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00a8: leave.s IL_00be
}
IL_00aa: ldarg.0
IL_00ab: ldc.i4.s -2
IL_00ad: stfld ""int C.<F>d__1.<>1__state""
IL_00b2: ldarg.0
IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__1.<>t__builder""
IL_00b8: ldloc.2
IL_00b9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00be: ret
}
");
}
[Fact]
public void AsyncWithThisRef01()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
int x => 14;
public async Task<int> F()
{
int c = this.x;
await Task.Yield();
c += this.x;
await Task.Yield();
c += this.x;
await Task.Yield();
await Task.Yield();
await Task.Yield();
return c;
}
}
class Test
{
public static void Main()
{
Task<int> t = new C().F();
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
var verifier = CompileAndVerify(source, expectedOutput: expected);
verifier.VerifyIL("C.<F>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @"
{
// Code size 612 (0x264)
.maxstack 3
.locals init (int V_0,
C V_1,
int V_2,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_3,
System.Runtime.CompilerServices.YieldAwaitable V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__2.<>1__state""
IL_0006: stloc.0
IL_0007: ldarg.0
IL_0008: ldfld ""C C.<F>d__2.<>4__this""
IL_000d: stloc.1
.try
{
IL_000e: ldloc.0
IL_000f: switch (
IL_006f,
IL_00e0,
IL_0151,
IL_01af,
IL_020a)
IL_0028: ldarg.0
IL_0029: ldloc.1
IL_002a: call ""int C.x.get""
IL_002f: stfld ""int C.<F>d__2.<c>5__2""
IL_0034: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0039: stloc.s V_4
IL_003b: ldloca.s V_4
IL_003d: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_0042: stloc.3
IL_0043: ldloca.s V_3
IL_0045: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_004a: brtrue.s IL_008b
IL_004c: ldarg.0
IL_004d: ldc.i4.0
IL_004e: dup
IL_004f: stloc.0
IL_0050: stfld ""int C.<F>d__2.<>1__state""
IL_0055: ldarg.0
IL_0056: ldloc.3
IL_0057: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_005c: ldarg.0
IL_005d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_0062: ldloca.s V_3
IL_0064: ldarg.0
IL_0065: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__2>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__2)""
IL_006a: leave IL_0263
IL_006f: ldarg.0
IL_0070: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_0075: stloc.3
IL_0076: ldarg.0
IL_0077: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_007c: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0082: ldarg.0
IL_0083: ldc.i4.m1
IL_0084: dup
IL_0085: stloc.0
IL_0086: stfld ""int C.<F>d__2.<>1__state""
IL_008b: ldloca.s V_3
IL_008d: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_0092: ldarg.0
IL_0093: ldarg.0
IL_0094: ldfld ""int C.<F>d__2.<c>5__2""
IL_0099: ldloc.1
IL_009a: call ""int C.x.get""
IL_009f: add
IL_00a0: stfld ""int C.<F>d__2.<c>5__2""
IL_00a5: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_00aa: stloc.s V_4
IL_00ac: ldloca.s V_4
IL_00ae: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_00b3: stloc.3
IL_00b4: ldloca.s V_3
IL_00b6: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00bb: brtrue.s IL_00fc
IL_00bd: ldarg.0
IL_00be: ldc.i4.1
IL_00bf: dup
IL_00c0: stloc.0
IL_00c1: stfld ""int C.<F>d__2.<>1__state""
IL_00c6: ldarg.0
IL_00c7: ldloc.3
IL_00c8: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_00cd: ldarg.0
IL_00ce: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_00d3: ldloca.s V_3
IL_00d5: ldarg.0
IL_00d6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__2>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__2)""
IL_00db: leave IL_0263
IL_00e0: ldarg.0
IL_00e1: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_00e6: stloc.3
IL_00e7: ldarg.0
IL_00e8: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_00ed: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_00f3: ldarg.0
IL_00f4: ldc.i4.m1
IL_00f5: dup
IL_00f6: stloc.0
IL_00f7: stfld ""int C.<F>d__2.<>1__state""
IL_00fc: ldloca.s V_3
IL_00fe: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_0103: ldarg.0
IL_0104: ldarg.0
IL_0105: ldfld ""int C.<F>d__2.<c>5__2""
IL_010a: ldloc.1
IL_010b: call ""int C.x.get""
IL_0110: add
IL_0111: stfld ""int C.<F>d__2.<c>5__2""
IL_0116: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_011b: stloc.s V_4
IL_011d: ldloca.s V_4
IL_011f: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_0124: stloc.3
IL_0125: ldloca.s V_3
IL_0127: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_012c: brtrue.s IL_016d
IL_012e: ldarg.0
IL_012f: ldc.i4.2
IL_0130: dup
IL_0131: stloc.0
IL_0132: stfld ""int C.<F>d__2.<>1__state""
IL_0137: ldarg.0
IL_0138: ldloc.3
IL_0139: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_013e: ldarg.0
IL_013f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_0144: ldloca.s V_3
IL_0146: ldarg.0
IL_0147: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__2>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__2)""
IL_014c: leave IL_0263
IL_0151: ldarg.0
IL_0152: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_0157: stloc.3
IL_0158: ldarg.0
IL_0159: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_015e: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0164: ldarg.0
IL_0165: ldc.i4.m1
IL_0166: dup
IL_0167: stloc.0
IL_0168: stfld ""int C.<F>d__2.<>1__state""
IL_016d: ldloca.s V_3
IL_016f: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_0174: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0179: stloc.s V_4
IL_017b: ldloca.s V_4
IL_017d: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_0182: stloc.3
IL_0183: ldloca.s V_3
IL_0185: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_018a: brtrue.s IL_01cb
IL_018c: ldarg.0
IL_018d: ldc.i4.3
IL_018e: dup
IL_018f: stloc.0
IL_0190: stfld ""int C.<F>d__2.<>1__state""
IL_0195: ldarg.0
IL_0196: ldloc.3
IL_0197: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_019c: ldarg.0
IL_019d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_01a2: ldloca.s V_3
IL_01a4: ldarg.0
IL_01a5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__2>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__2)""
IL_01aa: leave IL_0263
IL_01af: ldarg.0
IL_01b0: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_01b5: stloc.3
IL_01b6: ldarg.0
IL_01b7: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_01bc: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_01c2: ldarg.0
IL_01c3: ldc.i4.m1
IL_01c4: dup
IL_01c5: stloc.0
IL_01c6: stfld ""int C.<F>d__2.<>1__state""
IL_01cb: ldloca.s V_3
IL_01cd: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_01d2: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_01d7: stloc.s V_4
IL_01d9: ldloca.s V_4
IL_01db: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_01e0: stloc.3
IL_01e1: ldloca.s V_3
IL_01e3: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_01e8: brtrue.s IL_0226
IL_01ea: ldarg.0
IL_01eb: ldc.i4.4
IL_01ec: dup
IL_01ed: stloc.0
IL_01ee: stfld ""int C.<F>d__2.<>1__state""
IL_01f3: ldarg.0
IL_01f4: ldloc.3
IL_01f5: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_01fa: ldarg.0
IL_01fb: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_0200: ldloca.s V_3
IL_0202: ldarg.0
IL_0203: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__2>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__2)""
IL_0208: leave.s IL_0263
IL_020a: ldarg.0
IL_020b: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_0210: stloc.3
IL_0211: ldarg.0
IL_0212: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__2.<>u__1""
IL_0217: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_021d: ldarg.0
IL_021e: ldc.i4.m1
IL_021f: dup
IL_0220: stloc.0
IL_0221: stfld ""int C.<F>d__2.<>1__state""
IL_0226: ldloca.s V_3
IL_0228: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_022d: ldarg.0
IL_022e: ldfld ""int C.<F>d__2.<c>5__2""
IL_0233: stloc.2
IL_0234: leave.s IL_024f
}
catch System.Exception
{
IL_0236: stloc.s V_5
IL_0238: ldarg.0
IL_0239: ldc.i4.s -2
IL_023b: stfld ""int C.<F>d__2.<>1__state""
IL_0240: ldarg.0
IL_0241: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_0246: ldloc.s V_5
IL_0248: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_024d: leave.s IL_0263
}
IL_024f: ldarg.0
IL_0250: ldc.i4.s -2
IL_0252: stfld ""int C.<F>d__2.<>1__state""
IL_0257: ldarg.0
IL_0258: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__2.<>t__builder""
IL_025d: ldloc.2
IL_025e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_0263: ret
}
");
}
[Fact]
public void AsyncWithBaseRef()
{
var source = @"
using System;
using System.Threading.Tasks;
class B
{
protected int x = 42;
}
class C : B
{
public async Task<int> F()
{
int c = base.x;
return await Task.Factory.StartNew(() => c);
}
}
class Test
{
public static void Main()
{
Task<int> t = new C().F();
t.Wait(1000 * 60);
Console.WriteLine(t.Result);
}
}";
var expected = @"
42
";
CompileAndVerify(source, expectedOutput: expected);
}
[Fact]
public void ReuseFields_SpillTemps()
{
var source = @"
using System.Threading.Tasks;
class Test
{
static void F1(int x, int y)
{
}
async static Task<int> F2()
{
return await Task.Factory.StartNew(() => 42);
}
public static async void Run()
{
int x = 1;
F1(x, await F2());
int y = 2;
F1(y, await F2());
int z = 3;
F1(z, await F2());
}
public static void Main()
{
Run();
}
}";
var reference = CreateCompilationWithMscorlib45(source, references: new MetadataReference[] { SystemRef_v4_0_30319_17929 }).EmitToImageReference();
var comp = CreateCompilationWithMscorlib45("", new[] { reference }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal));
var testClass = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("Test");
var stateMachineClass = (NamedTypeSymbol)testClass.GetMembers().Single(s => s.Name.StartsWith("<Run>", StringComparison.Ordinal));
IEnumerable<IGrouping<TypeSymbol, FieldSymbol>> spillFieldsByType = stateMachineClass.GetMembers().Where(m => m.Kind == SymbolKind.Field && m.Name.StartsWith("<>7__wrap", StringComparison.Ordinal)).Cast<FieldSymbol>().GroupBy(x => x.Type);
Assert.Equal(1, spillFieldsByType.Count());
Assert.Equal(1, spillFieldsByType.Single(x => TypeSymbol.Equals(x.Key, comp.GetSpecialType(SpecialType.System_Int32), TypeCompareKind.ConsiderEverything2)).Count());
}
[Fact]
public void ReuseFields_Generic()
{
var source = @"
using System.Collections.Generic;
using System.Threading.Tasks;
class Test<U>
{
static IEnumerable<T> GetEnum<T>() => null;
static Task<int> F(int a) => null;
public static async void M<S, T>()
{
foreach (var x in GetEnum<T>()) await F(1);
foreach (var x in GetEnum<S>()) await F(2);
foreach (var x in GetEnum<T>()) await F(3);
foreach (var x in GetEnum<U>()) await F(4);
foreach (var x in GetEnum<U>()) await F(5);
}
}";
var c = CompileAndVerify(source, expectedOutput: null, options: TestOptions.ReleaseDll);
var actual = GetFieldLoadsAndStores(c, "Test<U>.<M>d__2<S, T>.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext");
// make sure we are reusing synthesized iterator locals and that the locals are nulled:
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
IL_0000: ldarg.0
IL_0001: ldfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0027: callvirt ""System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator()""
IL_002c: stfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_0037: ldarg.0
IL_0038: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_005b: stloc.0
IL_005c: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0062: ldloc.1
IL_0063: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0068: ldarg.0
IL_0069: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_007b: ldarg.0
IL_007c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0082: ldarg.0
IL_0083: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0091: stloc.0
IL_0092: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_009f: ldarg.0
IL_00a0: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_00b2: ldarg.0
IL_00b3: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_00ba: ldarg.0
IL_00bb: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_00c7: ldnull
IL_00c8: stfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_00d3: callvirt ""System.Collections.Generic.IEnumerator<S> System.Collections.Generic.IEnumerable<S>.GetEnumerator()""
IL_00d8: stfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_00e4: ldarg.0
IL_00e5: ldfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_0108: stloc.0
IL_0109: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_010f: ldloc.1
IL_0110: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0115: ldarg.0
IL_0116: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_0128: ldarg.0
IL_0129: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_012f: ldarg.0
IL_0130: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_013e: stloc.0
IL_013f: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_014c: ldarg.0
IL_014d: ldfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_015f: ldarg.0
IL_0160: ldfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_0167: ldarg.0
IL_0168: ldfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_0174: ldnull
IL_0175: stfld ""System.Collections.Generic.IEnumerator<S> Test<U>.<M>d__2<S, T>.<>7__wrap2""
IL_0180: callvirt ""System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator()""
IL_0185: stfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_0191: ldarg.0
IL_0192: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_01b5: stloc.0
IL_01b6: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_01bc: ldloc.1
IL_01bd: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_01c2: ldarg.0
IL_01c3: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_01d5: ldarg.0
IL_01d6: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_01dc: ldarg.0
IL_01dd: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_01eb: stloc.0
IL_01ec: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_01f9: ldarg.0
IL_01fa: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_020c: ldarg.0
IL_020d: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_0214: ldarg.0
IL_0215: ldfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_0221: ldnull
IL_0222: stfld ""System.Collections.Generic.IEnumerator<T> Test<U>.<M>d__2<S, T>.<>7__wrap1""
IL_022d: callvirt ""System.Collections.Generic.IEnumerator<U> System.Collections.Generic.IEnumerable<U>.GetEnumerator()""
IL_0232: stfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_023e: ldarg.0
IL_023f: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_0262: stloc.0
IL_0263: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0269: ldloc.1
IL_026a: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_026f: ldarg.0
IL_0270: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_0282: ldarg.0
IL_0283: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0289: ldarg.0
IL_028a: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0298: stloc.0
IL_0299: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_02a6: ldarg.0
IL_02a7: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_02b9: ldarg.0
IL_02ba: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_02c1: ldarg.0
IL_02c2: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_02ce: ldnull
IL_02cf: stfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_02da: callvirt ""System.Collections.Generic.IEnumerator<U> System.Collections.Generic.IEnumerable<U>.GetEnumerator()""
IL_02df: stfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_02eb: ldarg.0
IL_02ec: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_030f: stloc.0
IL_0310: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0316: ldloc.1
IL_0317: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_031c: ldarg.0
IL_031d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_032c: ldarg.0
IL_032d: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0333: ldarg.0
IL_0334: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test<U>.<M>d__2<S, T>.<>u__1""
IL_0342: stloc.0
IL_0343: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0350: ldarg.0
IL_0351: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_0363: ldarg.0
IL_0364: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_036b: ldarg.0
IL_036c: ldfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_0378: ldnull
IL_0379: stfld ""System.Collections.Generic.IEnumerator<U> Test<U>.<M>d__2<S, T>.<>7__wrap3""
IL_0382: ldc.i4.s -2
IL_0384: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_0389: ldarg.0
IL_038a: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
IL_0398: ldc.i4.s -2
IL_039a: stfld ""int Test<U>.<M>d__2<S, T>.<>1__state""
IL_039f: ldarg.0
IL_03a0: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test<U>.<M>d__2<S, T>.<>t__builder""
", actual);
}
[Fact]
public void ReuseFields_Dynamic()
{
var source = @"
using System.Collections.Generic;
using System.Threading.Tasks;
class Test
{
static IEnumerable<dynamic> GetDynamicEnum() => null;
static IEnumerable<object> GetObjectEnum() => null;
static Task<int> F(int a) => null;
public static async void M()
{
foreach (var x in GetDynamicEnum()) await F(1);
foreach (var x in GetObjectEnum()) await F(2);
}
}";
var c = CompileAndVerify(source, expectedOutput: null, options: TestOptions.ReleaseDll);
var actual = GetFieldLoadsAndStores(c, "Test.<M>d__3.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext");
// make sure we are reusing synthesized iterator locals and that the locals are nulled:
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
IL_0000: ldarg.0
IL_0001: ldfld ""int Test.<M>d__3.<>1__state""
IL_0017: callvirt ""System.Collections.Generic.IEnumerator<dynamic> System.Collections.Generic.IEnumerable<dynamic>.GetEnumerator()""
IL_001c: stfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_0027: ldarg.0
IL_0028: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_004b: stloc.0
IL_004c: stfld ""int Test.<M>d__3.<>1__state""
IL_0052: ldloc.1
IL_0053: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_0058: ldarg.0
IL_0059: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<M>d__3.<>t__builder""
IL_006b: ldarg.0
IL_006c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_0072: ldarg.0
IL_0073: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_0081: stloc.0
IL_0082: stfld ""int Test.<M>d__3.<>1__state""
IL_008f: ldarg.0
IL_0090: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00a2: ldarg.0
IL_00a3: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00aa: ldarg.0
IL_00ab: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00b7: ldnull
IL_00b8: stfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00c3: callvirt ""System.Collections.Generic.IEnumerator<object> System.Collections.Generic.IEnumerable<object>.GetEnumerator()""
IL_00c8: stfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00d4: ldarg.0
IL_00d5: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_00f8: stloc.0
IL_00f9: stfld ""int Test.<M>d__3.<>1__state""
IL_00ff: ldloc.1
IL_0100: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_0105: ldarg.0
IL_0106: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<M>d__3.<>t__builder""
IL_0115: ldarg.0
IL_0116: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_011c: ldarg.0
IL_011d: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<M>d__3.<>u__1""
IL_012b: stloc.0
IL_012c: stfld ""int Test.<M>d__3.<>1__state""
IL_0139: ldarg.0
IL_013a: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_014c: ldarg.0
IL_014d: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_0154: ldarg.0
IL_0155: ldfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_0161: ldnull
IL_0162: stfld ""System.Collections.Generic.IEnumerator<dynamic> Test.<M>d__3.<>7__wrap1""
IL_016b: ldc.i4.s -2
IL_016d: stfld ""int Test.<M>d__3.<>1__state""
IL_0172: ldarg.0
IL_0173: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<M>d__3.<>t__builder""
IL_0181: ldc.i4.s -2
IL_0183: stfld ""int Test.<M>d__3.<>1__state""
IL_0188: ldarg.0
IL_0189: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<M>d__3.<>t__builder""
", actual);
}
[Fact]
public void ManySynthesizedNames()
{
string source = @"
using System;
using System.Threading.Tasks;
public class C
{
public async Task F()
{
var a1 = await Task.FromResult(default(Tuple<char, char, char>));
var a2 = await Task.FromResult(default(Tuple<char, char, byte>));
var a3 = await Task.FromResult(default(Tuple<char, byte, char>));
var a4 = await Task.FromResult(default(Tuple<char, byte, byte>));
var a5 = await Task.FromResult(default(Tuple<byte, char, char>));
var a6 = await Task.FromResult(default(Tuple<byte, char, byte>));
var a7 = await Task.FromResult(default(Tuple<byte, byte, char>));
var a8 = await Task.FromResult(default(Tuple<byte, byte, byte>));
var b1 = await Task.FromResult(default(Tuple<int, int, int>));
var b2 = await Task.FromResult(default(Tuple<int, int, long>));
var b3 = await Task.FromResult(default(Tuple<int, long, int>));
var b4 = await Task.FromResult(default(Tuple<int, long, long>));
var b5 = await Task.FromResult(default(Tuple<long, int, int>));
var b6 = await Task.FromResult(default(Tuple<long, int, long>));
var b7 = await Task.FromResult(default(Tuple<long, long, int>));
var b8 = await Task.FromResult(default(Tuple<long, long, long>));
}
}";
CompileAndVerify(source, targetFramework: TargetFramework.Empty, references: s_asyncRefs, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module =>
{
AssertEx.Equal(new[]
{
"<>1__state",
"<>t__builder",
"<>u__1",
"<>u__2",
"<>u__3",
"<>u__4",
"<>u__5",
"<>u__6",
"<>u__7",
"<>u__8",
"<>u__9",
"<>u__10",
"<>u__11",
"<>u__12",
"<>u__13",
"<>u__14",
"<>u__15",
"<>u__16",
}, module.GetFieldNames("C.<F>d__0"));
});
}
[WorkItem(9775, "https://github.com/dotnet/roslyn/issues/9775")]
[Fact]
public void Fixed_Debug()
{
var text =
@"using System;
using System.Threading.Tasks;
class C
{
static async Task<int> F(byte[] b)
{
int i;
unsafe
{
fixed (byte* p = b)
{
i = *p;
}
}
await Task.Yield();
return i;
}
static void Main()
{
var i = F(new byte[] { 1, 2, 3 }).Result;
Console.Write(i);
}
}";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"1", verify: Verification.Fails);
verifier.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 198 (0xc6)
.maxstack 3
.locals init (int V_0,
int V_1,
byte* V_2, //p
pinned byte[] V_3,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_4,
System.Runtime.CompilerServices.YieldAwaitable V_5,
System.Exception V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_006b
IL_000a: ldarg.0
IL_000b: ldfld ""byte[] C.<F>d__0.b""
IL_0010: dup
IL_0011: stloc.3
IL_0012: brfalse.s IL_0019
IL_0014: ldloc.3
IL_0015: ldlen
IL_0016: conv.i4
IL_0017: brtrue.s IL_001e
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.2
IL_001c: br.s IL_0027
IL_001e: ldloc.3
IL_001f: ldc.i4.0
IL_0020: ldelema ""byte""
IL_0025: conv.u
IL_0026: stloc.2
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: ldind.u1
IL_002a: stfld ""int C.<F>d__0.<i>5__2""
IL_002f: ldnull
IL_0030: stloc.3
IL_0031: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0036: stloc.s V_5
IL_0038: ldloca.s V_5
IL_003a: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_003f: stloc.s V_4
IL_0041: ldloca.s V_4
IL_0043: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0048: brtrue.s IL_0088
IL_004a: ldarg.0
IL_004b: ldc.i4.0
IL_004c: dup
IL_004d: stloc.0
IL_004e: stfld ""int C.<F>d__0.<>1__state""
IL_0053: ldarg.0
IL_0054: ldloc.s V_4
IL_0056: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_005b: ldarg.0
IL_005c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_0061: ldloca.s V_4
IL_0063: ldarg.0
IL_0064: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__0)""
IL_0069: leave.s IL_00c5
IL_006b: ldarg.0
IL_006c: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_0071: stloc.s V_4
IL_0073: ldarg.0
IL_0074: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_0079: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_007f: ldarg.0
IL_0080: ldc.i4.m1
IL_0081: dup
IL_0082: stloc.0
IL_0083: stfld ""int C.<F>d__0.<>1__state""
IL_0088: ldloca.s V_4
IL_008a: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_008f: ldarg.0
IL_0090: ldfld ""int C.<F>d__0.<i>5__2""
IL_0095: stloc.1
IL_0096: leave.s IL_00b1
}
catch System.Exception
{
IL_0098: stloc.s V_6
IL_009a: ldarg.0
IL_009b: ldc.i4.s -2
IL_009d: stfld ""int C.<F>d__0.<>1__state""
IL_00a2: ldarg.0
IL_00a3: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00a8: ldloc.s V_6
IL_00aa: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00af: leave.s IL_00c5
}
IL_00b1: ldarg.0
IL_00b2: ldc.i4.s -2
IL_00b4: stfld ""int C.<F>d__0.<>1__state""
IL_00b9: ldarg.0
IL_00ba: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00bf: ldloc.1
IL_00c0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00c5: ret
}");
verifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"1", verify: Verification.Fails);
verifier.VerifyIL("C.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 227 (0xe3)
.maxstack 3
.locals init (int V_0,
int V_1,
pinned byte[] V_2,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_3,
System.Runtime.CompilerServices.YieldAwaitable V_4,
C.<F>d__0 V_5,
System.Exception V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<F>d__0.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0086
IL_000e: nop
IL_000f: nop
IL_0010: ldarg.0
IL_0011: ldfld ""byte[] C.<F>d__0.b""
IL_0016: dup
IL_0017: stloc.2
IL_0018: brfalse.s IL_001f
IL_001a: ldloc.2
IL_001b: ldlen
IL_001c: conv.i4
IL_001d: brtrue.s IL_0029
IL_001f: ldarg.0
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stfld ""byte* C.<F>d__0.<p>5__2""
IL_0027: br.s IL_0037
IL_0029: ldarg.0
IL_002a: ldloc.2
IL_002b: ldc.i4.0
IL_002c: ldelema ""byte""
IL_0031: conv.u
IL_0032: stfld ""byte* C.<F>d__0.<p>5__2""
IL_0037: nop
IL_0038: ldarg.0
IL_0039: ldarg.0
IL_003a: ldfld ""byte* C.<F>d__0.<p>5__2""
IL_003f: ldind.u1
IL_0040: stfld ""int C.<F>d__0.<i>5__1""
IL_0045: nop
IL_0046: ldnull
IL_0047: stloc.2
IL_0048: nop
IL_0049: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_004e: stloc.s V_4
IL_0050: ldloca.s V_4
IL_0052: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_0057: stloc.3
IL_0058: ldloca.s V_3
IL_005a: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_005f: brtrue.s IL_00a2
IL_0061: ldarg.0
IL_0062: ldc.i4.0
IL_0063: dup
IL_0064: stloc.0
IL_0065: stfld ""int C.<F>d__0.<>1__state""
IL_006a: ldarg.0
IL_006b: ldloc.3
IL_006c: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_0071: ldarg.0
IL_0072: stloc.s V_5
IL_0074: ldarg.0
IL_0075: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_007a: ldloca.s V_3
IL_007c: ldloca.s V_5
IL_007e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, C.<F>d__0>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref C.<F>d__0)""
IL_0083: nop
IL_0084: leave.s IL_00e2
IL_0086: ldarg.0
IL_0087: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_008c: stloc.3
IL_008d: ldarg.0
IL_008e: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter C.<F>d__0.<>u__1""
IL_0093: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0099: ldarg.0
IL_009a: ldc.i4.m1
IL_009b: dup
IL_009c: stloc.0
IL_009d: stfld ""int C.<F>d__0.<>1__state""
IL_00a2: ldloca.s V_3
IL_00a4: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_00a9: nop
IL_00aa: ldarg.0
IL_00ab: ldfld ""int C.<F>d__0.<i>5__1""
IL_00b0: stloc.1
IL_00b1: leave.s IL_00cd
}
catch System.Exception
{
IL_00b3: stloc.s V_6
IL_00b5: ldarg.0
IL_00b6: ldc.i4.s -2
IL_00b8: stfld ""int C.<F>d__0.<>1__state""
IL_00bd: ldarg.0
IL_00be: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00c3: ldloc.s V_6
IL_00c5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)""
IL_00ca: nop
IL_00cb: leave.s IL_00e2
}
IL_00cd: ldarg.0
IL_00ce: ldc.i4.s -2
IL_00d0: stfld ""int C.<F>d__0.<>1__state""
IL_00d5: ldarg.0
IL_00d6: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> C.<F>d__0.<>t__builder""
IL_00db: ldloc.1
IL_00dc: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)""
IL_00e1: nop
IL_00e2: ret
}");
}
[WorkItem(15290, "https://github.com/dotnet/roslyn/issues/15290")]
[Fact]
public void ReuseLocals()
{
var text =
@"
using System;
using System.Threading.Tasks;
class Test
{
public static void Main(string[] args) => MainAsync(args).GetAwaiter().GetResult();
private static async Task MainAsync(string[] args)
{
if (args.Length > 0)
{
int a = 1;
await Task.Yield();
Console.WriteLine(a);
}
else
{
int b = 2;
await Task.Yield();
Console.WriteLine(b);
}
}
}";
var verifier = CompileAndVerify(text, options: TestOptions.ReleaseExe, expectedOutput: @"2");
// NOTE: only one hoisted int local:
// int Test.<MainAsync>d__1.<a>5__2
verifier.VerifyIL("Test.<MainAsync>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 292 (0x124)
.maxstack 3
.locals init (int V_0,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_1,
System.Runtime.CompilerServices.YieldAwaitable V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_005b
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq IL_00c9
IL_0011: ldarg.0
IL_0012: ldfld ""string[] Test.<MainAsync>d__1.args""
IL_0017: ldlen
IL_0018: brfalse.s IL_008b
IL_001a: ldarg.0
IL_001b: ldc.i4.1
IL_001c: stfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0021: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0026: stloc.2
IL_0027: ldloca.s V_2
IL_0029: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_002e: stloc.1
IL_002f: ldloca.s V_1
IL_0031: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0036: brtrue.s IL_0077
IL_0038: ldarg.0
IL_0039: ldc.i4.0
IL_003a: dup
IL_003b: stloc.0
IL_003c: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0041: ldarg.0
IL_0042: ldloc.1
IL_0043: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0048: ldarg.0
IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_004e: ldloca.s V_1
IL_0050: ldarg.0
IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_0056: leave IL_0123
IL_005b: ldarg.0
IL_005c: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0061: stloc.1
IL_0062: ldarg.0
IL_0063: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0068: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_006e: ldarg.0
IL_006f: ldc.i4.m1
IL_0070: dup
IL_0071: stloc.0
IL_0072: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0077: ldloca.s V_1
IL_0079: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_007e: ldarg.0
IL_007f: ldfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0084: call ""void System.Console.WriteLine(int)""
IL_0089: br.s IL_00f7
IL_008b: ldarg.0
IL_008c: ldc.i4.2
IL_008d: stfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0092: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0097: stloc.2
IL_0098: ldloca.s V_2
IL_009a: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_009f: stloc.1
IL_00a0: ldloca.s V_1
IL_00a2: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00a7: brtrue.s IL_00e5
IL_00a9: ldarg.0
IL_00aa: ldc.i4.1
IL_00ab: dup
IL_00ac: stloc.0
IL_00ad: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00b2: ldarg.0
IL_00b3: ldloc.1
IL_00b4: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00b9: ldarg.0
IL_00ba: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_00bf: ldloca.s V_1
IL_00c1: ldarg.0
IL_00c2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_00c7: leave.s IL_0123
IL_00c9: ldarg.0
IL_00ca: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00cf: stloc.1
IL_00d0: ldarg.0
IL_00d1: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00d6: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_00dc: ldarg.0
IL_00dd: ldc.i4.m1
IL_00de: dup
IL_00df: stloc.0
IL_00e0: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00e5: ldloca.s V_1
IL_00e7: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_00ec: ldarg.0
IL_00ed: ldfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_00f2: call ""void System.Console.WriteLine(int)""
IL_00f7: leave.s IL_0110
}
catch System.Exception
{
IL_00f9: stloc.3
IL_00fa: ldarg.0
IL_00fb: ldc.i4.s -2
IL_00fd: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0102: ldarg.0
IL_0103: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0108: ldloc.3
IL_0109: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_010e: leave.s IL_0123
}
IL_0110: ldarg.0
IL_0111: ldc.i4.s -2
IL_0113: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0118: ldarg.0
IL_0119: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_011e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0123: ret
}");
verifier = CompileAndVerify(text, options: TestOptions.DebugExe, expectedOutput: @"2");
// NOTE: two separate hoisted int locals:
// int Test.<MainAsync>d__1.<a>5__1 and
// int Test.<MainAsync>d__1.<b>5__2
verifier.VerifyIL("Test.<MainAsync>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 331 (0x14b)
.maxstack 3
.locals init (int V_0,
bool V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
Test.<MainAsync>d__1 V_4,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_5,
System.Exception V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0019
IL_0012: br.s IL_006f
IL_0014: br IL_00e8
IL_0019: nop
IL_001a: ldarg.0
IL_001b: ldfld ""string[] Test.<MainAsync>d__1.args""
IL_0020: ldlen
IL_0021: ldc.i4.0
IL_0022: cgt.un
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: brfalse.s IL_00a2
IL_0028: nop
IL_0029: ldarg.0
IL_002a: ldc.i4.1
IL_002b: stfld ""int Test.<MainAsync>d__1.<a>5__1""
IL_0030: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0035: stloc.3
IL_0036: ldloca.s V_3
IL_0038: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_003d: stloc.2
IL_003e: ldloca.s V_2
IL_0040: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0045: brtrue.s IL_008b
IL_0047: ldarg.0
IL_0048: ldc.i4.0
IL_0049: dup
IL_004a: stloc.0
IL_004b: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0050: ldarg.0
IL_0051: ldloc.2
IL_0052: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0057: ldarg.0
IL_0058: stloc.s V_4
IL_005a: ldarg.0
IL_005b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0060: ldloca.s V_2
IL_0062: ldloca.s V_4
IL_0064: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_0069: nop
IL_006a: leave IL_014a
IL_006f: ldarg.0
IL_0070: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0075: stloc.2
IL_0076: ldarg.0
IL_0077: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_007c: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0082: ldarg.0
IL_0083: ldc.i4.m1
IL_0084: dup
IL_0085: stloc.0
IL_0086: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_008b: ldloca.s V_2
IL_008d: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_0092: nop
IL_0093: ldarg.0
IL_0094: ldfld ""int Test.<MainAsync>d__1.<a>5__1""
IL_0099: call ""void System.Console.WriteLine(int)""
IL_009e: nop
IL_009f: nop
IL_00a0: br.s IL_011a
IL_00a2: nop
IL_00a3: ldarg.0
IL_00a4: ldc.i4.2
IL_00a5: stfld ""int Test.<MainAsync>d__1.<b>5__2""
IL_00aa: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_00af: stloc.3
IL_00b0: ldloca.s V_3
IL_00b2: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_00b7: stloc.s V_5
IL_00b9: ldloca.s V_5
IL_00bb: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00c0: brtrue.s IL_0105
IL_00c2: ldarg.0
IL_00c3: ldc.i4.1
IL_00c4: dup
IL_00c5: stloc.0
IL_00c6: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00cb: ldarg.0
IL_00cc: ldloc.s V_5
IL_00ce: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00d3: ldarg.0
IL_00d4: stloc.s V_4
IL_00d6: ldarg.0
IL_00d7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_00dc: ldloca.s V_5
IL_00de: ldloca.s V_4
IL_00e0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_00e5: nop
IL_00e6: leave.s IL_014a
IL_00e8: ldarg.0
IL_00e9: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00ee: stloc.s V_5
IL_00f0: ldarg.0
IL_00f1: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00f6: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_00fc: ldarg.0
IL_00fd: ldc.i4.m1
IL_00fe: dup
IL_00ff: stloc.0
IL_0100: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0105: ldloca.s V_5
IL_0107: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_010c: nop
IL_010d: ldarg.0
IL_010e: ldfld ""int Test.<MainAsync>d__1.<b>5__2""
IL_0113: call ""void System.Console.WriteLine(int)""
IL_0118: nop
IL_0119: nop
IL_011a: leave.s IL_0136
}
catch System.Exception
{
IL_011c: stloc.s V_6
IL_011e: ldarg.0
IL_011f: ldc.i4.s -2
IL_0121: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0126: ldarg.0
IL_0127: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_012c: ldloc.s V_6
IL_012e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0133: nop
IL_0134: leave.s IL_014a
}
IL_0136: ldarg.0
IL_0137: ldc.i4.s -2
IL_0139: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_013e: ldarg.0
IL_013f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0144: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0149: nop
IL_014a: ret
}");
}
[WorkItem(15290, "https://github.com/dotnet/roslyn/issues/15290")]
[Fact]
public void ReuseLocalsSynthetic()
{
var text =
@"
using System;
using System.Threading.Tasks;
class Test
{
public static void Main(string[] args) => MainAsync(args).GetAwaiter().GetResult();
private static async Task MainAsync(string[] args)
{
if (args.Length > 0)
{
int a = 1;
await Task.Yield();
Console.WriteLine(a);
}
else
{
int b = 2;
await Task.Yield();
Console.WriteLine(b);
}
}
}";
var verifier = CompileAndVerify(text, options: TestOptions.ReleaseExe, expectedOutput: @"2");
// NOTE: only one hoisted int local:
// int Test.<MainAsync>d__1.<a>5__2
verifier.VerifyIL("Test.<MainAsync>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 292 (0x124)
.maxstack 3
.locals init (int V_0,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_1,
System.Runtime.CompilerServices.YieldAwaitable V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_005b
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: beq IL_00c9
IL_0011: ldarg.0
IL_0012: ldfld ""string[] Test.<MainAsync>d__1.args""
IL_0017: ldlen
IL_0018: brfalse.s IL_008b
IL_001a: ldarg.0
IL_001b: ldc.i4.1
IL_001c: stfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0021: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0026: stloc.2
IL_0027: ldloca.s V_2
IL_0029: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_002e: stloc.1
IL_002f: ldloca.s V_1
IL_0031: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0036: brtrue.s IL_0077
IL_0038: ldarg.0
IL_0039: ldc.i4.0
IL_003a: dup
IL_003b: stloc.0
IL_003c: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0041: ldarg.0
IL_0042: ldloc.1
IL_0043: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0048: ldarg.0
IL_0049: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_004e: ldloca.s V_1
IL_0050: ldarg.0
IL_0051: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_0056: leave IL_0123
IL_005b: ldarg.0
IL_005c: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0061: stloc.1
IL_0062: ldarg.0
IL_0063: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0068: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_006e: ldarg.0
IL_006f: ldc.i4.m1
IL_0070: dup
IL_0071: stloc.0
IL_0072: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0077: ldloca.s V_1
IL_0079: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_007e: ldarg.0
IL_007f: ldfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0084: call ""void System.Console.WriteLine(int)""
IL_0089: br.s IL_00f7
IL_008b: ldarg.0
IL_008c: ldc.i4.2
IL_008d: stfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_0092: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0097: stloc.2
IL_0098: ldloca.s V_2
IL_009a: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_009f: stloc.1
IL_00a0: ldloca.s V_1
IL_00a2: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00a7: brtrue.s IL_00e5
IL_00a9: ldarg.0
IL_00aa: ldc.i4.1
IL_00ab: dup
IL_00ac: stloc.0
IL_00ad: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00b2: ldarg.0
IL_00b3: ldloc.1
IL_00b4: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00b9: ldarg.0
IL_00ba: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_00bf: ldloca.s V_1
IL_00c1: ldarg.0
IL_00c2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_00c7: leave.s IL_0123
IL_00c9: ldarg.0
IL_00ca: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00cf: stloc.1
IL_00d0: ldarg.0
IL_00d1: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00d6: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_00dc: ldarg.0
IL_00dd: ldc.i4.m1
IL_00de: dup
IL_00df: stloc.0
IL_00e0: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00e5: ldloca.s V_1
IL_00e7: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_00ec: ldarg.0
IL_00ed: ldfld ""int Test.<MainAsync>d__1.<a>5__2""
IL_00f2: call ""void System.Console.WriteLine(int)""
IL_00f7: leave.s IL_0110
}
catch System.Exception
{
IL_00f9: stloc.3
IL_00fa: ldarg.0
IL_00fb: ldc.i4.s -2
IL_00fd: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0102: ldarg.0
IL_0103: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0108: ldloc.3
IL_0109: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_010e: leave.s IL_0123
}
IL_0110: ldarg.0
IL_0111: ldc.i4.s -2
IL_0113: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0118: ldarg.0
IL_0119: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_011e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0123: ret
}");
verifier = CompileAndVerify(text, options: TestOptions.DebugExe, expectedOutput: @"2");
// NOTE: two separate hoisted int locals:
// int Test.<MainAsync>d__1.<a>5__1 and
// int Test.<MainAsync>d__1.<b>5__2
verifier.VerifyIL("Test.<MainAsync>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()",
@"
{
// Code size 331 (0x14b)
.maxstack 3
.locals init (int V_0,
bool V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
Test.<MainAsync>d__1 V_4,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_5,
System.Exception V_6)
IL_0000: ldarg.0
IL_0001: ldfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0014
IL_0010: br.s IL_0019
IL_0012: br.s IL_006f
IL_0014: br IL_00e8
IL_0019: nop
IL_001a: ldarg.0
IL_001b: ldfld ""string[] Test.<MainAsync>d__1.args""
IL_0020: ldlen
IL_0021: ldc.i4.0
IL_0022: cgt.un
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: brfalse.s IL_00a2
IL_0028: nop
IL_0029: ldarg.0
IL_002a: ldc.i4.1
IL_002b: stfld ""int Test.<MainAsync>d__1.<a>5__1""
IL_0030: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_0035: stloc.3
IL_0036: ldloca.s V_3
IL_0038: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_003d: stloc.2
IL_003e: ldloca.s V_2
IL_0040: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_0045: brtrue.s IL_008b
IL_0047: ldarg.0
IL_0048: ldc.i4.0
IL_0049: dup
IL_004a: stloc.0
IL_004b: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0050: ldarg.0
IL_0051: ldloc.2
IL_0052: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0057: ldarg.0
IL_0058: stloc.s V_4
IL_005a: ldarg.0
IL_005b: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0060: ldloca.s V_2
IL_0062: ldloca.s V_4
IL_0064: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_0069: nop
IL_006a: leave IL_014a
IL_006f: ldarg.0
IL_0070: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_0075: stloc.2
IL_0076: ldarg.0
IL_0077: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_007c: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_0082: ldarg.0
IL_0083: ldc.i4.m1
IL_0084: dup
IL_0085: stloc.0
IL_0086: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_008b: ldloca.s V_2
IL_008d: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_0092: nop
IL_0093: ldarg.0
IL_0094: ldfld ""int Test.<MainAsync>d__1.<a>5__1""
IL_0099: call ""void System.Console.WriteLine(int)""
IL_009e: nop
IL_009f: nop
IL_00a0: br.s IL_011a
IL_00a2: nop
IL_00a3: ldarg.0
IL_00a4: ldc.i4.2
IL_00a5: stfld ""int Test.<MainAsync>d__1.<b>5__2""
IL_00aa: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()""
IL_00af: stloc.3
IL_00b0: ldloca.s V_3
IL_00b2: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()""
IL_00b7: stloc.s V_5
IL_00b9: ldloca.s V_5
IL_00bb: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get""
IL_00c0: brtrue.s IL_0105
IL_00c2: ldarg.0
IL_00c3: ldc.i4.1
IL_00c4: dup
IL_00c5: stloc.0
IL_00c6: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_00cb: ldarg.0
IL_00cc: ldloc.s V_5
IL_00ce: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00d3: ldarg.0
IL_00d4: stloc.s V_4
IL_00d6: ldarg.0
IL_00d7: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_00dc: ldloca.s V_5
IL_00de: ldloca.s V_4
IL_00e0: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Test.<MainAsync>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Test.<MainAsync>d__1)""
IL_00e5: nop
IL_00e6: leave.s IL_014a
IL_00e8: ldarg.0
IL_00e9: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00ee: stloc.s V_5
IL_00f0: ldarg.0
IL_00f1: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Test.<MainAsync>d__1.<>u__1""
IL_00f6: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter""
IL_00fc: ldarg.0
IL_00fd: ldc.i4.m1
IL_00fe: dup
IL_00ff: stloc.0
IL_0100: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0105: ldloca.s V_5
IL_0107: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()""
IL_010c: nop
IL_010d: ldarg.0
IL_010e: ldfld ""int Test.<MainAsync>d__1.<b>5__2""
IL_0113: call ""void System.Console.WriteLine(int)""
IL_0118: nop
IL_0119: nop
IL_011a: leave.s IL_0136
}
catch System.Exception
{
IL_011c: stloc.s V_6
IL_011e: ldarg.0
IL_011f: ldc.i4.s -2
IL_0121: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_0126: ldarg.0
IL_0127: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_012c: ldloc.s V_6
IL_012e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)""
IL_0133: nop
IL_0134: leave.s IL_014a
}
IL_0136: ldarg.0
IL_0137: ldc.i4.s -2
IL_0139: stfld ""int Test.<MainAsync>d__1.<>1__state""
IL_013e: ldarg.0
IL_013f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<MainAsync>d__1.<>t__builder""
IL_0144: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()""
IL_0149: nop
IL_014a: ret
}");
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpCodeActions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpCodeActions : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpCodeActions(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpCodeActions))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public void GenerateMethodInClosedFile()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Foo.cs", contents: @"
public class Foo
{
}
");
SetUpEditor(@"
using System;
public class Program
{
public static void Main(string[] args)
{
Foo f = new Foo();
f.Bar()$$
}
}
");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Generate method 'Foo.Bar'", applyFix: true);
VisualStudio.SolutionExplorer.Verify.FileContents(project, "Foo.cs", @"
using System;
public class Foo
{
internal void Bar()
{
throw new NotImplementedException();
}
}
");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public void FastDoubleInvoke()
{
// We want to invoke the first smart tag and then *immediately * try invoking the next.
// The next will happen to be the 'Simplify name' smart tag. We should be able
// to get it to invoke without any sort of waiting to happen. This helps address a bug
// we had where our asynchronous smart tags interfered with asynchrony in VS, which caused
// the second smart tag to not expand if you tried invoking it too quickly
SetUpEditor(@"
class Program
{
static void Main(string[] args)
{
Exception $$ex = new System.ArgumentException();
}
}
");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("using System;", applyFix: true, blockUntilComplete: true);
VisualStudio.Editor.InvokeCodeActionListWithoutWaiting();
VisualStudio.Editor.Verify.CodeAction("Simplify name 'System.ArgumentException'", applyFix: true, blockUntilComplete: true);
VisualStudio.Editor.Verify.TextContains(
@"
using System;
class Program
{
static void Main(string[] args)
{
Exception ex = new ArgumentException();
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public void InvokeDelegateWithConditionalAccessMultipleTimes()
{
var markup = @"
using System;
class C
{
public event EventHandler First;
public event EventHandler Second;
void RaiseFirst()
{
var temp1 = First;
if (temp1 != null)
{
temp1$$(this, EventArgs.Empty);
}
}
void RaiseSecond()
{
var temp2 = Second;
if (temp2 != null)
{
temp2(this, EventArgs.Empty);
}
}
}";
MarkupTestFile.GetSpans(markup, out _, out ImmutableArray<TextSpan> _);
SetUpEditor(markup);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Delegate invocation can be simplified.", applyFix: true, ensureExpectedItemsAreOrdered: true, blockUntilComplete: true);
VisualStudio.Editor.PlaceCaret("temp2", 0, 0, extendSelection: false, selectBlock: false);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Delegate invocation can be simplified.", applyFix: true, ensureExpectedItemsAreOrdered: true, blockUntilComplete: true);
VisualStudio.Editor.Verify.TextContains("First?.");
VisualStudio.Editor.Verify.TextContains("Second?.");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.EditorConfig)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
[WorkItem(15003, "https://github.com/dotnet/roslyn/issues/15003")]
[WorkItem(19089, "https://github.com/dotnet/roslyn/issues/19089")]
public void ApplyEditorConfigAndFixAllOccurrences()
{
var markup = @"
class C
{
public int X1
{
get
{
$$return 3;
}
}
public int Y1 => 5;
public int X2
{
get
{
return 3;
}
}
public int Y2 => 5;
}";
var expectedText = @"
class C
{
public int X1 => 3;
public int Y1 => 5;
public int X2 => 3;
public int Y2 => 5;
}";
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");
/*
* The first portion of this test adds a .editorconfig file to configure the analyzer behavior, and verifies
* that diagnostics appear automatically in response to the newly-created file. A fix all operation is
* applied, and the result is verified against the expected outcome for the .editorconfig style.
*/
MarkupTestFile.GetSpans(markup, out _, out ImmutableArray<TextSpan> _);
SetUpEditor(markup);
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.Verify.CodeActionsNotShowing();
var editorConfig = @"root = true
[*.cs]
csharp_style_expression_bodied_properties = true:warning
";
VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig, open: false);
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Use expression body for properties",
applyFix: true,
fixAllScope: FixAllScope.Project);
Assert.Equal(expectedText, VisualStudio.Editor.GetText());
/*
* The second portion of this test modifier the existing .editorconfig file to configure the analyzer to the
* opposite style of the initial configuration, and verifies that diagnostics update automatically in
* response to the changes. A fix all operation is applied, and the result is verified against the expected
* outcome for the modified .editorconfig style.
*/
VisualStudio.SolutionExplorer.SetFileContents(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig.Replace("true:warning", "false:warning"));
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Use block body for properties",
applyFix: true,
fixAllScope: FixAllScope.Project);
expectedText = @"
class C
{
public int X1
{
get
{
return 3;
}
}
public int Y1
{
get
{
return 5;
}
}
public int X2
{
get
{
return 3;
}
}
public int Y2
{
get
{
return 5;
}
}
}";
Assert.Equal(expectedText, VisualStudio.Editor.GetText());
}
[CriticalWpfTheory]
[InlineData(FixAllScope.Project)]
[InlineData(FixAllScope.Solution)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
[WorkItem(33507, "https://github.com/dotnet/roslyn/issues/33507")]
public void FixAllOccurrencesIgnoresGeneratedCode(FixAllScope scope)
{
var markup = @"
using System;
using $$System.Threading;
class C
{
public IntPtr X1 { get; set; }
}";
var expectedText = @"
using System;
class C
{
public IntPtr X1 { get; set; }
}";
var generatedSourceMarkup = @"// <auto-generated/>
using System;
using $$System.Threading;
class D
{
public IntPtr X1 { get; set; }
}";
var expectedGeneratedSource = @"// <auto-generated/>
using System;
class D
{
public IntPtr X1 { get; set; }
}";
MarkupTestFile.GetPosition(generatedSourceMarkup, out var generatedSource, out int generatedSourcePosition);
VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), "D.cs", generatedSource, open: false);
// Switch to the main document we'll be editing
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");
// Verify that applying a Fix All operation does not change generated files.
// This is a regression test for correctness with respect to the design.
SetUpEditor(markup);
VisualStudio.WaitForApplicationIdle(CancellationToken.None);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Remove Unnecessary Usings",
applyFix: true,
fixAllScope: scope);
Assert.Equal(expectedText, VisualStudio.Editor.GetText());
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "D.cs");
Assert.Equal(generatedSource, VisualStudio.Editor.GetText());
// Verify that a Fix All in Document in the generated file still does nothing.
// ⚠ This is a statement of the current behavior, and not a claim regarding correctness of the design.
// The current behavior is observable; any change to this behavior should be part of an intentional design
// change.
VisualStudio.Editor.MoveCaret(generatedSourcePosition);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Remove Unnecessary Usings",
applyFix: true,
fixAllScope: FixAllScope.Document);
Assert.Equal(generatedSource, VisualStudio.Editor.GetText());
// Verify that the code action can still be applied manually from within the generated file.
// This is a regression test for correctness with respect to the design.
VisualStudio.Editor.MoveCaret(generatedSourcePosition);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Remove Unnecessary Usings",
applyFix: true,
fixAllScope: null);
Assert.Equal(expectedGeneratedSource, VisualStudio.Editor.GetText());
}
[CriticalWpfTheory]
[InlineData(FixAllScope.Project)]
[InlineData(FixAllScope.Solution)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
[WorkItem(33507, "https://github.com/dotnet/roslyn/issues/33507")]
public void FixAllOccurrencesTriggeredFromGeneratedCode(FixAllScope scope)
{
var markup = @"// <auto-generated/>
using System;
using $$System.Threading;
class C
{
public IntPtr X1 { get; set; }
}";
var secondFile = @"
using System;
using System.Threading;
class D
{
public IntPtr X1 { get; set; }
}";
var expectedSecondFile = @"
using System;
class D
{
public IntPtr X1 { get; set; }
}";
VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), "D.cs", secondFile, open: false);
// Switch to the main document we'll be editing
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");
// Verify that applying a Fix All operation does not change generated file, but does change other files.
// ⚠ This is a statement of the current behavior, and not a claim regarding correctness of the design.
// The current behavior is observable; any change to this behavior should be part of an intentional design
// change.
MarkupTestFile.GetPosition(markup, out var expectedText, out int _);
SetUpEditor(markup);
VisualStudio.WaitForApplicationIdle(CancellationToken.None);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Remove Unnecessary Usings",
applyFix: true,
fixAllScope: scope);
Assert.Equal(expectedText, VisualStudio.Editor.GetText());
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "D.cs");
Assert.Equal(expectedSecondFile, VisualStudio.Editor.GetText());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public void ClassificationInPreviewPane()
{
SetUpEditor(@"
class Program
{
int Main()
{
Foo$$();
}
}");
VisualStudio.Editor.InvokeCodeActionList();
var classifiedTokens = GetLightbulbPreviewClassification("Generate method 'Program.Foo'");
Assert.True(classifiedTokens.Any(c => c.Text == "void" && c.Classification == "keyword"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public void AddUsingExactMatchBeforeRenameTracking()
{
SetUpEditor(@"
public class Program
{
static void Main(string[] args)
{
P2$$ p;
}
}
public class P2 { }");
VisualStudio.Editor.SendKeys(VirtualKey.Backspace, VirtualKey.Backspace, "Stream");
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"using System.IO;",
"Rename 'P2' to 'Stream'",
"System.IO.Stream",
"Generate class 'Stream' in new file",
"Generate class 'Stream'",
"Generate nested class 'Stream'",
"Generate new type...",
"Remove unused variable",
"Suppress or Configure issues",
"Suppress CS0168",
"in Source",
"Configure CS0168 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: expectedItems[0], ensureExpectedItemsAreOrdered: true);
VisualStudio.Editor.Verify.TextContains("using System.IO;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public void GFUFuzzyMatchAfterRenameTracking()
{
SetUpEditor(@"
namespace N
{
class Goober { }
}
namespace NS
{
public class P2
{
static void Main(string[] args)
{
P2$$ p;
}
}
}");
VisualStudio.Editor.SendKeys(VirtualKey.Backspace, VirtualKey.Backspace,
"Foober");
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"Rename 'P2' to 'Foober'",
"Generate type 'Foober'",
"Generate class 'Foober' in new file",
"Generate class 'Foober'",
"Generate nested class 'Foober'",
"Generate new type...",
"Goober - using N;",
"Suppress or Configure issues",
"Suppress CS0168",
"in Source",
"Configure CS0168 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: expectedItems[0], ensureExpectedItemsAreOrdered: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public void SuppressionAfterRefactorings()
{
SetUpEditor(@"
[System.Obsolete]
class C
{
}
class Program
{
static void Main(string[] args)
{
C p = $$2;
}
}");
VisualStudio.Editor.SelectTextInCurrentDocument("2");
VisualStudio.Editor.InvokeCodeActionList();
var generateImplicitTitle = "Generate implicit conversion operator in 'C'";
var expectedItems = new[]
{
"Introduce constant for '2'",
"Introduce constant for all occurrences of '2'",
"Introduce local constant for '2'",
"Introduce local constant for all occurrences of '2'",
"Extract method",
generateImplicitTitle,
"Suppress or Configure issues",
"Suppress CS0612",
"in Source",
"Configure CS0612 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: generateImplicitTitle, ensureExpectedItemsAreOrdered: true);
VisualStudio.Editor.Verify.TextContains("implicit");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public void OrderFixesByCursorProximityLeft()
{
SetUpEditor(@"
using System;
public class Program
{
static void Main(string[] args)
{
Byte[] bytes = null;
GCHandle$$ handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
}
}");
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"using System.Runtime.InteropServices;",
"System.Runtime.InteropServices.GCHandle"
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: expectedItems[0], ensureExpectedItemsAreOrdered: true);
VisualStudio.Editor.Verify.TextContains("using System.Runtime.InteropServices");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public void OrderFixesByCursorProximityRight()
{
SetUpEditor(@"
using System;
public class Program
{
static void Main(string[] args)
{
Byte[] bytes = null;
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.$$Pinned);
}
}");
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"using System.Runtime.InteropServices;",
"System.Runtime.InteropServices.GCHandle"
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: expectedItems[0], ensureExpectedItemsAreOrdered: true);
VisualStudio.Editor.Verify.TextContains("using System.Runtime.InteropServices");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public void ConfigureCodeStyleOptionValueAndSeverity()
{
SetUpEditor(@"
using System;
public class Program
{
static void Main(string[] args)
{
var $$x = new Program();
}
}");
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"Use discard '__'", // IDE0059
"Use explicit type instead of 'var'", // IDE0008
"Introduce local",
"Introduce local for 'new Program()'",
"Introduce local for all occurrences of 'new Program()'",
"Suppress or Configure issues",
"Configure IDE0008 code style",
"csharp__style__var__elsewhere",
"true",
"false",
"csharp__style__var__for__built__in__types",
"true",
"false",
"csharp__style__var__when__type__is__apparent",
"true",
"false",
"Configure IDE0008 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
"Suppress IDE0059",
"in Source",
"in Suppression File",
"in Source (attribute)",
"Configure IDE0059 code style",
"unused__local__variable",
"discard__variable",
"Configure IDE0059 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
"Configure severity for all 'Style' analyzers",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
"Configure severity for all analyzers",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, ensureExpectedItemsAreOrdered: true);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46784"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
[WorkItem(46784, "https://github.com/dotnet/roslyn/issues/46784")]
public void ConfigureSeverity()
{
var markup = @"
class C
{
public static void Main()
{
// CS0168: The variable 'x' is declared but never used
int $$x;
}
}";
SetUpEditor(markup);
// Verify CS0168 warning in original code.
VerifyDiagnosticInErrorList("Warning", VisualStudio);
// Apply configuration severity fix to change CS0168 to be an error.
SetUpEditor(markup);
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"Remove unused variable",
"Suppress or Configure issues",
"Suppress CS0168",
"in Source",
"Configure CS0168 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: "Error", ensureExpectedItemsAreOrdered: true);
// Verify CS0168 is now reported as an error.
VerifyDiagnosticInErrorList("Error", VisualStudio);
return;
static void VerifyDiagnosticInErrorList(string expectedSeverity, VisualStudioInstance visualStudio)
{
visualStudio.ErrorList.ShowErrorList();
var expectedContents = new[] {
new ErrorListItem(
severity: expectedSeverity,
description: "The variable 'x' is declared but never used",
project: "TestProj",
fileName: "Class1.cs",
line: 7,
column: 13)
};
var actualContents = visualStudio.ErrorList.GetErrorListContents();
Assert.Equal(expectedContents, actualContents);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Common;
using Microsoft.VisualStudio.IntegrationTest.Utilities.Input;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils;
namespace Roslyn.VisualStudio.IntegrationTests.CSharp
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class CSharpCodeActions : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.CSharp;
public CSharpCodeActions(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(CSharpCodeActions))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public void GenerateMethodInClosedFile()
{
var project = new ProjectUtils.Project(ProjectName);
VisualStudio.SolutionExplorer.AddFile(project, "Foo.cs", contents: @"
public class Foo
{
}
");
SetUpEditor(@"
using System;
public class Program
{
public static void Main(string[] args)
{
Foo f = new Foo();
f.Bar()$$
}
}
");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Generate method 'Foo.Bar'", applyFix: true);
VisualStudio.SolutionExplorer.Verify.FileContents(project, "Foo.cs", @"
using System;
public class Foo
{
internal void Bar()
{
throw new NotImplementedException();
}
}
");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public void FastDoubleInvoke()
{
// We want to invoke the first smart tag and then *immediately * try invoking the next.
// The next will happen to be the 'Simplify name' smart tag. We should be able
// to get it to invoke without any sort of waiting to happen. This helps address a bug
// we had where our asynchronous smart tags interfered with asynchrony in VS, which caused
// the second smart tag to not expand if you tried invoking it too quickly
SetUpEditor(@"
class Program
{
static void Main(string[] args)
{
Exception $$ex = new System.ArgumentException();
}
}
");
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("using System;", applyFix: true, blockUntilComplete: true);
VisualStudio.Editor.InvokeCodeActionListWithoutWaiting();
VisualStudio.Editor.Verify.CodeAction("Simplify name 'System.ArgumentException'", applyFix: true, blockUntilComplete: true);
VisualStudio.Editor.Verify.TextContains(
@"
using System;
class Program
{
static void Main(string[] args)
{
Exception ex = new ArgumentException();
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsInvokeDelegateWithConditionalAccess)]
public void InvokeDelegateWithConditionalAccessMultipleTimes()
{
var markup = @"
using System;
class C
{
public event EventHandler First;
public event EventHandler Second;
void RaiseFirst()
{
var temp1 = First;
if (temp1 != null)
{
temp1$$(this, EventArgs.Empty);
}
}
void RaiseSecond()
{
var temp2 = Second;
if (temp2 != null)
{
temp2(this, EventArgs.Empty);
}
}
}";
MarkupTestFile.GetSpans(markup, out _, out ImmutableArray<TextSpan> _);
SetUpEditor(markup);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Delegate invocation can be simplified.", applyFix: true, ensureExpectedItemsAreOrdered: true, blockUntilComplete: true);
VisualStudio.Editor.PlaceCaret("temp2", 0, 0, extendSelection: false, selectBlock: false);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction("Delegate invocation can be simplified.", applyFix: true, ensureExpectedItemsAreOrdered: true, blockUntilComplete: true);
VisualStudio.Editor.Verify.TextContains("First?.");
VisualStudio.Editor.Verify.TextContains("Second?.");
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.EditorConfig)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
[WorkItem(15003, "https://github.com/dotnet/roslyn/issues/15003")]
[WorkItem(19089, "https://github.com/dotnet/roslyn/issues/19089")]
public void ApplyEditorConfigAndFixAllOccurrences()
{
var markup = @"
class C
{
public int X1
{
get
{
$$return 3;
}
}
public int Y1 => 5;
public int X2
{
get
{
return 3;
}
}
public int Y2 => 5;
}";
var expectedText = @"
class C
{
public int X1 => 3;
public int Y1 => 5;
public int X2 => 3;
public int Y2 => 5;
}";
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");
/*
* The first portion of this test adds a .editorconfig file to configure the analyzer behavior, and verifies
* that diagnostics appear automatically in response to the newly-created file. A fix all operation is
* applied, and the result is verified against the expected outcome for the .editorconfig style.
*/
MarkupTestFile.GetSpans(markup, out _, out ImmutableArray<TextSpan> _);
SetUpEditor(markup);
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.Verify.CodeActionsNotShowing();
var editorConfig = @"root = true
[*.cs]
csharp_style_expression_bodied_properties = true:warning
";
VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig, open: false);
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Use expression body for properties",
applyFix: true,
fixAllScope: FixAllScope.Project);
Assert.Equal(expectedText, VisualStudio.Editor.GetText());
/*
* The second portion of this test modifier the existing .editorconfig file to configure the analyzer to the
* opposite style of the initial configuration, and verifies that diagnostics update automatically in
* response to the changes. A fix all operation is applied, and the result is verified against the expected
* outcome for the modified .editorconfig style.
*/
VisualStudio.SolutionExplorer.SetFileContents(new ProjectUtils.Project(ProjectName), ".editorconfig", editorConfig.Replace("true:warning", "false:warning"));
VisualStudio.Workspace.WaitForAllAsyncOperations(
Helper.HangMitigatingTimeout,
FeatureAttribute.Workspace,
FeatureAttribute.SolutionCrawler,
FeatureAttribute.DiagnosticService,
FeatureAttribute.ErrorSquiggles);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Use block body for properties",
applyFix: true,
fixAllScope: FixAllScope.Project);
expectedText = @"
class C
{
public int X1
{
get
{
return 3;
}
}
public int Y1
{
get
{
return 5;
}
}
public int X2
{
get
{
return 3;
}
}
public int Y2
{
get
{
return 5;
}
}
}";
Assert.Equal(expectedText, VisualStudio.Editor.GetText());
}
[CriticalWpfTheory]
[InlineData(FixAllScope.Project)]
[InlineData(FixAllScope.Solution)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
[WorkItem(33507, "https://github.com/dotnet/roslyn/issues/33507")]
public void FixAllOccurrencesIgnoresGeneratedCode(FixAllScope scope)
{
var markup = @"
using System;
using $$System.Threading;
class C
{
public IntPtr X1 { get; set; }
}";
var expectedText = @"
using System;
class C
{
public IntPtr X1 { get; set; }
}";
var generatedSourceMarkup = @"// <auto-generated/>
using System;
using $$System.Threading;
class D
{
public IntPtr X1 { get; set; }
}";
var expectedGeneratedSource = @"// <auto-generated/>
using System;
class D
{
public IntPtr X1 { get; set; }
}";
MarkupTestFile.GetPosition(generatedSourceMarkup, out var generatedSource, out int generatedSourcePosition);
VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), "D.cs", generatedSource, open: false);
// Switch to the main document we'll be editing
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");
// Verify that applying a Fix All operation does not change generated files.
// This is a regression test for correctness with respect to the design.
SetUpEditor(markup);
VisualStudio.WaitForApplicationIdle(CancellationToken.None);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Remove Unnecessary Usings",
applyFix: true,
fixAllScope: scope);
Assert.Equal(expectedText, VisualStudio.Editor.GetText());
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "D.cs");
Assert.Equal(generatedSource, VisualStudio.Editor.GetText());
// Verify that a Fix All in Document in the generated file still does nothing.
// ⚠ This is a statement of the current behavior, and not a claim regarding correctness of the design.
// The current behavior is observable; any change to this behavior should be part of an intentional design
// change.
VisualStudio.Editor.MoveCaret(generatedSourcePosition);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Remove Unnecessary Usings",
applyFix: true,
fixAllScope: FixAllScope.Document);
Assert.Equal(generatedSource, VisualStudio.Editor.GetText());
// Verify that the code action can still be applied manually from within the generated file.
// This is a regression test for correctness with respect to the design.
VisualStudio.Editor.MoveCaret(generatedSourcePosition);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Remove Unnecessary Usings",
applyFix: true,
fixAllScope: null);
Assert.Equal(expectedGeneratedSource, VisualStudio.Editor.GetText());
}
[CriticalWpfTheory]
[InlineData(FixAllScope.Project)]
[InlineData(FixAllScope.Solution)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
[WorkItem(33507, "https://github.com/dotnet/roslyn/issues/33507")]
public void FixAllOccurrencesTriggeredFromGeneratedCode(FixAllScope scope)
{
var markup = @"// <auto-generated/>
using System;
using $$System.Threading;
class C
{
public IntPtr X1 { get; set; }
}";
var secondFile = @"
using System;
using System.Threading;
class D
{
public IntPtr X1 { get; set; }
}";
var expectedSecondFile = @"
using System;
class D
{
public IntPtr X1 { get; set; }
}";
VisualStudio.SolutionExplorer.AddFile(new ProjectUtils.Project(ProjectName), "D.cs", secondFile, open: false);
// Switch to the main document we'll be editing
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "Class1.cs");
// Verify that applying a Fix All operation does not change generated file, but does change other files.
// ⚠ This is a statement of the current behavior, and not a claim regarding correctness of the design.
// The current behavior is observable; any change to this behavior should be part of an intentional design
// change.
MarkupTestFile.GetPosition(markup, out var expectedText, out int _);
SetUpEditor(markup);
VisualStudio.WaitForApplicationIdle(CancellationToken.None);
VisualStudio.Editor.InvokeCodeActionList();
VisualStudio.Editor.Verify.CodeAction(
"Remove Unnecessary Usings",
applyFix: true,
fixAllScope: scope);
Assert.Equal(expectedText, VisualStudio.Editor.GetText());
VisualStudio.SolutionExplorer.OpenFile(new ProjectUtils.Project(ProjectName), "D.cs");
Assert.Equal(expectedSecondFile, VisualStudio.Editor.GetText());
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public void ClassificationInPreviewPane()
{
SetUpEditor(@"
class Program
{
int Main()
{
Foo$$();
}
}");
VisualStudio.Editor.InvokeCodeActionList();
var classifiedTokens = GetLightbulbPreviewClassification("Generate method 'Program.Foo'");
Assert.True(classifiedTokens.Any(c => c.Text == "void" && c.Classification == "keyword"));
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public void AddUsingExactMatchBeforeRenameTracking()
{
SetUpEditor(@"
public class Program
{
static void Main(string[] args)
{
P2$$ p;
}
}
public class P2 { }");
VisualStudio.Editor.SendKeys(VirtualKey.Backspace, VirtualKey.Backspace, "Stream");
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"using System.IO;",
"Rename 'P2' to 'Stream'",
"System.IO.Stream",
"Generate class 'Stream' in new file",
"Generate class 'Stream'",
"Generate nested class 'Stream'",
"Generate new type...",
"Remove unused variable",
"Suppress or Configure issues",
"Suppress CS0168",
"in Source",
"Configure CS0168 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: expectedItems[0], ensureExpectedItemsAreOrdered: true);
VisualStudio.Editor.Verify.TextContains("using System.IO;");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)]
public void GFUFuzzyMatchAfterRenameTracking()
{
SetUpEditor(@"
namespace N
{
class Goober { }
}
namespace NS
{
public class P2
{
static void Main(string[] args)
{
P2$$ p;
}
}
}");
VisualStudio.Editor.SendKeys(VirtualKey.Backspace, VirtualKey.Backspace,
"Foober");
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"Rename 'P2' to 'Foober'",
"Generate type 'Foober'",
"Generate class 'Foober' in new file",
"Generate class 'Foober'",
"Generate nested class 'Foober'",
"Generate new type...",
"Goober - using N;",
"Suppress or Configure issues",
"Suppress CS0168",
"in Source",
"Configure CS0168 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: expectedItems[0], ensureExpectedItemsAreOrdered: true);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeGeneration)]
public void SuppressionAfterRefactorings()
{
SetUpEditor(@"
[System.Obsolete]
class C
{
}
class Program
{
static void Main(string[] args)
{
C p = $$2;
}
}");
VisualStudio.Editor.SelectTextInCurrentDocument("2");
VisualStudio.Editor.InvokeCodeActionList();
var generateImplicitTitle = "Generate implicit conversion operator in 'C'";
var expectedItems = new[]
{
"Introduce constant for '2'",
"Introduce constant for all occurrences of '2'",
"Introduce local constant for '2'",
"Introduce local constant for all occurrences of '2'",
"Extract method",
generateImplicitTitle,
"Suppress or Configure issues",
"Suppress CS0612",
"in Source",
"Configure CS0612 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: generateImplicitTitle, ensureExpectedItemsAreOrdered: true);
VisualStudio.Editor.Verify.TextContains("implicit");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public void OrderFixesByCursorProximityLeft()
{
SetUpEditor(@"
using System;
public class Program
{
static void Main(string[] args)
{
Byte[] bytes = null;
GCHandle$$ handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
}
}");
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"using System.Runtime.InteropServices;",
"System.Runtime.InteropServices.GCHandle"
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: expectedItems[0], ensureExpectedItemsAreOrdered: true);
VisualStudio.Editor.Verify.TextContains("using System.Runtime.InteropServices");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public void OrderFixesByCursorProximityRight()
{
SetUpEditor(@"
using System;
public class Program
{
static void Main(string[] args)
{
Byte[] bytes = null;
GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.$$Pinned);
}
}");
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"using System.Runtime.InteropServices;",
"System.Runtime.InteropServices.GCHandle"
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: expectedItems[0], ensureExpectedItemsAreOrdered: true);
VisualStudio.Editor.Verify.TextContains("using System.Runtime.InteropServices");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
public void ConfigureCodeStyleOptionValueAndSeverity()
{
SetUpEditor(@"
using System;
public class Program
{
static void Main(string[] args)
{
var $$x = new Program();
}
}");
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"Use discard '__'", // IDE0059
"Use explicit type instead of 'var'", // IDE0008
"Introduce local",
"Introduce local for 'new Program()'",
"Introduce local for all occurrences of 'new Program()'",
"Suppress or Configure issues",
"Configure IDE0008 code style",
"csharp__style__var__elsewhere",
"true",
"false",
"csharp__style__var__for__built__in__types",
"true",
"false",
"csharp__style__var__when__type__is__apparent",
"true",
"false",
"Configure IDE0008 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
"Suppress IDE0059",
"in Source",
"in Suppression File",
"in Source (attribute)",
"Configure IDE0059 code style",
"unused__local__variable",
"discard__variable",
"Configure IDE0059 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
"Configure severity for all 'Style' analyzers",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
"Configure severity for all analyzers",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, ensureExpectedItemsAreOrdered: true);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46784"), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)]
[WorkItem(46784, "https://github.com/dotnet/roslyn/issues/46784")]
public void ConfigureSeverity()
{
var markup = @"
class C
{
public static void Main()
{
// CS0168: The variable 'x' is declared but never used
int $$x;
}
}";
SetUpEditor(markup);
// Verify CS0168 warning in original code.
VerifyDiagnosticInErrorList("Warning", VisualStudio);
// Apply configuration severity fix to change CS0168 to be an error.
SetUpEditor(markup);
VisualStudio.Editor.InvokeCodeActionList();
var expectedItems = new[]
{
"Remove unused variable",
"Suppress or Configure issues",
"Suppress CS0168",
"in Source",
"Configure CS0168 severity",
"None",
"Silent",
"Suggestion",
"Warning",
"Error",
};
VisualStudio.Editor.Verify.CodeActions(expectedItems, applyFix: "Error", ensureExpectedItemsAreOrdered: true);
// Verify CS0168 is now reported as an error.
VerifyDiagnosticInErrorList("Error", VisualStudio);
return;
static void VerifyDiagnosticInErrorList(string expectedSeverity, VisualStudioInstance visualStudio)
{
visualStudio.ErrorList.ShowErrorList();
var expectedContents = new[] {
new ErrorListItem(
severity: expectedSeverity,
description: "The variable 'x' is declared but never used",
project: "TestProj",
fileName: "Class1.cs",
line: 7,
column: 13)
};
var actualContents = visualStudio.ErrorList.GetErrorListContents();
Assert.Equal(expectedContents, actualContents);
}
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/Core/Portable/Notification/GlobalOperationNotificationServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.CodeAnalysis.Notification
{
[ExportWorkspaceServiceFactory(typeof(IGlobalOperationNotificationService), ServiceLayer.Default), Shared]
internal class GlobalOperationNotificationServiceFactory : IWorkspaceServiceFactory
{
private readonly IAsynchronousOperationListener _listener;
private readonly IGlobalOperationNotificationService _singleton;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GlobalOperationNotificationServiceFactory(IAsynchronousOperationListenerProvider listenerProvider)
{
_listener = listenerProvider.GetListener(FeatureAttribute.GlobalOperation);
_singleton = new GlobalOperationNotificationService(_listener);
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> _singleton;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.CodeAnalysis.Notification
{
[ExportWorkspaceServiceFactory(typeof(IGlobalOperationNotificationService), ServiceLayer.Default), Shared]
internal class GlobalOperationNotificationServiceFactory : IWorkspaceServiceFactory
{
private readonly IAsynchronousOperationListener _listener;
private readonly IGlobalOperationNotificationService _singleton;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GlobalOperationNotificationServiceFactory(IAsynchronousOperationListenerProvider listenerProvider)
{
_listener = listenerProvider.GetListener(FeatureAttribute.GlobalOperation);
_singleton = new GlobalOperationNotificationService(_listener);
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> _singleton;
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.Sort.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.Sort.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Collections;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of the List class.
/// </summary>
public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T>
{
public static IEnumerable<object[]> ValidCollectionSizes_GreaterThanOne()
{
yield return new object[] { 2 };
yield return new object[] { 20 };
}
#region Sort
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_WithoutDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
IComparer<T> comparer = Comparer<T>.Default;
list.Sort();
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(comparer.Compare(list[i], list[i + 1]) < 0);
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_WithDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
list.Add(list[0]);
IComparer<T> comparer = Comparer<T>.Default;
list.Sort();
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(comparer.Compare(list[i], list[i + 1]) <= 0);
});
}
#endregion
#region Sort(IComparer)
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_IComparer_WithoutDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
IComparer<T> comparer = GetIComparer();
list.Sort(comparer);
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(comparer.Compare(list[i], list[i + 1]) < 0);
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_IComparer_WithDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
list.Add(list[0]);
IComparer<T> comparer = GetIComparer();
list.Sort(comparer);
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(comparer.Compare(list[i], list[i + 1]) <= 0);
});
}
#endregion
#region Sort(Comparison)
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_Comparison_WithoutDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
IComparer<T> iComparer = GetIComparer();
Comparison<T> comparer = ((T first, T second) => { return iComparer.Compare(first, second); });
list.Sort(comparer);
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(iComparer.Compare(list[i], list[i + 1]) < 0);
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_Comparison_WithDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
list.Add(list[0]);
IComparer<T> iComparer = GetIComparer();
Comparison<T> comparer = ((T first, T second) => { return iComparer.Compare(first, second); });
list.Sort(comparer);
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(iComparer.Compare(list[i], list[i + 1]) <= 0);
});
}
#endregion
#region Sort(int, int, IComparer<T>)
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_intintIComparer_WithoutDuplicates(int count)
{
SegmentedList<T> unsortedList = GenericListFactory(count);
IComparer<T> comparer = GetIComparer();
for (int startIndex = 0; startIndex < count - 2; startIndex++)
for (int sortCount = 1; sortCount < count - startIndex; sortCount++)
{
SegmentedList<T> list = new SegmentedList<T>(unsortedList);
list.Sort(startIndex, sortCount + 1, comparer);
for (int i = startIndex; i < sortCount; i++)
Assert.InRange(comparer.Compare(list[i], list[i + 1]), int.MinValue, 0);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_intintIComparer_WithDuplicates(int count)
{
SegmentedList<T> unsortedList = GenericListFactory(count);
IComparer<T> comparer = GetIComparer();
unsortedList.Add(unsortedList[0]);
for (int startIndex = 0; startIndex < count - 2; startIndex++)
for (int sortCount = 2; sortCount < count - startIndex; sortCount++)
{
SegmentedList<T> list = new SegmentedList<T>(unsortedList);
list.Sort(startIndex, sortCount + 1, comparer);
for (int i = startIndex; i < sortCount; i++)
Assert.InRange(comparer.Compare(list[i], list[i + 1]), int.MinValue, 1);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Sort_intintIComparer_NegativeRange_ThrowsArgumentOutOfRangeException(int count)
{
SegmentedList<T> list = GenericListFactory(count);
Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[]
{
Tuple.Create(-1,-1),
Tuple.Create(-1, 0),
Tuple.Create(-1, 1),
Tuple.Create(-1, 2),
Tuple.Create(-2, 0),
Tuple.Create(int.MinValue, 0),
Tuple.Create(0 ,-1),
Tuple.Create(0 ,-2),
Tuple.Create(0 , int.MinValue),
Tuple.Create(1 ,-1),
Tuple.Create(2 ,-1),
};
Assert.All(InvalidParameters, invalidSet =>
{
Assert.Throws<ArgumentOutOfRangeException>(() => list.Sort(invalidSet.Item1, invalidSet.Item2, GetIComparer()));
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Sort_intintIComparer_InvalidRange_ThrowsArgumentException(int count)
{
SegmentedList<T> list = GenericListFactory(count);
Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[]
{
Tuple.Create(count, 1),
Tuple.Create(count + 1, 0),
Tuple.Create(int.MaxValue, 0),
};
Assert.All(InvalidParameters, invalidSet =>
{
Assert.Throws<ArgumentException>(null, () => list.Sort(invalidSet.Item1, invalidSet.Item2, GetIComparer()));
});
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.Sort.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Collections;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of the List class.
/// </summary>
public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T>
{
public static IEnumerable<object[]> ValidCollectionSizes_GreaterThanOne()
{
yield return new object[] { 2 };
yield return new object[] { 20 };
}
#region Sort
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_WithoutDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
IComparer<T> comparer = Comparer<T>.Default;
list.Sort();
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(comparer.Compare(list[i], list[i + 1]) < 0);
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_WithDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
list.Add(list[0]);
IComparer<T> comparer = Comparer<T>.Default;
list.Sort();
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(comparer.Compare(list[i], list[i + 1]) <= 0);
});
}
#endregion
#region Sort(IComparer)
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_IComparer_WithoutDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
IComparer<T> comparer = GetIComparer();
list.Sort(comparer);
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(comparer.Compare(list[i], list[i + 1]) < 0);
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_IComparer_WithDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
list.Add(list[0]);
IComparer<T> comparer = GetIComparer();
list.Sort(comparer);
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(comparer.Compare(list[i], list[i + 1]) <= 0);
});
}
#endregion
#region Sort(Comparison)
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_Comparison_WithoutDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
IComparer<T> iComparer = GetIComparer();
Comparison<T> comparer = ((T first, T second) => { return iComparer.Compare(first, second); });
list.Sort(comparer);
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(iComparer.Compare(list[i], list[i + 1]) < 0);
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_Comparison_WithDuplicates(int count)
{
SegmentedList<T> list = GenericListFactory(count);
list.Add(list[0]);
IComparer<T> iComparer = GetIComparer();
Comparison<T> comparer = ((T first, T second) => { return iComparer.Compare(first, second); });
list.Sort(comparer);
Assert.All(Enumerable.Range(0, count - 2), i =>
{
Assert.True(iComparer.Compare(list[i], list[i + 1]) <= 0);
});
}
#endregion
#region Sort(int, int, IComparer<T>)
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_intintIComparer_WithoutDuplicates(int count)
{
SegmentedList<T> unsortedList = GenericListFactory(count);
IComparer<T> comparer = GetIComparer();
for (int startIndex = 0; startIndex < count - 2; startIndex++)
for (int sortCount = 1; sortCount < count - startIndex; sortCount++)
{
SegmentedList<T> list = new SegmentedList<T>(unsortedList);
list.Sort(startIndex, sortCount + 1, comparer);
for (int i = startIndex; i < sortCount; i++)
Assert.InRange(comparer.Compare(list[i], list[i + 1]), int.MinValue, 0);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes_GreaterThanOne))]
public void Sort_intintIComparer_WithDuplicates(int count)
{
SegmentedList<T> unsortedList = GenericListFactory(count);
IComparer<T> comparer = GetIComparer();
unsortedList.Add(unsortedList[0]);
for (int startIndex = 0; startIndex < count - 2; startIndex++)
for (int sortCount = 2; sortCount < count - startIndex; sortCount++)
{
SegmentedList<T> list = new SegmentedList<T>(unsortedList);
list.Sort(startIndex, sortCount + 1, comparer);
for (int i = startIndex; i < sortCount; i++)
Assert.InRange(comparer.Compare(list[i], list[i + 1]), int.MinValue, 1);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Sort_intintIComparer_NegativeRange_ThrowsArgumentOutOfRangeException(int count)
{
SegmentedList<T> list = GenericListFactory(count);
Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[]
{
Tuple.Create(-1,-1),
Tuple.Create(-1, 0),
Tuple.Create(-1, 1),
Tuple.Create(-1, 2),
Tuple.Create(-2, 0),
Tuple.Create(int.MinValue, 0),
Tuple.Create(0 ,-1),
Tuple.Create(0 ,-2),
Tuple.Create(0 , int.MinValue),
Tuple.Create(1 ,-1),
Tuple.Create(2 ,-1),
};
Assert.All(InvalidParameters, invalidSet =>
{
Assert.Throws<ArgumentOutOfRangeException>(() => list.Sort(invalidSet.Item1, invalidSet.Item2, GetIComparer()));
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void Sort_intintIComparer_InvalidRange_ThrowsArgumentException(int count)
{
SegmentedList<T> list = GenericListFactory(count);
Tuple<int, int>[] InvalidParameters = new Tuple<int, int>[]
{
Tuple.Create(count, 1),
Tuple.Create(count + 1, 0),
Tuple.Create(int.MaxValue, 0),
};
Assert.All(InvalidParameters, invalidSet =>
{
Assert.Throws<ArgumentException>(null, () => list.Sort(invalidSet.Item1, invalidSet.Item2, GetIComparer()));
});
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType
{
internal abstract class AbstractMoveTypeService : IMoveTypeService
{
/// <summary>
/// Annotation to mark the namespace encapsulating the type that has been moved
/// </summary>
public static SyntaxAnnotation NamespaceScopeMovedAnnotation = new(nameof(MoveTypeOperationKind.MoveTypeNamespaceScope));
public abstract Task<Solution> GetModifiedSolutionAsync(Document document, TextSpan textSpan, MoveTypeOperationKind operationKind, CancellationToken cancellationToken);
public abstract Task<ImmutableArray<CodeAction>> GetRefactoringAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
}
internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> :
AbstractMoveTypeService
where TService : AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax>
where TTypeDeclarationSyntax : SyntaxNode
where TNamespaceDeclarationSyntax : SyntaxNode
where TMemberDeclarationSyntax : SyntaxNode
where TCompilationUnitSyntax : SyntaxNode
{
public override async Task<ImmutableArray<CodeAction>> GetRefactoringAsync(
Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var state = await CreateStateAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return ImmutableArray<CodeAction>.Empty;
}
var actions = CreateActions(state, cancellationToken);
return actions;
}
public override async Task<Solution> GetModifiedSolutionAsync(Document document, TextSpan textSpan, MoveTypeOperationKind operationKind, CancellationToken cancellationToken)
{
var state = await CreateStateAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return document.Project.Solution;
}
var suggestedFileNames = GetSuggestedFileNames(
state.TypeNode,
IsNestedType(state.TypeNode),
state.TypeName,
state.SemanticDocument.Document.Name,
state.SemanticDocument.SemanticModel,
cancellationToken);
var editor = Editor.GetEditor(operationKind, (TService)this, state, suggestedFileNames.FirstOrDefault(), cancellationToken);
var modifiedSolution = await editor.GetModifiedSolutionAsync().ConfigureAwait(false);
return modifiedSolution ?? document.Project.Solution;
}
protected abstract Task<TTypeDeclarationSyntax> GetRelevantNodeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
private async Task<State> CreateStateAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var nodeToAnalyze = await GetRelevantNodeAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (nodeToAnalyze == null)
{
return null;
}
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
return State.Generate(semanticDocument, nodeToAnalyze, cancellationToken);
}
private ImmutableArray<CodeAction> CreateActions(State state, CancellationToken cancellationToken)
{
var typeMatchesDocumentName = TypeMatchesDocumentName(
state.TypeNode,
state.TypeName,
state.DocumentNameWithoutExtension,
state.SemanticDocument.SemanticModel,
cancellationToken);
if (typeMatchesDocumentName)
{
// if type name matches document name, per style conventions, we have nothing to do.
return ImmutableArray<CodeAction>.Empty;
}
using var _ = ArrayBuilder<CodeAction>.GetInstance(out var actions);
var manyTypes = MultipleTopLevelTypeDeclarationInSourceDocument(state.SemanticDocument.Root);
var isNestedType = IsNestedType(state.TypeNode);
var syntaxFacts = state.SemanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>();
var isClassNextToGlobalStatements = manyTypes
? false
: ClassNextToGlobalStatements(state.SemanticDocument.Root, syntaxFacts);
var suggestedFileNames = GetSuggestedFileNames(
state.TypeNode,
isNestedType,
state.TypeName,
state.SemanticDocument.Document.Name,
state.SemanticDocument.SemanticModel,
cancellationToken);
// (1) Add Move type to new file code action:
// case 1: There are multiple type declarations in current document. offer, move to new file.
// case 2: This is a nested type, offer to move to new file.
// case 3: If there is a single type decl in current file, *do not* offer move to new file,
// rename actions are sufficient in this case.
// case 4: If there are top level statements(Global statements) offer to move even
// in cases where there are only one class in the file.
if (manyTypes || isNestedType || isClassNextToGlobalStatements)
{
foreach (var fileName in suggestedFileNames)
{
actions.Add(GetCodeAction(state, fileName, operationKind: MoveTypeOperationKind.MoveType));
}
}
// (2) Add rename file and rename type code actions:
// Case: No type declaration in file matches the file name.
if (!AnyTopLevelTypeMatchesDocumentName(state, cancellationToken))
{
foreach (var fileName in suggestedFileNames)
{
actions.Add(GetCodeAction(state, fileName, operationKind: MoveTypeOperationKind.RenameFile));
}
// only if the document name can be legal identifier in the language,
// offer to rename type with document name
if (state.IsDocumentNameAValidIdentifier)
{
actions.Add(GetCodeAction(
state, fileName: state.DocumentNameWithoutExtension,
operationKind: MoveTypeOperationKind.RenameType));
}
}
Debug.Assert(actions.Count != 0, "No code actions found for MoveType Refactoring");
return actions.ToImmutable();
}
private static bool ClassNextToGlobalStatements(SyntaxNode root, ISyntaxFactsService syntaxFacts)
=> syntaxFacts.ContainsGlobalStatement(root);
private CodeAction GetCodeAction(State state, string fileName, MoveTypeOperationKind operationKind) =>
new MoveTypeCodeAction((TService)this, state, operationKind, fileName);
private static bool IsNestedType(TTypeDeclarationSyntax typeNode) =>
typeNode.Parent is TTypeDeclarationSyntax;
/// <summary>
/// checks if there is a single top level type declaration in a document
/// </summary>
/// <remarks>
/// optimized for perf, uses Skip(1).Any() instead of Count() > 1
/// </remarks>
private static bool MultipleTopLevelTypeDeclarationInSourceDocument(SyntaxNode root) =>
TopLevelTypeDeclarations(root).Skip(1).Any();
private static IEnumerable<TTypeDeclarationSyntax> TopLevelTypeDeclarations(SyntaxNode root) =>
root.DescendantNodes(n => n is TCompilationUnitSyntax or TNamespaceDeclarationSyntax)
.OfType<TTypeDeclarationSyntax>();
private static bool AnyTopLevelTypeMatchesDocumentName(State state, CancellationToken cancellationToken)
{
var root = state.SemanticDocument.Root;
var semanticModel = state.SemanticDocument.SemanticModel;
return TopLevelTypeDeclarations(root).Any(
typeDeclaration =>
{
var typeName = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken).Name;
return TypeMatchesDocumentName(
typeDeclaration, typeName, state.DocumentNameWithoutExtension,
semanticModel, cancellationToken);
});
}
/// <summary>
/// checks if type name matches its parent document name, per style rules.
/// </summary>
/// <remarks>
/// Note: For a nested type, a matching document name could be just the type name or a
/// dotted qualified name of its type hierarchy.
/// </remarks>
protected static bool TypeMatchesDocumentName(
TTypeDeclarationSyntax typeNode,
string typeName,
string documentNameWithoutExtension,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// If it is not a nested type, we compare the unqualified type name with the document name.
// If it is a nested type, the type name `Outer.Inner` matches file names `Inner.cs` and `Outer.Inner.cs`
var namesMatch = typeName.Equals(documentNameWithoutExtension, StringComparison.CurrentCulture);
if (!namesMatch)
{
var typeNameParts = GetTypeNamePartsForNestedTypeNode(typeNode, semanticModel, cancellationToken);
var fileNameParts = documentNameWithoutExtension.Split('.');
// qualified type name `Outer.Inner` matches file names `Inner.cs` and `Outer.Inner.cs`
return typeNameParts.SequenceEqual(fileNameParts, StringComparer.CurrentCulture);
}
return namesMatch;
}
private static ImmutableArray<string> GetSuggestedFileNames(
TTypeDeclarationSyntax typeNode,
bool isNestedType,
string typeName,
string documentNameWithExtension,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var fileExtension = Path.GetExtension(documentNameWithExtension);
var standaloneName = typeName + fileExtension;
// If it is a nested type, we should match type hierarchy's name parts with the file name.
if (isNestedType)
{
var typeNameParts = GetTypeNamePartsForNestedTypeNode(typeNode, semanticModel, cancellationToken);
var dottedName = typeNameParts.Join(".") + fileExtension;
return ImmutableArray.Create(standaloneName, dottedName);
}
else
{
return ImmutableArray.Create(standaloneName);
}
}
private static IEnumerable<string> GetTypeNamePartsForNestedTypeNode(
TTypeDeclarationSyntax typeNode, SemanticModel semanticModel, CancellationToken cancellationToken) =>
typeNode.AncestorsAndSelf()
.OfType<TTypeDeclarationSyntax>()
.Select(n => semanticModel.GetDeclaredSymbol(n, cancellationToken).Name)
.Reverse();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType
{
internal abstract class AbstractMoveTypeService : IMoveTypeService
{
/// <summary>
/// Annotation to mark the namespace encapsulating the type that has been moved
/// </summary>
public static SyntaxAnnotation NamespaceScopeMovedAnnotation = new(nameof(MoveTypeOperationKind.MoveTypeNamespaceScope));
public abstract Task<Solution> GetModifiedSolutionAsync(Document document, TextSpan textSpan, MoveTypeOperationKind operationKind, CancellationToken cancellationToken);
public abstract Task<ImmutableArray<CodeAction>> GetRefactoringAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
}
internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> :
AbstractMoveTypeService
where TService : AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax>
where TTypeDeclarationSyntax : SyntaxNode
where TNamespaceDeclarationSyntax : SyntaxNode
where TMemberDeclarationSyntax : SyntaxNode
where TCompilationUnitSyntax : SyntaxNode
{
public override async Task<ImmutableArray<CodeAction>> GetRefactoringAsync(
Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var state = await CreateStateAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return ImmutableArray<CodeAction>.Empty;
}
var actions = CreateActions(state, cancellationToken);
return actions;
}
public override async Task<Solution> GetModifiedSolutionAsync(Document document, TextSpan textSpan, MoveTypeOperationKind operationKind, CancellationToken cancellationToken)
{
var state = await CreateStateAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (state == null)
{
return document.Project.Solution;
}
var suggestedFileNames = GetSuggestedFileNames(
state.TypeNode,
IsNestedType(state.TypeNode),
state.TypeName,
state.SemanticDocument.Document.Name,
state.SemanticDocument.SemanticModel,
cancellationToken);
var editor = Editor.GetEditor(operationKind, (TService)this, state, suggestedFileNames.FirstOrDefault(), cancellationToken);
var modifiedSolution = await editor.GetModifiedSolutionAsync().ConfigureAwait(false);
return modifiedSolution ?? document.Project.Solution;
}
protected abstract Task<TTypeDeclarationSyntax> GetRelevantNodeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
private async Task<State> CreateStateAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var nodeToAnalyze = await GetRelevantNodeAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
if (nodeToAnalyze == null)
{
return null;
}
var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
return State.Generate(semanticDocument, nodeToAnalyze, cancellationToken);
}
private ImmutableArray<CodeAction> CreateActions(State state, CancellationToken cancellationToken)
{
var typeMatchesDocumentName = TypeMatchesDocumentName(
state.TypeNode,
state.TypeName,
state.DocumentNameWithoutExtension,
state.SemanticDocument.SemanticModel,
cancellationToken);
if (typeMatchesDocumentName)
{
// if type name matches document name, per style conventions, we have nothing to do.
return ImmutableArray<CodeAction>.Empty;
}
using var _ = ArrayBuilder<CodeAction>.GetInstance(out var actions);
var manyTypes = MultipleTopLevelTypeDeclarationInSourceDocument(state.SemanticDocument.Root);
var isNestedType = IsNestedType(state.TypeNode);
var syntaxFacts = state.SemanticDocument.Document.GetRequiredLanguageService<ISyntaxFactsService>();
var isClassNextToGlobalStatements = manyTypes
? false
: ClassNextToGlobalStatements(state.SemanticDocument.Root, syntaxFacts);
var suggestedFileNames = GetSuggestedFileNames(
state.TypeNode,
isNestedType,
state.TypeName,
state.SemanticDocument.Document.Name,
state.SemanticDocument.SemanticModel,
cancellationToken);
// (1) Add Move type to new file code action:
// case 1: There are multiple type declarations in current document. offer, move to new file.
// case 2: This is a nested type, offer to move to new file.
// case 3: If there is a single type decl in current file, *do not* offer move to new file,
// rename actions are sufficient in this case.
// case 4: If there are top level statements(Global statements) offer to move even
// in cases where there are only one class in the file.
if (manyTypes || isNestedType || isClassNextToGlobalStatements)
{
foreach (var fileName in suggestedFileNames)
{
actions.Add(GetCodeAction(state, fileName, operationKind: MoveTypeOperationKind.MoveType));
}
}
// (2) Add rename file and rename type code actions:
// Case: No type declaration in file matches the file name.
if (!AnyTopLevelTypeMatchesDocumentName(state, cancellationToken))
{
foreach (var fileName in suggestedFileNames)
{
actions.Add(GetCodeAction(state, fileName, operationKind: MoveTypeOperationKind.RenameFile));
}
// only if the document name can be legal identifier in the language,
// offer to rename type with document name
if (state.IsDocumentNameAValidIdentifier)
{
actions.Add(GetCodeAction(
state, fileName: state.DocumentNameWithoutExtension,
operationKind: MoveTypeOperationKind.RenameType));
}
}
Debug.Assert(actions.Count != 0, "No code actions found for MoveType Refactoring");
return actions.ToImmutable();
}
private static bool ClassNextToGlobalStatements(SyntaxNode root, ISyntaxFactsService syntaxFacts)
=> syntaxFacts.ContainsGlobalStatement(root);
private CodeAction GetCodeAction(State state, string fileName, MoveTypeOperationKind operationKind) =>
new MoveTypeCodeAction((TService)this, state, operationKind, fileName);
private static bool IsNestedType(TTypeDeclarationSyntax typeNode) =>
typeNode.Parent is TTypeDeclarationSyntax;
/// <summary>
/// checks if there is a single top level type declaration in a document
/// </summary>
/// <remarks>
/// optimized for perf, uses Skip(1).Any() instead of Count() > 1
/// </remarks>
private static bool MultipleTopLevelTypeDeclarationInSourceDocument(SyntaxNode root) =>
TopLevelTypeDeclarations(root).Skip(1).Any();
private static IEnumerable<TTypeDeclarationSyntax> TopLevelTypeDeclarations(SyntaxNode root) =>
root.DescendantNodes(n => n is TCompilationUnitSyntax or TNamespaceDeclarationSyntax)
.OfType<TTypeDeclarationSyntax>();
private static bool AnyTopLevelTypeMatchesDocumentName(State state, CancellationToken cancellationToken)
{
var root = state.SemanticDocument.Root;
var semanticModel = state.SemanticDocument.SemanticModel;
return TopLevelTypeDeclarations(root).Any(
typeDeclaration =>
{
var typeName = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken).Name;
return TypeMatchesDocumentName(
typeDeclaration, typeName, state.DocumentNameWithoutExtension,
semanticModel, cancellationToken);
});
}
/// <summary>
/// checks if type name matches its parent document name, per style rules.
/// </summary>
/// <remarks>
/// Note: For a nested type, a matching document name could be just the type name or a
/// dotted qualified name of its type hierarchy.
/// </remarks>
protected static bool TypeMatchesDocumentName(
TTypeDeclarationSyntax typeNode,
string typeName,
string documentNameWithoutExtension,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
// If it is not a nested type, we compare the unqualified type name with the document name.
// If it is a nested type, the type name `Outer.Inner` matches file names `Inner.cs` and `Outer.Inner.cs`
var namesMatch = typeName.Equals(documentNameWithoutExtension, StringComparison.CurrentCulture);
if (!namesMatch)
{
var typeNameParts = GetTypeNamePartsForNestedTypeNode(typeNode, semanticModel, cancellationToken);
var fileNameParts = documentNameWithoutExtension.Split('.');
// qualified type name `Outer.Inner` matches file names `Inner.cs` and `Outer.Inner.cs`
return typeNameParts.SequenceEqual(fileNameParts, StringComparer.CurrentCulture);
}
return namesMatch;
}
private static ImmutableArray<string> GetSuggestedFileNames(
TTypeDeclarationSyntax typeNode,
bool isNestedType,
string typeName,
string documentNameWithExtension,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var fileExtension = Path.GetExtension(documentNameWithExtension);
var standaloneName = typeName + fileExtension;
// If it is a nested type, we should match type hierarchy's name parts with the file name.
if (isNestedType)
{
var typeNameParts = GetTypeNamePartsForNestedTypeNode(typeNode, semanticModel, cancellationToken);
var dottedName = typeNameParts.Join(".") + fileExtension;
return ImmutableArray.Create(standaloneName, dottedName);
}
else
{
return ImmutableArray.Create(standaloneName);
}
}
private static IEnumerable<string> GetTypeNamePartsForNestedTypeNode(
TTypeDeclarationSyntax typeNode, SemanticModel semanticModel, CancellationToken cancellationToken) =>
typeNode.AncestorsAndSelf()
.OfType<TTypeDeclarationSyntax>()
.Select(n => semanticModel.GetDeclaredSymbol(n, cancellationToken).Name)
.Reverse();
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/DoKeywordRecommender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Do" keyword at the start of a statement
''' </summary>
Friend Class DoKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsMultiLineStatementContext Then
Return ImmutableArray.Create(
New RecommendedKeyword("Do", VBFeaturesResources.Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_or_until_the_condition_becomes_true_Do_Loop_While_Until_condition),
New RecommendedKeyword("Do Until", VBFeaturesResources.Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Until_condition_Loop),
New RecommendedKeyword("Do While", VBFeaturesResources.Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_While_condition_Loop))
End If
' Are we after Exit or Continue?
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
If targetToken.IsKind(SyntaxKind.ExitKeyword, SyntaxKind.ContinueKeyword) AndAlso
context.IsInStatementBlockOfKind(SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock,
SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock) AndAlso
Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then
If targetToken.IsKind(SyntaxKind.ExitKeyword) Then
Return ImmutableArray.Create(New RecommendedKeyword("Do", VBFeaturesResources.Exits_a_Do_loop_and_transfers_execution_immediately_to_the_statement_following_the_Loop_statement))
Else
Return ImmutableArray.Create(New RecommendedKeyword("Do", VBFeaturesResources.Transfers_execution_immediately_to_the_next_iteration_of_the_Do_loop))
End If
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
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.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements
''' <summary>
''' Recommends the "Do" keyword at the start of a statement
''' </summary>
Friend Class DoKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
If context.IsMultiLineStatementContext Then
Return ImmutableArray.Create(
New RecommendedKeyword("Do", VBFeaturesResources.Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_or_until_the_condition_becomes_true_Do_Loop_While_Until_condition),
New RecommendedKeyword("Do Until", VBFeaturesResources.Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Until_condition_Loop),
New RecommendedKeyword("Do While", VBFeaturesResources.Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_While_condition_Loop))
End If
' Are we after Exit or Continue?
If context.FollowsEndOfStatement Then
Return ImmutableArray(Of RecommendedKeyword).Empty
End If
Dim targetToken = context.TargetToken
If targetToken.IsKind(SyntaxKind.ExitKeyword, SyntaxKind.ContinueKeyword) AndAlso
context.IsInStatementBlockOfKind(SyntaxKind.SimpleDoLoopBlock,
SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock,
SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock) AndAlso
Not context.IsInStatementBlockOfKind(SyntaxKind.FinallyBlock) Then
If targetToken.IsKind(SyntaxKind.ExitKeyword) Then
Return ImmutableArray.Create(New RecommendedKeyword("Do", VBFeaturesResources.Exits_a_Do_loop_and_transfers_execution_immediately_to_the_statement_following_the_Loop_statement))
Else
Return ImmutableArray.Create(New RecommendedKeyword("Do", VBFeaturesResources.Transfers_execution_immediately_to_the_next_iteration_of_the_Do_loop))
End If
End If
Return ImmutableArray(Of RecommendedKeyword).Empty
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Test/Emit/CodeGen/UnsafeTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class UnsafeTests : EmitMetadataTestBase
{
#region AddressOf tests
[Fact]
public void AddressOfLocal_Unused()
{
var text = @"
unsafe class C
{
void M()
{
int x;
int* p = &x;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes);
compVerifier.VerifyIL("C.M", @"
{
// Code size 4 (0x4)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldloca.s V_0
IL_0002: pop
IL_0003: ret
}
");
}
[Fact]
public void AddressOfLocal_Used()
{
var text = @"
unsafe class C
{
void M(int* param)
{
int x;
int* p = &x;
M(p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 2
.locals init (int V_0, //x
int* V_1) //p
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldarg.0
IL_0005: ldloc.1
IL_0006: call ""void C.M(int*)""
IL_000b: ret
}
");
}
[Fact]
public void AddressOfParameter_Unused()
{
var text = @"
unsafe class C
{
void M(int x)
{
int* p = &x;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes);
compVerifier.VerifyIL("C.M", @"
{
// Code size 4 (0x4)
.maxstack 1
IL_0000: ldarga.s V_1
IL_0002: pop
IL_0003: ret
}
");
}
[Fact]
public void AddressOfParameter_Used()
{
var text = @"
unsafe class C
{
void M(int x, int* param)
{
int* p = &x;
M(x, p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 13 (0xd)
.maxstack 3
.locals init (int* V_0) //p
IL_0000: ldarga.s V_1
IL_0002: conv.u
IL_0003: stloc.0
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: ldloc.0
IL_0007: call ""void C.M(int, int*)""
IL_000c: ret
}
");
}
[Fact]
public void AddressOfStructField()
{
var text = @"
unsafe class C
{
void M()
{
S1 s;
S1* p1 = &s;
S2* p2 = &s.s;
int* p3 = &s.s.x;
Goo(s, p1, p2, p3);
}
void Goo(S1 s, S1* p1, S2* p2, int* p3) { }
}
struct S1
{
public S2 s;
}
struct S2
{
public int x;
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 38 (0x26)
.maxstack 5
.locals init (S1 V_0, //s
S1* V_1, //p1
S2* V_2, //p2
int* V_3) //p3
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: ldflda ""S2 S1.s""
IL_000b: conv.u
IL_000c: stloc.2
IL_000d: ldloca.s V_0
IL_000f: ldflda ""S2 S1.s""
IL_0014: ldflda ""int S2.x""
IL_0019: conv.u
IL_001a: stloc.3
IL_001b: ldarg.0
IL_001c: ldloc.0
IL_001d: ldloc.1
IL_001e: ldloc.2
IL_001f: ldloc.3
IL_0020: call ""void C.Goo(S1, S1*, S2*, int*)""
IL_0025: ret
}
");
}
[Fact]
public void AddressOfSuppressOptimization()
{
var text = @"
unsafe class C
{
static void M()
{
int x = 123;
Goo(&x); // should not optimize into 'Goo(&123)'
}
static void Goo(int* p) { }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: call ""void C.Goo(int*)""
IL_000b: ret
}
");
}
#endregion AddressOf tests
#region Dereference tests
[Fact]
public void DereferenceLocal()
{
var text = @"
unsafe class C
{
static void Main()
{
int x = 123;
int* p = &x;
System.Console.WriteLine(*p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "123", verify: Verification.Fails);
// NOTE: p is optimized away, but & and * aren't.
compVerifier.VerifyIL("C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: ldind.i4
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ret
}
");
}
[Fact]
public void DereferenceParameter()
{
var text = @"
unsafe class C
{
static void Main()
{
long x = 456;
System.Console.WriteLine(Dereference(&x));
}
static long Dereference(long* p)
{
return *p;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "456", verify: Verification.Fails);
compVerifier.VerifyIL("C.Dereference", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldind.i8
IL_0002: ret
}
");
}
[Fact]
public void DereferenceWrite()
{
var text = @"
unsafe class C
{
static void Main()
{
int x = 1;
int* p = &x;
*p = 2;
System.Console.WriteLine(x);
}
}
";
var compVerifierOptimized = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "2", verify: Verification.Fails);
// NOTE: p is optimized away, but & and * aren't.
compVerifierOptimized.VerifyIL("C.Main", @"
{
// Code size 14 (0xe)
.maxstack 2
.locals init (int V_0) //x
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: conv.u
IL_0005: ldc.i4.2
IL_0006: stind.i4
IL_0007: ldloc.0
IL_0008: call ""void System.Console.WriteLine(int)""
IL_000d: ret
}
");
var compVerifierUnoptimized = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: "2", verify: Verification.Fails);
compVerifierUnoptimized.VerifyIL("C.Main", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (int V_0, //x
int* V_1) //p
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.2
IL_0009: stind.i4
IL_000a: ldloc.0
IL_000b: call ""void System.Console.WriteLine(int)""
IL_0010: nop
IL_0011: ret
}
");
}
[Fact]
public void DereferenceStruct()
{
var text = @"
unsafe struct S
{
S* p;
byte x;
static void Main()
{
S s;
S* sp = &s;
(*sp).p = sp;
(*sp).x = 1;
System.Console.WriteLine((*(s.p)).x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (S V_0, //s
S* V_1) //sp
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldloc.1
IL_0005: ldloc.1
IL_0006: stfld ""S* S.p""
IL_000b: ldloc.1
IL_000c: ldc.i4.1
IL_000d: stfld ""byte S.x""
IL_0012: ldloc.0
IL_0013: ldfld ""S* S.p""
IL_0018: ldfld ""byte S.x""
IL_001d: call ""void System.Console.WriteLine(int)""
IL_0022: ret
}
");
}
[Fact]
public void DereferenceSwap()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
byte b1 = 2;
byte b2 = 7;
Console.WriteLine(""Before: {0} {1}"", b1, b2);
Swap(&b1, &b2);
Console.WriteLine(""After: {0} {1}"", b1, b2);
}
static void Swap(byte* p1, byte* p2)
{
byte tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"Before: 2 7
After: 7 2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Swap", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (byte V_0) //tmp
IL_0000: ldarg.0
IL_0001: ldind.u1
IL_0002: stloc.0
IL_0003: ldarg.0
IL_0004: ldarg.1
IL_0005: ldind.u1
IL_0006: stind.i1
IL_0007: ldarg.1
IL_0008: ldloc.0
IL_0009: stind.i1
IL_000a: ret
}
");
}
[Fact]
public void DereferenceIsLValue1()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
char c = 'a';
char* p = &c;
Console.Write(c);
Incr(ref *p);
Console.Write(c);
}
static void Incr(ref char c)
{
c++;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"ab", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (char V_0) //c
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: ldloc.0
IL_0007: call ""void System.Console.Write(char)""
IL_000c: call ""void C.Incr(ref char)""
IL_0011: ldloc.0
IL_0012: call ""void System.Console.Write(char)""
IL_0017: ret
}
");
}
[Fact]
public void DereferenceIsLValue2()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 1;
S* p = &s;
Console.Write(s.x);
(*p).Mutate();
Console.Write(s.x);
}
void Mutate()
{
x++;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: call ""void S.Mutate()""
IL_001b: ldloc.0
IL_001c: ldfld ""int S.x""
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ret
}
");
}
#endregion Dereference tests
#region Pointer member access tests
[Fact]
public void PointerMemberAccessRead()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write(p->x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldfld ""int S.x""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldfld ""int S.x""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
}
");
}
[Fact]
public void PointerMemberAccessWrite()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write(s.x);
p->x = 4;
Console.Write(s.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: ldc.i4.4
IL_0017: stfld ""int S.x""
IL_001c: ldloc.0
IL_001d: ldfld ""int S.x""
IL_0022: call ""void System.Console.Write(int)""
IL_0027: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: ldc.i4.4
IL_0017: stfld ""int S.x""
IL_001c: ldloc.0
IL_001d: ldfld ""int S.x""
IL_0022: call ""void System.Console.Write(int)""
IL_0027: ret
}
");
}
[Fact]
public void PointerMemberAccessInvoke()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s;
S* p = &s;
p->M();
p->M(1);
p->M(1, 2);
}
void M() { Console.Write(1); }
void M(int x) { Console.Write(2); }
}
static class Extensions
{
public static void M(this S s, int x, int y) { Console.Write(3); }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: dup
IL_0004: call ""void S.M()""
IL_0009: dup
IL_000a: ldc.i4.1
IL_000b: call ""void S.M(int)""
IL_0010: ldobj ""S""
IL_0015: ldc.i4.1
IL_0016: ldc.i4.2
IL_0017: call ""void Extensions.M(S, int, int)""
IL_001c: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: dup
IL_0004: call ""void S.M()""
IL_0009: dup
IL_000a: ldc.i4.1
IL_000b: call ""void S.M(int)""
IL_0010: ldobj ""S""
IL_0015: ldc.i4.1
IL_0016: ldc.i4.2
IL_0017: call ""void Extensions.M(S, int, int)""
IL_001c: ret
}
");
}
[Fact]
public void PointerMemberAccessInvoke001()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s;
S* p = &s;
Test(ref p);
}
static void Test(ref S* p)
{
p->M();
p->M(1);
p->M(1, 2);
}
void M() { Console.Write(1); }
void M(int x) { Console.Write(2); }
}
static class Extensions
{
public static void M(this S s, int x, int y) { Console.Write(3); }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Test(ref S*)", @"
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldind.i
IL_0002: call ""void S.M()""
IL_0007: ldarg.0
IL_0008: ldind.i
IL_0009: ldc.i4.1
IL_000a: call ""void S.M(int)""
IL_000f: ldarg.0
IL_0010: ldind.i
IL_0011: ldobj ""S""
IL_0016: ldc.i4.1
IL_0017: ldc.i4.2
IL_0018: call ""void Extensions.M(S, int, int)""
IL_001d: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Test(ref S*)", @"
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldind.i
IL_0002: call ""void S.M()""
IL_0007: ldarg.0
IL_0008: ldind.i
IL_0009: ldc.i4.1
IL_000a: call ""void S.M(int)""
IL_000f: ldarg.0
IL_0010: ldind.i
IL_0011: ldobj ""S""
IL_0016: ldc.i4.1
IL_0017: ldc.i4.2
IL_0018: call ""void Extensions.M(S, int, int)""
IL_001d: ret
}
");
}
[Fact]
public void PointerMemberAccessMutate()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write((p->x)++);
Console.Write((p->x)++);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (S V_0, //s
int V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: ldflda ""int S.x""
IL_0011: dup
IL_0012: ldind.i4
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: add
IL_0017: stind.i4
IL_0018: ldloc.1
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldflda ""int S.x""
IL_0023: dup
IL_0024: ldind.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: stind.i4
IL_002a: ldloc.1
IL_002b: call ""void System.Console.Write(int)""
IL_0030: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (S V_0, //s
int V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: ldflda ""int S.x""
IL_0011: dup
IL_0012: ldind.i4
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: add
IL_0017: stind.i4
IL_0018: ldloc.1
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldflda ""int S.x""
IL_0023: dup
IL_0024: ldind.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: stind.i4
IL_002a: ldloc.1
IL_002b: call ""void System.Console.Write(int)""
IL_0030: ret
}
");
}
#endregion Pointer member access tests
#region Pointer element access tests
[Fact]
public void PointerElementAccessCheckedAndUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s = new S();
S* p = &s;
int i = (int)p;
uint ui = (uint)p;
long l = (long)p;
ulong ul = (ulong)p;
checked
{
s = p[i];
s = p[ui];
s = p[l];
s = p[ul];
}
unchecked
{
s = p[i];
s = p[ui];
s = p[l];
s = p[ul];
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
// The conversions differ from dev10 in the same way as for numeric addition.
// Note that, unlike for numeric addition, the add operation is never checked.
compVerifier.VerifyIL("S.Main", @"
{
// Code size 170 (0xaa)
.maxstack 4
.locals init (S V_0, //s
int V_1, //i
uint V_2, //ui
long V_3, //l
ulong V_4) //ul
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: conv.i4
IL_000d: stloc.1
IL_000e: dup
IL_000f: conv.u4
IL_0010: stloc.2
IL_0011: dup
IL_0012: conv.u8
IL_0013: stloc.3
IL_0014: dup
IL_0015: conv.u8
IL_0016: stloc.s V_4
IL_0018: dup
IL_0019: ldloc.1
IL_001a: conv.i
IL_001b: sizeof ""S""
IL_0021: mul.ovf
IL_0022: add
IL_0023: ldobj ""S""
IL_0028: stloc.0
IL_0029: dup
IL_002a: ldloc.2
IL_002b: conv.u8
IL_002c: sizeof ""S""
IL_0032: conv.i8
IL_0033: mul.ovf
IL_0034: conv.i
IL_0035: add
IL_0036: ldobj ""S""
IL_003b: stloc.0
IL_003c: dup
IL_003d: ldloc.3
IL_003e: sizeof ""S""
IL_0044: conv.i8
IL_0045: mul.ovf
IL_0046: conv.i
IL_0047: add
IL_0048: ldobj ""S""
IL_004d: stloc.0
IL_004e: dup
IL_004f: ldloc.s V_4
IL_0051: sizeof ""S""
IL_0057: conv.ovf.u8
IL_0058: mul.ovf.un
IL_0059: conv.u
IL_005a: add
IL_005b: ldobj ""S""
IL_0060: stloc.0
IL_0061: dup
IL_0062: ldloc.1
IL_0063: conv.i
IL_0064: sizeof ""S""
IL_006a: mul
IL_006b: add
IL_006c: ldobj ""S""
IL_0071: stloc.0
IL_0072: dup
IL_0073: ldloc.2
IL_0074: conv.u8
IL_0075: sizeof ""S""
IL_007b: conv.i8
IL_007c: mul
IL_007d: conv.i
IL_007e: add
IL_007f: ldobj ""S""
IL_0084: stloc.0
IL_0085: dup
IL_0086: ldloc.3
IL_0087: sizeof ""S""
IL_008d: conv.i8
IL_008e: mul
IL_008f: conv.i
IL_0090: add
IL_0091: ldobj ""S""
IL_0096: stloc.0
IL_0097: ldloc.s V_4
IL_0099: sizeof ""S""
IL_009f: conv.i8
IL_00a0: mul
IL_00a1: conv.u
IL_00a2: add
IL_00a3: ldobj ""S""
IL_00a8: stloc.0
IL_00a9: ret
}
");
}
[Fact]
public void PointerElementAccessWrite()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int* p = null;
p[1] = 2;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 9 (0x9)
.maxstack 2
.locals init (int* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.4
IL_0005: add
IL_0006: ldc.i4.2
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void PointerElementAccessMutate()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int[] array = new int[3];
fixed (int* p = array)
{
p[1] += ++p[0];
p[2] -= p[1]--;
}
foreach (int element in array)
{
Console.WriteLine(element);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
1
0
-1", verify: Verification.Fails);
}
[Fact]
public void PointerElementAccessNested()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
fixed (int* q = new int[3])
{
q[0] = 2;
q[1] = 0;
q[2] = 1;
Console.Write(q[q[q[q[q[q[*q]]]]]]);
Console.Write(q[q[q[q[q[q[q[*q]]]]]]]);
Console.Write(q[q[q[q[q[q[q[q[*q]]]]]]]]);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "210", verify: Verification.Fails);
}
[Fact]
public void PointerElementAccessZero()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int x = 1;
int* p = &x;
Console.WriteLine(p[0]);
}
}
";
// NOTE: no pointer arithmetic - just dereference p.
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: conv.u
IL_0005: ldind.i4
IL_0006: call ""void System.Console.WriteLine(int)""
IL_000b: ret
}
");
}
#endregion Pointer element access tests
#region Fixed statement tests
[Fact]
public void FixedStatementField()
{
var text = @"
using System;
unsafe class C
{
int x;
static void Main()
{
C c = new C();
fixed (int* p = &c.x)
{
*p = 1;
}
Console.WriteLine(c.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"1", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 30 (0x1e)
.maxstack 3
.locals init (pinned int& V_0)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: ldc.i4.1
IL_000f: stind.i4
IL_0010: ldc.i4.0
IL_0011: conv.u
IL_0012: stloc.0
IL_0013: ldfld ""int C.x""
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ret
}
");
}
[Fact]
public void FixedStatementThis()
{
var text = @"
public class Program
{
public static void Main()
{
S1 s = default;
s.Test();
}
unsafe readonly struct S1
{
readonly int x;
public void Test()
{
fixed(void* p = &this)
{
*(int*)p = 123;
}
ref readonly S1 r = ref this;
fixed (S1* p = &r)
{
System.Console.WriteLine(p->x);
}
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("Program.S1.Test()", @"
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (void* V_0, //p
pinned Program.S1& V_1)
IL_0000: ldarg.0
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: conv.u
IL_0004: stloc.0
IL_0005: ldloc.0
IL_0006: ldc.i4.s 123
IL_0008: stind.i4
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldarg.0
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: ldfld ""int Program.S1.x""
IL_0015: call ""void System.Console.WriteLine(int)""
IL_001a: ldc.i4.0
IL_001b: conv.u
IL_001c: stloc.1
IL_001d: ret
}
");
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[Fact]
public void FixedStatementMultipleFields()
{
var text = @"
using System;
unsafe class C
{
int x;
readonly int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldflda ""int C.y""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: stind.i4
IL_001b: ldc.i4.2
IL_001c: stind.i4
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.2
IL_0023: dup
IL_0024: ldfld ""int C.x""
IL_0029: call ""void System.Console.Write(int)""
IL_002e: ldfld ""int C.y""
IL_0033: call ""void System.Console.Write(int)""
IL_0038: ret
}
");
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[Fact]
public void FixedStatementMultipleMethods()
{
var text = @"
using System;
unsafe class C
{
int x;
readonly int y;
ref int X()=>ref x;
ref readonly int this[int i]=>ref y;
static void Main()
{
C c = new C();
fixed (int* p = &c.X(), q = &c[3])
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 58 (0x3a)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: callvirt ""ref int C.X()""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldc.i4.3
IL_0011: callvirt ""ref readonly int C.this[int].get""
IL_0016: stloc.2
IL_0017: ldloc.2
IL_0018: conv.u
IL_0019: ldloc.0
IL_001a: ldc.i4.1
IL_001b: stind.i4
IL_001c: ldc.i4.2
IL_001d: stind.i4
IL_001e: ldc.i4.0
IL_001f: conv.u
IL_0020: stloc.1
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.2
IL_0024: dup
IL_0025: ldfld ""int C.x""
IL_002a: call ""void System.Console.Write(int)""
IL_002f: ldfld ""int C.y""
IL_0034: call ""void System.Console.Write(int)""
IL_0039: ret
}
");
}
[WorkItem(546866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546866")]
[Fact]
public void FixedStatementProperty()
{
var text =
@"class C
{
string P { get { return null; } }
char[] Q { get { return null; } }
unsafe static void M(C c)
{
fixed (char* o = c.P)
{
}
fixed (char* o = c.Q)
{
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M(C)",
@"
{
// Code size 55 (0x37)
.maxstack 2
.locals init (char* V_0, //o
pinned string V_1,
char* V_2, //o
pinned char[] V_3)
IL_0000: ldarg.0
IL_0001: callvirt ""string C.P.get""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: stloc.1
IL_0017: ldarg.0
IL_0018: callvirt ""char[] C.Q.get""
IL_001d: dup
IL_001e: stloc.3
IL_001f: brfalse.s IL_0026
IL_0021: ldloc.3
IL_0022: ldlen
IL_0023: conv.i4
IL_0024: brtrue.s IL_002b
IL_0026: ldc.i4.0
IL_0027: conv.u
IL_0028: stloc.2
IL_0029: br.s IL_0034
IL_002b: ldloc.3
IL_002c: ldc.i4.0
IL_002d: ldelema ""char""
IL_0032: conv.u
IL_0033: stloc.2
IL_0034: ldnull
IL_0035: stloc.3
IL_0036: ret
}
");
}
[Fact]
public void FixedStatementMultipleOptimized()
{
var text = @"
using System;
unsafe class C
{
int x;
int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldflda ""int C.y""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: stind.i4
IL_001b: ldc.i4.2
IL_001c: stind.i4
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.2
IL_0023: dup
IL_0024: ldfld ""int C.x""
IL_0029: call ""void System.Console.Write(int)""
IL_002e: ldfld ""int C.y""
IL_0033: call ""void System.Console.Write(int)""
IL_0038: ret
}
");
}
[Fact]
public void FixedStatementReferenceParameter()
{
var text = @"
using System;
class C
{
static void Main()
{
char ch;
M(out ch);
Console.WriteLine(ch);
}
unsafe static void M(out char ch)
{
fixed (char* p = &ch)
{
*p = 'a';
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"a", verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: conv.u
IL_0004: ldc.i4.s 97
IL_0006: stind.i2
IL_0007: ldc.i4.0
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ret
}
");
}
[Fact]
public void FixedStatementReferenceParameterDebug()
{
var text = @"
using System;
class C
{
static void Main()
{
char ch;
M(out ch);
Console.WriteLine(ch);
}
unsafe static void M(out char ch)
{
fixed (char* p = &ch)
{
*p = 'a';
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"a", verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (char* V_0, //p
pinned char& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.1
IL_0003: ldloc.1
IL_0004: conv.u
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.s 97
IL_000a: stind.i2
IL_000b: nop
IL_000c: ldc.i4.0
IL_000d: conv.u
IL_000e: stloc.1
IL_000f: ret
}
");
}
[Fact]
public void FixedStatementStringLiteral()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"")
{
Console.WriteLine(*p);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"h", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
-IL_0000: nop
IL_0001: ldstr ""hello""
IL_0006: stloc.1
-IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
-IL_0015: nop
-IL_0016: ldloc.0
IL_0017: ldind.u2
IL_0018: call ""void System.Console.WriteLine(char)""
IL_001d: nop
-IL_001e: nop
~IL_001f: ldnull
IL_0020: stloc.1
-IL_0021: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementStringVariable()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
string s = ""hello"";
fixed (char* p = s)
{
Console.Write(*p);
}
s = null;
fixed (char* p = s)
{
Console.Write(p == null);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"hTrue", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 72 (0x48)
.maxstack 2
.locals init (string V_0, //s
char* V_1, //p
pinned string V_2,
char* V_3, //p
pinned string V_4)
-IL_0000: nop
-IL_0001: ldstr ""hello""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: stloc.2
-IL_0009: ldloc.2
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: brfalse.s IL_0017
IL_000f: ldloc.1
IL_0010: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0015: add
IL_0016: stloc.1
-IL_0017: nop
-IL_0018: ldloc.1
IL_0019: ldind.u2
IL_001a: call ""void System.Console.Write(char)""
IL_001f: nop
-IL_0020: nop
~IL_0021: ldnull
IL_0022: stloc.2
-IL_0023: ldnull
IL_0024: stloc.0
IL_0025: ldloc.0
IL_0026: stloc.s V_4
-IL_0028: ldloc.s V_4
IL_002a: conv.u
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: brfalse.s IL_0037
IL_002f: ldloc.3
IL_0030: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0035: add
IL_0036: stloc.3
-IL_0037: nop
-IL_0038: ldloc.3
IL_0039: ldc.i4.0
IL_003a: conv.u
IL_003b: ceq
IL_003d: call ""void System.Console.Write(bool)""
IL_0042: nop
-IL_0043: nop
~IL_0044: ldnull
IL_0045: stloc.s V_4
-IL_0047: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementStringVariableOptimized()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
string s = ""hello"";
fixed (char* p = s)
{
Console.Write(*p);
}
s = null;
fixed (char* p = s)
{
Console.Write(p == null);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"hTrue", verify: Verification.Fails);
// Null checks and branches are much simpler, but string temps are NOT optimized away.
compVerifier.VerifyIL("C.Main", @"
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char* V_2) //p
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldind.u2
IL_0016: call ""void System.Console.Write(char)""
IL_001b: ldnull
IL_001c: stloc.1
IL_001d: ldnull
IL_001e: stloc.1
IL_001f: ldloc.1
IL_0020: conv.u
IL_0021: stloc.2
IL_0022: ldloc.2
IL_0023: brfalse.s IL_002d
IL_0025: ldloc.2
IL_0026: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_002b: add
IL_002c: stloc.2
IL_002d: ldloc.2
IL_002e: ldc.i4.0
IL_002f: conv.u
IL_0030: ceq
IL_0032: call ""void System.Console.Write(bool)""
IL_0037: ldnull
IL_0038: stloc.1
IL_0039: ret
}
");
}
[Fact]
public void FixedStatementOneDimensionalArray()
{
var text = @"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (int* V_0, //p
pinned int[] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[] C.a""
IL_000b: ldc.i4.0
IL_000c: ldelem.i4
IL_000d: call ""void System.Console.Write(int)""
IL_0012: dup
IL_0013: ldfld ""int[] C.a""
IL_0018: dup
IL_0019: stloc.1
IL_001a: brfalse.s IL_0021
IL_001c: ldloc.1
IL_001d: ldlen
IL_001e: conv.i4
IL_001f: brtrue.s IL_0026
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.0
IL_0024: br.s IL_002f
IL_0026: ldloc.1
IL_0027: ldc.i4.0
IL_0028: ldelema ""int""
IL_002d: conv.u
IL_002e: stloc.0
IL_002f: ldloc.0
IL_0030: ldc.i4.1
IL_0031: stind.i4
IL_0032: ldnull
IL_0033: stloc.1
IL_0034: ldfld ""int[] C.a""
IL_0039: ldc.i4.0
IL_003a: ldelem.i4
IL_003b: call ""void System.Console.Write(int)""
IL_0040: ret
}
");
}
[Fact]
public void FixedStatementOneDimensionalArrayOptimized()
{
var text = @"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (int* V_0, //p
pinned int[] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[] C.a""
IL_000b: ldc.i4.0
IL_000c: ldelem.i4
IL_000d: call ""void System.Console.Write(int)""
IL_0012: dup
IL_0013: ldfld ""int[] C.a""
IL_0018: dup
IL_0019: stloc.1
IL_001a: brfalse.s IL_0021
IL_001c: ldloc.1
IL_001d: ldlen
IL_001e: conv.i4
IL_001f: brtrue.s IL_0026
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.0
IL_0024: br.s IL_002f
IL_0026: ldloc.1
IL_0027: ldc.i4.0
IL_0028: ldelema ""int""
IL_002d: conv.u
IL_002e: stloc.0
IL_002f: ldloc.0
IL_0030: ldc.i4.1
IL_0031: stind.i4
IL_0032: ldnull
IL_0033: stloc.1
IL_0034: ldfld ""int[] C.a""
IL_0039: ldc.i4.0
IL_003a: ldelem.i4
IL_003b: call ""void System.Console.Write(int)""
IL_0040: ret
}
");
}
[Fact]
public void FixedStatementMultiDimensionalArrayOptimized()
{
var text = @"
using System;
unsafe class C
{
int[,] a = new int[1,1];
static void Main()
{
C c = new C();
Console.Write(c.a[0, 0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0, 0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (int* V_0, //p
pinned int[,] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[,] C.a""
IL_000b: ldc.i4.0
IL_000c: ldc.i4.0
IL_000d: call ""int[*,*].Get""
IL_0012: call ""void System.Console.Write(int)""
IL_0017: dup
IL_0018: ldfld ""int[,] C.a""
IL_001d: dup
IL_001e: stloc.1
IL_001f: brfalse.s IL_0029
IL_0021: ldloc.1
IL_0022: callvirt ""int System.Array.Length.get""
IL_0027: brtrue.s IL_002e
IL_0029: ldc.i4.0
IL_002a: conv.u
IL_002b: stloc.0
IL_002c: br.s IL_0038
IL_002e: ldloc.1
IL_002f: ldc.i4.0
IL_0030: ldc.i4.0
IL_0031: call ""int[*,*].Address""
IL_0036: conv.u
IL_0037: stloc.0
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: stind.i4
IL_003b: ldnull
IL_003c: stloc.1
IL_003d: ldfld ""int[,] C.a""
IL_0042: ldc.i4.0
IL_0043: ldc.i4.0
IL_0044: call ""int[*,*].Get""
IL_0049: call ""void System.Console.Write(int)""
IL_004e: ret
}
");
}
[Fact]
public void FixedStatementMixed()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
Console.Write((int)*p);
Console.Write((int)*q);
Console.Write((int)*r);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"970104", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 99 (0x63)
.maxstack 2
.locals init (char* V_0, //p
char* V_1, //q
char* V_2, //r
pinned char& V_3,
pinned char[] V_4,
pinned string V_5)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""char C.c""
IL_000b: stloc.3
IL_000c: ldloc.3
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: ldfld ""char[] C.a""
IL_0014: dup
IL_0015: stloc.s V_4
IL_0017: brfalse.s IL_001f
IL_0019: ldloc.s V_4
IL_001b: ldlen
IL_001c: conv.i4
IL_001d: brtrue.s IL_0024
IL_001f: ldc.i4.0
IL_0020: conv.u
IL_0021: stloc.1
IL_0022: br.s IL_002e
IL_0024: ldloc.s V_4
IL_0026: ldc.i4.0
IL_0027: ldelema ""char""
IL_002c: conv.u
IL_002d: stloc.1
IL_002e: ldstr ""hello""
IL_0033: stloc.s V_5
IL_0035: ldloc.s V_5
IL_0037: conv.u
IL_0038: stloc.2
IL_0039: ldloc.2
IL_003a: brfalse.s IL_0044
IL_003c: ldloc.2
IL_003d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0042: add
IL_0043: stloc.2
IL_0044: ldloc.0
IL_0045: ldind.u2
IL_0046: call ""void System.Console.Write(int)""
IL_004b: ldloc.1
IL_004c: ldind.u2
IL_004d: call ""void System.Console.Write(int)""
IL_0052: ldloc.2
IL_0053: ldind.u2
IL_0054: call ""void System.Console.Write(int)""
IL_0059: ldc.i4.0
IL_005a: conv.u
IL_005b: stloc.3
IL_005c: ldnull
IL_005d: stloc.s V_4
IL_005f: ldnull
IL_0060: stloc.s V_5
IL_0062: ret
}
");
}
[Fact]
public void FixedStatementInTryOfTryFinally()
{
var text = @"
unsafe class C
{
static void nop() { }
void Test()
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
nop();
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_001f
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
}
finally
{
IL_0019: call ""void C.nop()""
IL_001e: endfinally
}
IL_001f: ret
}
");
}
[Fact]
public void FixedStatementInTryOfTryCatch()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
fixed (char* p = ""hello"")
{
}
}
catch
{
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: leave.s IL_001e
}
catch object
{
IL_001b: pop
IL_001c: leave.s IL_001e
}
IL_001e: ret
}
");
}
[Fact]
public void FixedStatementInFinally()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
}
finally
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: leave.s IL_0019
}
finally
{
IL_0002: ldstr ""hello""
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: conv.u
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0016
IL_000e: ldloc.0
IL_000f: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0014: add
IL_0015: stloc.0
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInCatchOfTryCatch()
{
var text = @"
unsafe class C
{
void nop() { }
void Test()
{
try
{
nop();
}
catch
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test",
@"{
// Code size 34 (0x22)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldarg.0
IL_0001: call ""void C.nop()""
IL_0006: leave.s IL_0021
}
catch object
{
IL_0008: pop
IL_0009: ldstr ""hello""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: conv.u
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: brfalse.s IL_001d
IL_0015: ldloc.0
IL_0016: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001b: add
IL_001c: stloc.0
IL_001d: ldnull
IL_001e: stloc.1
IL_001f: leave.s IL_0021
}
IL_0021: ret
}");
}
[Fact]
public void FixedStatementInCatchOfTryCatchFinally()
{
var text = @"
unsafe class C
{
static void nop() { }
void Test()
{
try
{
nop();
}
catch
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: call ""void C.nop()""
IL_0005: leave.s IL_0023
}
catch object
{
IL_0007: pop
.try
{
IL_0008: ldstr ""hello""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: brfalse.s IL_001c
IL_0014: ldloc.0
IL_0015: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001a: add
IL_001b: stloc.0
IL_001c: leave.s IL_0021
}
finally
{
IL_001e: ldnull
IL_001f: stloc.1
IL_0020: endfinally
}
IL_0021: leave.s IL_0023
}
IL_0023: ret
}
");
}
[Fact]
public void FixedStatementInFixed_NoBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Neither inner nor outer has finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""hello""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldnull
IL_0029: stloc.3
IL_002a: ldnull
IL_002b: stloc.1
IL_002c: ret
}
");
}
[Fact]
public void FixedStatementInFixed_InnerBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
goto label;
}
}
label: ;
}
}
";
// Inner and outer both have finally blocks.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 50 (0x32)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
.try
{
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: nop
.try
{
IL_0015: ldstr ""hello""
IL_001a: stloc.3
IL_001b: ldloc.3
IL_001c: conv.u
IL_001d: stloc.2
IL_001e: ldloc.2
IL_001f: brfalse.s IL_0029
IL_0021: ldloc.2
IL_0022: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0027: add
IL_0028: stloc.2
IL_0029: leave.s IL_0031
}
finally
{
IL_002b: ldnull
IL_002c: stloc.3
IL_002d: endfinally
}
}
finally
{
IL_002e: ldnull
IL_002f: stloc.1
IL_0030: endfinally
}
IL_0031: ret
}
");
}
[Fact]
public void FixedStatementInFixed_OuterBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
}
goto label;
}
label: ;
}
}
";
// Outer has finally, inner does not.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 48 (0x30)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
.try
{
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""hello""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldnull
IL_0029: stloc.3
IL_002a: leave.s IL_002f
}
finally
{
IL_002c: ldnull
IL_002d: stloc.1
IL_002e: endfinally
}
IL_002f: ret
}
");
}
[Fact]
public void FixedStatementInFixed_Nesting()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p1 = ""A"")
{
fixed (char* p2 = ""B"")
{
fixed (char* p3 = ""C"")
{
}
fixed (char* p4 = ""D"")
{
}
}
fixed (char* p5 = ""E"")
{
fixed (char* p6 = ""F"")
{
}
fixed (char* p7 = ""G"")
{
}
}
}
}
}
";
// This test checks two things:
// 1) nothing blows up with triple-nesting, and
// 2) none of the fixed statements has a try-finally.
// CONSIDER: Shorter test that performs the same checks.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 187 (0xbb)
.maxstack 2
.locals init (char* V_0, //p1
pinned string V_1,
char* V_2, //p2
pinned string V_3,
char* V_4, //p3
pinned string V_5,
char* V_6, //p4
char* V_7, //p5
char* V_8, //p6
char* V_9) //p7
IL_0000: ldstr ""A""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""B""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldstr ""C""
IL_002d: stloc.s V_5
IL_002f: ldloc.s V_5
IL_0031: conv.u
IL_0032: stloc.s V_4
IL_0034: ldloc.s V_4
IL_0036: brfalse.s IL_0042
IL_0038: ldloc.s V_4
IL_003a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_003f: add
IL_0040: stloc.s V_4
IL_0042: ldnull
IL_0043: stloc.s V_5
IL_0045: ldstr ""D""
IL_004a: stloc.s V_5
IL_004c: ldloc.s V_5
IL_004e: conv.u
IL_004f: stloc.s V_6
IL_0051: ldloc.s V_6
IL_0053: brfalse.s IL_005f
IL_0055: ldloc.s V_6
IL_0057: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_005c: add
IL_005d: stloc.s V_6
IL_005f: ldnull
IL_0060: stloc.s V_5
IL_0062: ldnull
IL_0063: stloc.3
IL_0064: ldstr ""E""
IL_0069: stloc.3
IL_006a: ldloc.3
IL_006b: conv.u
IL_006c: stloc.s V_7
IL_006e: ldloc.s V_7
IL_0070: brfalse.s IL_007c
IL_0072: ldloc.s V_7
IL_0074: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0079: add
IL_007a: stloc.s V_7
IL_007c: ldstr ""F""
IL_0081: stloc.s V_5
IL_0083: ldloc.s V_5
IL_0085: conv.u
IL_0086: stloc.s V_8
IL_0088: ldloc.s V_8
IL_008a: brfalse.s IL_0096
IL_008c: ldloc.s V_8
IL_008e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0093: add
IL_0094: stloc.s V_8
IL_0096: ldnull
IL_0097: stloc.s V_5
IL_0099: ldstr ""G""
IL_009e: stloc.s V_5
IL_00a0: ldloc.s V_5
IL_00a2: conv.u
IL_00a3: stloc.s V_9
IL_00a5: ldloc.s V_9
IL_00a7: brfalse.s IL_00b3
IL_00a9: ldloc.s V_9
IL_00ab: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_00b0: add
IL_00b1: stloc.s V_9
IL_00b3: ldnull
IL_00b4: stloc.s V_5
IL_00b6: ldnull
IL_00b7: stloc.3
IL_00b8: ldnull
IL_00b9: stloc.1
IL_00ba: ret
}
");
}
[Fact]
public void FixedStatementInUsing()
{
var text = @"
unsafe class C
{
void Test()
{
using (System.IDisposable d = null)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// CONSIDER: This is sort of silly since the using is optimized away.
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInLock()
{
var text = @"
unsafe class C
{
void Test()
{
lock (this)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally (matches dev11, but not clear why).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (C V_0,
bool V_1,
char* V_2, //p
pinned string V_3)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
.try
{
IL_0004: ldloc.0
IL_0005: ldloca.s V_1
IL_0007: call ""void System.Threading.Monitor.Enter(object, ref bool)""
IL_000c: ldstr ""hello""
IL_0011: stloc.3
IL_0012: ldloc.3
IL_0013: conv.u
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0020
IL_0018: ldloc.2
IL_0019: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001e: add
IL_001f: stloc.2
IL_0020: ldnull
IL_0021: stloc.3
IL_0022: leave.s IL_002e
}
finally
{
IL_0024: ldloc.1
IL_0025: brfalse.s IL_002d
IL_0027: ldloc.0
IL_0028: call ""void System.Threading.Monitor.Exit(object)""
IL_002d: endfinally
}
IL_002e: ret
}
");
}
[Fact]
public void FixedStatementInForEach_NoDispose()
{
var text = @"
unsafe class C
{
void Test(int[] array)
{
foreach (int i in array)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup in finally.
// CONSIDER: dev11 is smarter and skips the try-finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (int[] V_0,
int V_1,
char* V_2, //p
pinned string V_3)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: br.s IL_0027
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: ldelem.i4
IL_0009: pop
.try
{
IL_000a: ldstr ""hello""
IL_000f: stloc.3
IL_0010: ldloc.3
IL_0011: conv.u
IL_0012: stloc.2
IL_0013: ldloc.2
IL_0014: brfalse.s IL_001e
IL_0016: ldloc.2
IL_0017: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001c: add
IL_001d: stloc.2
IL_001e: leave.s IL_0023
}
finally
{
IL_0020: ldnull
IL_0021: stloc.3
IL_0022: endfinally
}
IL_0023: ldloc.1
IL_0024: ldc.i4.1
IL_0025: add
IL_0026: stloc.1
IL_0027: ldloc.1
IL_0028: ldloc.0
IL_0029: ldlen
IL_002a: conv.i4
IL_002b: blt.s IL_0006
IL_002d: ret
}
");
}
[Fact]
public void FixedStatementInForEach_Dispose()
{
var text = @"
unsafe class C
{
void Test(Enumerable e)
{
foreach (var x in e)
{
fixed (char* p = ""hello"")
{
}
}
}
}
class Enumerable
{
public Enumerator GetEnumerator() { return new Enumerator(); }
}
class Enumerator : System.IDisposable
{
int x;
public int Current { get { return x; } }
public bool MoveNext() { return ++x < 4; }
void System.IDisposable.Dispose() { }
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 62 (0x3e)
.maxstack 2
.locals init (Enumerator V_0,
char* V_1, //p
pinned string V_2)
IL_0000: ldarg.1
IL_0001: callvirt ""Enumerator Enumerable.GetEnumerator()""
IL_0006: stloc.0
.try
{
IL_0007: br.s IL_0029
IL_0009: ldloc.0
IL_000a: callvirt ""int Enumerator.Current.get""
IL_000f: pop
.try
{
IL_0010: ldstr ""hello""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0024
IL_001c: ldloc.1
IL_001d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0022: add
IL_0023: stloc.1
IL_0024: leave.s IL_0029
}
finally
{
IL_0026: ldnull
IL_0027: stloc.2
IL_0028: endfinally
}
IL_0029: ldloc.0
IL_002a: callvirt ""bool Enumerator.MoveNext()""
IL_002f: brtrue.s IL_0009
IL_0031: leave.s IL_003d
}
finally
{
IL_0033: ldloc.0
IL_0034: brfalse.s IL_003c
IL_0036: ldloc.0
IL_0037: callvirt ""void System.IDisposable.Dispose()""
IL_003c: endfinally
}
IL_003d: ret
}
");
}
[Fact]
public void FixedStatementInLambda1()
{
var text = @"
unsafe class C
{
void Test()
{
System.Action a = () =>
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
};
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}");
}
[Fact]
public void FixedStatementInLambda2()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
}
};
}
finally
{
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
[Fact]
public void FixedStatementInLambda3()
{
var text = @"
unsafe class C
{
void Test()
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
};
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInFieldInitializer1()
{
var text = @"
unsafe class C
{
System.Action a = () =>
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
};
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<.ctor>b__1_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInFieldInitializer2()
{
var text = @"
unsafe class C
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
};
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<.ctor>b__1_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_LoopBreak()
{
var text = @"
unsafe class C
{
void Test()
{
while(true)
{
fixed (char* p = ""hello"")
{
break;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_001a
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
IL_001a: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_LoopContinue()
{
var text = @"
unsafe class C
{
void Test()
{
while(true)
{
fixed (char* p = ""hello"")
{
continue;
}
}
}
}
";
// Cleanup in finally.
// CONSIDER: dev11 doesn't have a finally here, but that seems incorrect.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_SwitchBreak()
{
var text = @"
unsafe class C
{
void Test()
{
switch (1)
{
case 1:
fixed (char* p = ""hello"")
{
break;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_001a
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
IL_001a: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_SwitchGoto()
{
var text = @"
unsafe class C
{
void Test()
{
switch (1)
{
case 1:
fixed (char* p = ""hello"")
{
goto case 1;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_BackwardGoto()
{
var text = @"
unsafe class C
{
void Test()
{
label:
fixed (char* p = ""hello"")
{
goto label;
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_ForwardGoto()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_Throw()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
throw null;
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: throw
}
");
}
[Fact]
public void FixedStatementWithBranchOut_Return()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
return;
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_Loop()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
for (int i = 0; i < 10; i++)
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
int V_2) //i
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldc.i4.0
IL_0015: stloc.2
IL_0016: br.s IL_001c
IL_0018: ldloc.2
IL_0019: ldc.i4.1
IL_001a: add
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: ldc.i4.s 10
IL_001f: blt.s IL_0018
IL_0021: ldnull
IL_0022: stloc.1
IL_0023: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_InternalGoto()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
goto label;
label: ;
}
}
}
";
// NOTE: Dev11 uses a finally here, but it's unnecessary.
// From GotoChecker::VisitGOTO:
// We have an unrealized goto, so we do not know whether it
// branches out or not. We should be conservative and assume that
// it does.
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_Switch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
switch(*p)
{
case 'a':
Test();
goto case 'b';
case 'b':
Test();
goto case 'c';
case 'c':
Test();
goto case 'd';
case 'd':
Test();
goto case 'e';
case 'e':
Test();
goto case 'f';
case 'f':
Test();
goto default;
default:
Test();
break;
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 103 (0x67)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char V_2)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldind.u2
IL_0016: stloc.2
IL_0017: ldloc.2
IL_0018: ldc.i4.s 97
IL_001a: sub
IL_001b: switch (
IL_003a,
IL_0040,
IL_0046,
IL_004c,
IL_0052,
IL_0058)
IL_0038: br.s IL_005e
IL_003a: ldarg.0
IL_003b: call ""void C.Test()""
IL_0040: ldarg.0
IL_0041: call ""void C.Test()""
IL_0046: ldarg.0
IL_0047: call ""void C.Test()""
IL_004c: ldarg.0
IL_004d: call ""void C.Test()""
IL_0052: ldarg.0
IL_0053: call ""void C.Test()""
IL_0058: ldarg.0
IL_0059: call ""void C.Test()""
IL_005e: ldarg.0
IL_005f: call ""void C.Test()""
IL_0064: ldnull
IL_0065: stloc.1
IL_0066: ret
}
");
}
[Fact]
public void FixedStatementWithParenthesizedStringExpression()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ((""hello"")))
{
}
}
}";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
#endregion Fixed statement tests
#region Custom fixed statement tests
[Fact]
public void SimpleCaseOfCustomFixed()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
static class FixableExt
{
public static ref int GetPinnableReference(this Fixable self)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: newobj ""Fixable..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_000d
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: br.s IL_0015
IL_000d: call ""ref int Fixable.GetPinnableReference()""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: conv.u
IL_0015: ldc.i4.4
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.0
IL_0020: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixedExt()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
}
class Fixable
{
public ref int GetPinnableReference<T>() => throw null;
}
static class FixableExt
{
public static ref int GetPinnableReference<T>(this T self)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: newobj ""Fixable..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_000d
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: br.s IL_0015
IL_000d: call ""ref int FixableExt.GetPinnableReference<Fixable>(Fixable)""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: conv.u
IL_0015: ldc.i4.4
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.0
IL_0020: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixed_oldVersion()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2);
compVerifier.VerifyDiagnostics(
// (6,25): error CS8320: Feature 'extensible fixed statement' is not available in C# 7.2. Please use language version 7.3 or greater.
// fixed (int* p = new Fixable())
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "new Fixable()").WithArguments("extensible fixed statement", "7.3").WithLocation(6, 25)
);
}
[Fact]
public void SimpleCaseOfCustomFixedNull()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (Fixable)null)
{
System.Console.WriteLine((int)p);
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"0", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 26 (0x1a)
.maxstack 1
.locals init (pinned int& V_0)
IL_0000: ldnull
IL_0001: brtrue.s IL_0007
IL_0003: ldc.i4.0
IL_0004: conv.u
IL_0005: br.s IL_0010
IL_0007: ldnull
IL_0008: call ""ref int C.Fixable.GetPinnableReference()""
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: conv.u
IL_0010: conv.i4
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: ldc.i4.0
IL_0017: conv.u
IL_0018: stloc.0
IL_0019: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixedStruct()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (pinned int& V_0,
C.Fixable V_1)
IL_0000: ldloca.s V_1
IL_0002: dup
IL_0003: initobj ""C.Fixable""
IL_0009: call ""ref int C.Fixable.GetPinnableReference()""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: conv.u
IL_0011: ldc.i4.4
IL_0012: add
IL_0013: ldind.i4
IL_0014: call ""void System.Console.WriteLine(int)""
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: ret
}
");
}
[Fact]
public void CustomFixedStructNullable()
{
var text = @"
unsafe class C
{
public static void Main()
{
Fixable? f = new Fixable();
fixed (int* p = f)
{
System.Console.WriteLine(p[1]);
}
}
}
public struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
public static class FixableExt
{
public static ref int GetPinnableReference(this Fixable? f)
{
return ref f.Value.GetPinnableReference();
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (Fixable V_0,
pinned int& V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""Fixable""
IL_0008: ldloc.0
IL_0009: newobj ""Fixable?..ctor(Fixable)""
IL_000e: call ""ref int FixableExt.GetPinnableReference(Fixable?)""
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: conv.u
IL_0016: ldc.i4.4
IL_0017: add
IL_0018: ldind.i4
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ldc.i4.0
IL_001f: conv.u
IL_0020: stloc.1
IL_0021: ret
}
");
}
[Fact]
public void CustomFixedStructNullableErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
Fixable? f = new Fixable();
fixed (int* p = f)
{
System.Console.WriteLine(p[1]);
}
}
}
public struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (8,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "f").WithLocation(8, 25)
);
}
[Fact]
public void CustomFixedErrAmbiguous()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
public static class FixableExt1
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS0121: The call is ambiguous between the following methods or properties: 'FixableExt.GetPinnableReference(in Fixable)' and 'FixableExt1.GetPinnableReference(in Fixable)'
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_AmbigCall, "new Fixable(1)").WithArguments("FixableExt.GetPinnableReference(in Fixable)", "FixableExt1.GetPinnableReference(in Fixable)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25),
// (12,25): error CS0121: The call is ambiguous between the following methods or properties: 'FixableExt.GetPinnableReference(in Fixable)' and 'FixableExt1.GetPinnableReference(in Fixable)'
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_AmbigCall, "f").WithArguments("FixableExt.GetPinnableReference(in Fixable)", "FixableExt1.GetPinnableReference(in Fixable)").WithLocation(12, 25),
// (12,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "f").WithLocation(12, 25)
);
}
[Fact]
public void CustomFixedErrDynamic()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (dynamic)(new Fixable(1)))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = (dynamic)(new Fixable(1)))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(dynamic)(new Fixable(1))").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedErrBad()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (HocusPocus)(new Fixable(1)))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,26): error CS0246: The type or namespace name 'HocusPocus' could not be found (are you missing a using directive or an assembly reference?)
// fixed (int* p = (HocusPocus)(new Fixable(1)))
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "HocusPocus").WithArguments("HocusPocus").WithLocation(6, 26)
);
}
[Fact]
public void SimpleCaseOfCustomFixedGeneric()
{
var text = @"
unsafe class C
{
public static void Main()
{
Test(42);
Test((object)null);
}
public static void Test<T>(T arg)
{
fixed (int* p = arg)
{
System.Console.Write(p == null? 0: p[1]);
}
}
}
static class FixAllExt
{
public static ref int GetPinnableReference<T>(this T dummy)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"20", verify: Verification.Fails);
compVerifier.VerifyIL("C.Test<T>(T)", @"
{
// Code size 49 (0x31)
.maxstack 2
.locals init (int* V_0, //p
pinned int& V_1)
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brtrue.s IL_000c
IL_0008: ldc.i4.0
IL_0009: conv.u
IL_000a: br.s IL_001b
IL_000c: ldarga.s V_0
IL_000e: ldobj ""T""
IL_0013: call ""ref int FixAllExt.GetPinnableReference<T>(T)""
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: beq.s IL_0027
IL_0021: ldloc.0
IL_0022: ldc.i4.4
IL_0023: add
IL_0024: ldind.i4
IL_0025: br.s IL_0028
IL_0027: ldc.i4.0
IL_0028: call ""void System.Console.Write(int)""
IL_002d: ldc.i4.0
IL_002e: conv.u
IL_002f: stloc.1
IL_0030: ret
}
");
}
[Fact]
public void CustomFixedStructSideeffects()
{
var text = @"
unsafe class C
{
public static void Main()
{
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test(ref FixableStruct arg)
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
struct FixableStruct
{
public int x;
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyIL("C.Test(ref FixableStruct)", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: call ""ref int FixableStruct.GetPinnableReference()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.4
IL_000a: add
IL_000b: ldind.i4
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void CustomFixedClassSideeffects()
{
var text = @"
using System;
unsafe class C
{
public static void Main()
{
var b = new FixableClass();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test(ref FixableClass arg)
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
class FixableClass
{
public int x;
[Obsolete]
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyDiagnostics(
// (14,29): warning CS0612: 'FixableClass.GetPinnableReference()' is obsolete
// fixed (int* p = arg)
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "arg").WithArguments("FixableClass.GetPinnableReference()").WithLocation(14, 29)
);
// note that defensive copy is created
compVerifier.VerifyIL("C.Test(ref FixableClass)", @"
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_000a
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: conv.u
IL_0008: br.s IL_0012
IL_000a: call ""ref int FixableClass.GetPinnableReference()""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: ldc.i4.4
IL_0013: add
IL_0014: ldind.i4
IL_0015: call ""void System.Console.Write(int)""
IL_001a: ldc.i4.0
IL_001b: conv.u
IL_001c: stloc.0
IL_001d: ret
}
");
}
[Fact]
public void CustomFixedGenericSideeffects()
{
var text = @"
unsafe class C
{
public static void Main()
{
var a = new FixableClass();
Test(ref a);
System.Console.WriteLine(a.x);
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test<T>(ref T arg) where T: IFixable
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
interface IFixable
{
ref int GetPinnableReference();
}
class FixableClass : IFixable
{
public int x;
public ref int GetPinnableReference()
{
x = 123;
return ref (new int[] { 1, 2, 3 })[0];
}
}
struct FixableStruct : IFixable
{
public int x;
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"2123
5456");
compVerifier.VerifyIL("C.Test<T>(ref T)", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (pinned int& V_0,
T V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_1
IL_0003: initobj ""T""
IL_0009: ldloc.1
IL_000a: box ""T""
IL_000f: brtrue.s IL_0026
IL_0011: ldobj ""T""
IL_0016: stloc.1
IL_0017: ldloca.s V_1
IL_0019: ldloc.1
IL_001a: box ""T""
IL_001f: brtrue.s IL_0026
IL_0021: pop
IL_0022: ldc.i4.0
IL_0023: conv.u
IL_0024: br.s IL_0034
IL_0026: constrained. ""T""
IL_002c: callvirt ""ref int IFixable.GetPinnableReference()""
IL_0031: stloc.0
IL_0032: ldloc.0
IL_0033: conv.u
IL_0034: ldc.i4.4
IL_0035: add
IL_0036: ldind.i4
IL_0037: call ""void System.Console.Write(int)""
IL_003c: ldc.i4.0
IL_003d: conv.u
IL_003e: stloc.0
IL_003f: ret
}
");
}
[Fact]
public void CustomFixedGenericRefExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test<T>(ref T arg) where T: struct, IFixable
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
public interface IFixable
{
ref int GetPinnableReferenceImpl();
}
public struct FixableStruct : IFixable
{
public int x;
public ref int GetPinnableReferenceImpl()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
public static class FixableExt
{
public static ref int GetPinnableReference<T>(ref this T f) where T: struct, IFixable
{
return ref f.GetPinnableReferenceImpl();
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyIL("C.Test<T>(ref T)", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: call ""ref int FixableExt.GetPinnableReference<T>(ref T)""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.4
IL_000a: add
IL_000b: ldind.i4
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void CustomFixedStructInExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"23", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 61 (0x3d)
.maxstack 3
.locals init (Fixable V_0, //f
pinned int& V_1,
Fixable V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""Fixable..ctor(int)""
IL_0006: stloc.2
IL_0007: ldloca.s V_2
IL_0009: call ""ref readonly int FixableExt.GetPinnableReference(in Fixable)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: conv.u
IL_0011: ldc.i4.4
IL_0012: add
IL_0013: ldind.i4
IL_0014: call ""void System.Console.Write(int)""
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.1
IL_001c: ldloca.s V_0
IL_001e: ldc.i4.1
IL_001f: call ""Fixable..ctor(int)""
IL_0024: ldloca.s V_0
IL_0026: call ""ref readonly int FixableExt.GetPinnableReference(in Fixable)""
IL_002b: stloc.1
IL_002c: ldloc.1
IL_002d: conv.u
IL_002e: ldc.i4.2
IL_002f: conv.i
IL_0030: ldc.i4.4
IL_0031: mul
IL_0032: add
IL_0033: ldind.i4
IL_0034: call ""void System.Console.Write(int)""
IL_0039: ldc.i4.0
IL_003a: conv.u
IL_003b: stloc.1
IL_003c: ret
}
");
}
[Fact]
public void CustomFixedStructRefExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref int GetPinnableReference(ref this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (Fixable V_0, //f
pinned int& V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""Fixable..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref int FixableExt.GetPinnableReference(ref Fixable)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: conv.u
IL_0012: ldc.i4.2
IL_0013: conv.i
IL_0014: ldc.i4.4
IL_0015: mul
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.Write(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ret
}
");
}
[Fact]
public void CustomFixedStructRefExtensionErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref int GetPinnableReference(ref this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS1510: A ref or out value must be an assignable variable
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Fixable(1)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr01()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
private static ref int GetPinnableReference(this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS8385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr01_oldVersion()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
private static ref int GetPinnableReference(this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr02()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public static ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25),
// (6,25): error CS0176: Member 'Fixable.GetPinnableReference()' cannot be accessed with an instance reference; qualify it with a type name instead
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ObjectProhibited, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference()").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr03()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS1955: Non-invocable member 'Fixable.GetPinnableReference' cannot be used like a method.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr04()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference<T>() => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS0411: The type arguments for method 'Fixable.GetPinnableReference<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference<T>()").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr05_Obsolete()
{
var text = @"
using System;
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
[Obsolete(""hi"", true)]
public ref int GetPinnableReference() => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (8,25): error CS0619: 'Fixable.GetPinnableReference()' is obsolete: 'hi'
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference()", "hi").WithLocation(8, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr06_UseSite()
{
var missing_cs = "public struct Missing { }";
var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing");
var lib_cs = @"
public struct Fixable
{
public Fixable(int arg){}
public ref Missing GetPinnableReference() => throw null;
}
";
var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.EmitToImageReference() }, options: TestOptions.DebugDll);
var source =
@"
unsafe class C
{
public static void Main()
{
fixed (void* p = new Fixable(1))
{
}
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.EmitToImageReference() }, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (6,26): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// fixed (void* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_NoTypeDef, "new Fixable(1)").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 26),
// (6,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (void* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 26)
);
}
[Fact]
public void CustomFixedStructVariousErr07_Optional()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference(int x = 0) => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): warning CS0280: 'Fixable' does not implement the 'fixed' pattern. 'Fixable.GetPinnableReference(int)' has the wrong signature.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.WRN_PatternBadSignature, "new Fixable(1)").WithArguments("Fixable", "fixed", "Fixable.GetPinnableReference(int)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void FixStringMissingAllHelpers()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (char* p = string.Empty)
{
}
}
}
";
var comp = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
comp.MakeMemberMissing(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData);
comp.VerifyEmitDiagnostics(
// (6,26): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData'
// fixed (char* p = string.Empty)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "string.Empty").WithArguments("System.Runtime.CompilerServices.RuntimeHelpers", "get_OffsetToStringData").WithLocation(6, 26)
);
}
[Fact]
public void FixStringArrayExtensionHelpersIgnored()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (char* p = ""A"")
{
*p = default;
}
fixed (char* p = new char[1])
{
*p = default;
}
}
}
public static class FixableExt
{
public static ref char GetPinnableReference(this string self) => throw null;
public static ref char GetPinnableReference(this char[] self) => throw null;
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"");
compVerifier.VerifyIL("C.Main()", @"
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char* V_2, //p
pinned char[] V_3)
IL_0000: ldstr ""A""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldc.i4.0
IL_0016: stind.i2
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: ldc.i4.1
IL_001a: newarr ""char""
IL_001f: dup
IL_0020: stloc.3
IL_0021: brfalse.s IL_0028
IL_0023: ldloc.3
IL_0024: ldlen
IL_0025: conv.i4
IL_0026: brtrue.s IL_002d
IL_0028: ldc.i4.0
IL_0029: conv.u
IL_002a: stloc.2
IL_002b: br.s IL_0036
IL_002d: ldloc.3
IL_002e: ldc.i4.0
IL_002f: ldelema ""char""
IL_0034: conv.u
IL_0035: stloc.2
IL_0036: ldloc.2
IL_0037: ldc.i4.0
IL_0038: stind.i2
IL_0039: ldnull
IL_003a: stloc.3
IL_003b: ret
}
");
}
[Fact]
public void CustomFixedDelegateErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.Write(p[1]);
}
}
}
public delegate ref int ReturnsRef();
public struct Fixable
{
public Fixable(int arg){}
public ReturnsRef GetPinnableReference => null;
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable())
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable()").WithLocation(6, 25)
);
}
#endregion Custom fixed statement tests
#region Pointer conversion tests
[Fact]
public void ConvertNullToPointer()
{
var template = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
char ch = 'a';
char* p = &ch;
Console.WriteLine(p == null);
p = null;
Console.WriteLine(p == null);
}}
}}
}}
";
var expectedIL = @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (char V_0, //ch
char* V_1) //p
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.0
IL_0009: conv.u
IL_000a: ceq
IL_000c: call ""void System.Console.WriteLine(bool)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.0
IL_0016: conv.u
IL_0017: ceq
IL_0019: call ""void System.Console.WriteLine(bool)""
IL_001e: ret
}
";
var expectedOutput = @"False
True";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[Fact]
public void ConvertPointerToPointerOrVoid()
{
var template = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
char ch = 'a';
char* c1 = &ch;
void* v1 = c1;
void* v2 = (void**)v1;
char* c2 = (char*)v2;
Console.WriteLine(*c2);
}}
}}
}}
";
var expectedIL = @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (char V_0, //ch
void* V_1, //v1
void* V_2, //v2
char* V_3) //c2
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: stloc.2
IL_0009: ldloc.2
IL_000a: stloc.3
IL_000b: ldloc.3
IL_000c: ldind.u2
IL_000d: call ""void System.Console.WriteLine(char)""
IL_0012: ret
}
";
var expectedOutput = @"a";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[Fact]
public void ConvertPointerToNumericUnchecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
unchecked
{
sb = (sbyte)pi;
b = (byte)pi;
s = (short)pi;
us = (ushort)pi;
i = (int)pi;
ui = (uint)pi;
l = (long)pi;
ul = (ulong)pi;
sb = (sbyte)pv;
b = (byte)pv;
s = (short)pv;
us = (ushort)pv;
i = (int)pv;
ui = (uint)pv;
l = (long)pv;
ul = (ulong)pv;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 65 (0x41)
.maxstack 1
IL_0000: ldarg.1
IL_0001: conv.i1
IL_0002: starg.s V_3
IL_0004: ldarg.1
IL_0005: conv.u1
IL_0006: starg.s V_4
IL_0008: ldarg.1
IL_0009: conv.i2
IL_000a: starg.s V_5
IL_000c: ldarg.1
IL_000d: conv.u2
IL_000e: starg.s V_6
IL_0010: ldarg.1
IL_0011: conv.i4
IL_0012: starg.s V_7
IL_0014: ldarg.1
IL_0015: conv.u4
IL_0016: starg.s V_8
IL_0018: ldarg.1
IL_0019: conv.u8
IL_001a: starg.s V_9
IL_001c: ldarg.1
IL_001d: conv.u8
IL_001e: starg.s V_10
IL_0020: ldarg.2
IL_0021: conv.i1
IL_0022: starg.s V_3
IL_0024: ldarg.2
IL_0025: conv.u1
IL_0026: starg.s V_4
IL_0028: ldarg.2
IL_0029: conv.i2
IL_002a: starg.s V_5
IL_002c: ldarg.2
IL_002d: conv.u2
IL_002e: starg.s V_6
IL_0030: ldarg.2
IL_0031: conv.i4
IL_0032: starg.s V_7
IL_0034: ldarg.2
IL_0035: conv.u4
IL_0036: starg.s V_8
IL_0038: ldarg.2
IL_0039: conv.u8
IL_003a: starg.s V_9
IL_003c: ldarg.2
IL_003d: conv.u8
IL_003e: starg.s V_10
IL_0040: ret
}
");
}
[Fact]
public void ConvertPointerToNumericChecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
checked
{
sb = (sbyte)pi;
b = (byte)pi;
s = (short)pi;
us = (ushort)pi;
i = (int)pi;
ui = (uint)pi;
l = (long)pi;
ul = (ulong)pi;
sb = (sbyte)pv;
b = (byte)pv;
s = (short)pv;
us = (ushort)pv;
i = (int)pv;
ui = (uint)pv;
l = (long)pv;
ul = (ulong)pv;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 65 (0x41)
.maxstack 1
IL_0000: ldarg.1
IL_0001: conv.ovf.i1.un
IL_0002: starg.s V_3
IL_0004: ldarg.1
IL_0005: conv.ovf.u1.un
IL_0006: starg.s V_4
IL_0008: ldarg.1
IL_0009: conv.ovf.i2.un
IL_000a: starg.s V_5
IL_000c: ldarg.1
IL_000d: conv.ovf.u2.un
IL_000e: starg.s V_6
IL_0010: ldarg.1
IL_0011: conv.ovf.i4.un
IL_0012: starg.s V_7
IL_0014: ldarg.1
IL_0015: conv.ovf.u4.un
IL_0016: starg.s V_8
IL_0018: ldarg.1
IL_0019: conv.ovf.i8.un
IL_001a: starg.s V_9
IL_001c: ldarg.1
IL_001d: conv.u8
IL_001e: starg.s V_10
IL_0020: ldarg.2
IL_0021: conv.ovf.i1.un
IL_0022: starg.s V_3
IL_0024: ldarg.2
IL_0025: conv.ovf.u1.un
IL_0026: starg.s V_4
IL_0028: ldarg.2
IL_0029: conv.ovf.i2.un
IL_002a: starg.s V_5
IL_002c: ldarg.2
IL_002d: conv.ovf.u2.un
IL_002e: starg.s V_6
IL_0030: ldarg.2
IL_0031: conv.ovf.i4.un
IL_0032: starg.s V_7
IL_0034: ldarg.2
IL_0035: conv.ovf.u4.un
IL_0036: starg.s V_8
IL_0038: ldarg.2
IL_0039: conv.ovf.i8.un
IL_003a: starg.s V_9
IL_003c: ldarg.2
IL_003d: conv.u8
IL_003e: starg.s V_10
IL_0040: ret
}
");
}
[Fact]
public void ConvertNumericToPointerUnchecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
unchecked
{
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 79 (0x4f)
.maxstack 1
IL_0000: ldarg.3
IL_0001: conv.i
IL_0002: starg.s V_1
IL_0004: ldarg.s V_4
IL_0006: conv.u
IL_0007: starg.s V_1
IL_0009: ldarg.s V_5
IL_000b: conv.i
IL_000c: starg.s V_1
IL_000e: ldarg.s V_6
IL_0010: conv.u
IL_0011: starg.s V_1
IL_0013: ldarg.s V_7
IL_0015: conv.i
IL_0016: starg.s V_1
IL_0018: ldarg.s V_8
IL_001a: conv.u
IL_001b: starg.s V_1
IL_001d: ldarg.s V_9
IL_001f: conv.u
IL_0020: starg.s V_1
IL_0022: ldarg.s V_10
IL_0024: conv.u
IL_0025: starg.s V_1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: starg.s V_2
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: starg.s V_2
IL_0030: ldarg.s V_5
IL_0032: conv.i
IL_0033: starg.s V_2
IL_0035: ldarg.s V_6
IL_0037: conv.u
IL_0038: starg.s V_2
IL_003a: ldarg.s V_7
IL_003c: conv.i
IL_003d: starg.s V_2
IL_003f: ldarg.s V_8
IL_0041: conv.u
IL_0042: starg.s V_2
IL_0044: ldarg.s V_9
IL_0046: conv.u
IL_0047: starg.s V_2
IL_0049: ldarg.s V_10
IL_004b: conv.u
IL_004c: starg.s V_2
IL_004e: ret
}
");
}
[Fact]
public void ConvertNumericToPointerChecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
checked
{
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 79 (0x4f)
.maxstack 1
IL_0000: ldarg.3
IL_0001: conv.ovf.u
IL_0002: starg.s V_1
IL_0004: ldarg.s V_4
IL_0006: conv.u
IL_0007: starg.s V_1
IL_0009: ldarg.s V_5
IL_000b: conv.ovf.u
IL_000c: starg.s V_1
IL_000e: ldarg.s V_6
IL_0010: conv.u
IL_0011: starg.s V_1
IL_0013: ldarg.s V_7
IL_0015: conv.ovf.u
IL_0016: starg.s V_1
IL_0018: ldarg.s V_8
IL_001a: conv.u
IL_001b: starg.s V_1
IL_001d: ldarg.s V_9
IL_001f: conv.ovf.u
IL_0020: starg.s V_1
IL_0022: ldarg.s V_10
IL_0024: conv.ovf.u.un
IL_0025: starg.s V_1
IL_0027: ldarg.3
IL_0028: conv.ovf.u
IL_0029: starg.s V_2
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: starg.s V_2
IL_0030: ldarg.s V_5
IL_0032: conv.ovf.u
IL_0033: starg.s V_2
IL_0035: ldarg.s V_6
IL_0037: conv.u
IL_0038: starg.s V_2
IL_003a: ldarg.s V_7
IL_003c: conv.ovf.u
IL_003d: starg.s V_2
IL_003f: ldarg.s V_8
IL_0041: conv.u
IL_0042: starg.s V_2
IL_0044: ldarg.s V_9
IL_0046: conv.ovf.u
IL_0047: starg.s V_2
IL_0049: ldarg.s V_10
IL_004b: conv.ovf.u.un
IL_004c: starg.s V_2
IL_004e: ret
}
");
}
[Fact]
public void ConvertClassToPointerUDC()
{
var template = @"
using System;
unsafe class C
{{
void M(int* pi, void* pv, Explicit e, Implicit i)
{{
{0}
{{
e = (Explicit)pi;
e = (Explicit)pv;
i = pi;
i = pv;
pi = (int*)e;
pv = (int*)e;
pi = i;
pv = i;
}}
}}
}}
unsafe class Explicit
{{
public static explicit operator Explicit(void* p)
{{
return null;
}}
public static explicit operator int*(Explicit e)
{{
return null;
}}
}}
unsafe class Implicit
{{
public static implicit operator Implicit(void* p)
{{
return null;
}}
public static implicit operator int*(Implicit e)
{{
return null;
}}
}}
";
var expectedIL = @"
{
// Code size 67 (0x43)
.maxstack 1
IL_0000: ldarg.1
IL_0001: call ""Explicit Explicit.op_Explicit(void*)""
IL_0006: starg.s V_3
IL_0008: ldarg.2
IL_0009: call ""Explicit Explicit.op_Explicit(void*)""
IL_000e: starg.s V_3
IL_0010: ldarg.1
IL_0011: call ""Implicit Implicit.op_Implicit(void*)""
IL_0016: starg.s V_4
IL_0018: ldarg.2
IL_0019: call ""Implicit Implicit.op_Implicit(void*)""
IL_001e: starg.s V_4
IL_0020: ldarg.3
IL_0021: call ""int* Explicit.op_Explicit(Explicit)""
IL_0026: starg.s V_1
IL_0028: ldarg.3
IL_0029: call ""int* Explicit.op_Explicit(Explicit)""
IL_002e: starg.s V_2
IL_0030: ldarg.s V_4
IL_0032: call ""int* Implicit.op_Implicit(Implicit)""
IL_0037: starg.s V_1
IL_0039: ldarg.s V_4
IL_003b: call ""int* Implicit.op_Implicit(Implicit)""
IL_0040: starg.s V_2
IL_0042: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
}
[Fact]
public void ConvertIntPtrToPointer()
{
var template = @"
using System;
unsafe class C
{{
void M(int* pi, void* pv, IntPtr i, UIntPtr u)
{{
{0}
{{
i = (IntPtr)pi;
i = (IntPtr)pv;
u = (UIntPtr)pi;
u = (UIntPtr)pv;
pi = (int*)i;
pv = (int*)i;
pi = (int*)u;
pv = (int*)u;
}}
}}
}}
";
// Nothing special here - just more UDCs.
var expectedIL = @"
{
// Code size 67 (0x43)
.maxstack 1
IL_0000: ldarg.1
IL_0001: call ""System.IntPtr System.IntPtr.op_Explicit(void*)""
IL_0006: starg.s V_3
IL_0008: ldarg.2
IL_0009: call ""System.IntPtr System.IntPtr.op_Explicit(void*)""
IL_000e: starg.s V_3
IL_0010: ldarg.1
IL_0011: call ""System.UIntPtr System.UIntPtr.op_Explicit(void*)""
IL_0016: starg.s V_4
IL_0018: ldarg.2
IL_0019: call ""System.UIntPtr System.UIntPtr.op_Explicit(void*)""
IL_001e: starg.s V_4
IL_0020: ldarg.3
IL_0021: call ""void* System.IntPtr.op_Explicit(System.IntPtr)""
IL_0026: starg.s V_1
IL_0028: ldarg.3
IL_0029: call ""void* System.IntPtr.op_Explicit(System.IntPtr)""
IL_002e: starg.s V_2
IL_0030: ldarg.s V_4
IL_0032: call ""void* System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0037: starg.s V_1
IL_0039: ldarg.s V_4
IL_003b: call ""void* System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0040: starg.s V_2
IL_0042: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
}
[Fact]
public void FixedStatementConversion()
{
var template = @"
using System;
unsafe class C
{{
char c = 'a';
char[] a = new char[1];
static void Main()
{{
{0}
{{
C c = new C();
fixed (void* p = &c.c, q = c.a, r = ""hello"")
{{
Console.Write((int)*(char*)p);
Console.Write((int)*(char*)q);
Console.Write((int)*(char*)r);
}}
}}
}}
}}
";
// NB: "pinned System.IntPtr&" (which ildasm displays as "pinned native int&"), not void.
var expectedIL = @"
{
// Code size 112 (0x70)
.maxstack 2
.locals init (C V_0, //c
void* V_1, //p
void* V_2, //q
void* V_3, //r
pinned char& V_4,
pinned char[] V_5,
pinned string V_6)
-IL_0000: nop
-IL_0001: nop
-IL_0002: newobj ""C..ctor()""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldflda ""char C.c""
IL_000e: stloc.s V_4
-IL_0010: ldloc.s V_4
IL_0012: conv.u
IL_0013: stloc.1
-IL_0014: ldloc.0
IL_0015: ldfld ""char[] C.a""
IL_001a: dup
IL_001b: stloc.s V_5
IL_001d: brfalse.s IL_0025
IL_001f: ldloc.s V_5
IL_0021: ldlen
IL_0022: conv.i4
IL_0023: brtrue.s IL_002a
IL_0025: ldc.i4.0
IL_0026: conv.u
IL_0027: stloc.2
IL_0028: br.s IL_0034
IL_002a: ldloc.s V_5
IL_002c: ldc.i4.0
IL_002d: ldelema ""char""
IL_0032: conv.u
IL_0033: stloc.2
IL_0034: ldstr ""hello""
IL_0039: stloc.s V_6
-IL_003b: ldloc.s V_6
IL_003d: conv.u
IL_003e: stloc.3
IL_003f: ldloc.3
IL_0040: brfalse.s IL_004a
IL_0042: ldloc.3
IL_0043: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0048: add
IL_0049: stloc.3
-IL_004a: nop
-IL_004b: ldloc.1
IL_004c: ldind.u2
IL_004d: call ""void System.Console.Write(int)""
IL_0052: nop
-IL_0053: ldloc.2
IL_0054: ldind.u2
IL_0055: call ""void System.Console.Write(int)""
IL_005a: nop
-IL_005b: ldloc.3
IL_005c: ldind.u2
IL_005d: call ""void System.Console.Write(int)""
IL_0062: nop
-IL_0063: nop
~IL_0064: ldc.i4.0
IL_0065: conv.u
IL_0066: stloc.s V_4
IL_0068: ldnull
IL_0069: stloc.s V_5
IL_006b: ldnull
IL_006c: stloc.s V_6
-IL_006e: nop
-IL_006f: ret
}
";
var expectedOutput = @"970104";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL, sequencePoints: "C.Main");
CompileAndVerify(string.Format(template, "checked "), options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL, sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementVoidPointerPointer()
{
var template = @"
using System;
unsafe class C
{{
void* v;
static void Main()
{{
{0}
{{
char ch = 'a';
C c = new C();
c.v = &ch;
fixed (void** p = &c.v)
{{
Console.Write(*(char*)*p);
}}
}}
}}
}}
";
// NB: "pinned void*&", as in Dev10.
var expectedIL = @"
{
// Code size 36 (0x24)
.maxstack 3
.locals init (char V_0, //ch
pinned void*& V_1)
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: newobj ""C..ctor()""
IL_0008: dup
IL_0009: ldloca.s V_0
IL_000b: conv.u
IL_000c: stfld ""void* C.v""
IL_0011: ldflda ""void* C.v""
IL_0016: stloc.1
IL_0017: ldloc.1
IL_0018: conv.u
IL_0019: ldind.i
IL_001a: ldind.u2
IL_001b: call ""void System.Console.Write(char)""
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.1
IL_0023: ret
}
";
var expectedOutput = @"a";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayConversion()
{
var template = @"
using System;
unsafe class C
{{
void M(int*[] api, void*[] apv, Array a)
{{
{0}
{{
a = api;
a = apv;
api = (int*[])a;
apv = (void*[])a;
}}
}}
}}
";
var expectedIL = @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.1
IL_0001: starg.s V_3
IL_0003: ldarg.2
IL_0004: starg.s V_3
IL_0006: ldarg.3
IL_0007: castclass ""int*[]""
IL_000c: starg.s V_1
IL_000e: ldarg.3
IL_000f: castclass ""void*[]""
IL_0014: starg.s V_2
IL_0016: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayConversionRuntimeError()
{
var text = @"
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] api = new int*[1];
System.Array a = api;
a.GetValue(0);
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayEnumerableConversion()
{
var template = @"
using System.Collections;
unsafe class C
{{
void M(int*[] api, void*[] apv, IEnumerable e)
{{
{0}
{{
e = api;
e = apv;
api = (int*[])e;
apv = (void*[])e;
}}
}}
}}
";
var expectedIL = @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.1
IL_0001: starg.s V_3
IL_0003: ldarg.2
IL_0004: starg.s V_3
IL_0006: ldarg.3
IL_0007: castclass ""int*[]""
IL_000c: starg.s V_1
IL_000e: ldarg.3
IL_000f: castclass ""void*[]""
IL_0014: starg.s V_2
IL_0016: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayEnumerableConversionRuntimeError()
{
var text = @"
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] api = new int*[1];
System.Collections.IEnumerable e = api;
var enumerator = e.GetEnumerator();
enumerator.MoveNext();
var current = enumerator.Current;
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
[Fact]
public void PointerArrayForeachSingle()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int*[] array = new []
{
(int*)1,
(int*)2,
};
foreach (var element in array)
{
Console.Write((int)element);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "12", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 41 (0x29)
.maxstack 4
.locals init (int*[] V_0,
int V_1)
IL_0000: ldc.i4.2
IL_0001: newarr ""int*""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: conv.i
IL_000a: stelem.i
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: conv.i
IL_000f: stelem.i
IL_0010: stloc.0
IL_0011: ldc.i4.0
IL_0012: stloc.1
IL_0013: br.s IL_0022
IL_0015: ldloc.0
IL_0016: ldloc.1
IL_0017: ldelem.i
IL_0018: conv.i4
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldloc.1
IL_001f: ldc.i4.1
IL_0020: add
IL_0021: stloc.1
IL_0022: ldloc.1
IL_0023: ldloc.0
IL_0024: ldlen
IL_0025: conv.i4
IL_0026: blt.s IL_0015
IL_0028: ret
}
");
}
[Fact]
public void PointerArrayForeachMultiple()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int*[,] array = new [,]
{
{ (int*)1, (int*)2, },
{ (int*)3, (int*)4, },
};
foreach (var element in array)
{
Console.Write((int)element);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1234", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 120 (0x78)
.maxstack 5
.locals init (int*[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4)
IL_0000: ldc.i4.2
IL_0001: ldc.i4.2
IL_0002: newobj ""int*[*,*]..ctor""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: conv.i
IL_000c: call ""int*[*,*].Set""
IL_0011: dup
IL_0012: ldc.i4.0
IL_0013: ldc.i4.1
IL_0014: ldc.i4.2
IL_0015: conv.i
IL_0016: call ""int*[*,*].Set""
IL_001b: dup
IL_001c: ldc.i4.1
IL_001d: ldc.i4.0
IL_001e: ldc.i4.3
IL_001f: conv.i
IL_0020: call ""int*[*,*].Set""
IL_0025: dup
IL_0026: ldc.i4.1
IL_0027: ldc.i4.1
IL_0028: ldc.i4.4
IL_0029: conv.i
IL_002a: call ""int*[*,*].Set""
IL_002f: stloc.0
IL_0030: ldloc.0
IL_0031: ldc.i4.0
IL_0032: callvirt ""int System.Array.GetUpperBound(int)""
IL_0037: stloc.1
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: callvirt ""int System.Array.GetUpperBound(int)""
IL_003f: stloc.2
IL_0040: ldloc.0
IL_0041: ldc.i4.0
IL_0042: callvirt ""int System.Array.GetLowerBound(int)""
IL_0047: stloc.3
IL_0048: br.s IL_0073
IL_004a: ldloc.0
IL_004b: ldc.i4.1
IL_004c: callvirt ""int System.Array.GetLowerBound(int)""
IL_0051: stloc.s V_4
IL_0053: br.s IL_006a
IL_0055: ldloc.0
IL_0056: ldloc.3
IL_0057: ldloc.s V_4
IL_0059: call ""int*[*,*].Get""
IL_005e: conv.i4
IL_005f: call ""void System.Console.Write(int)""
IL_0064: ldloc.s V_4
IL_0066: ldc.i4.1
IL_0067: add
IL_0068: stloc.s V_4
IL_006a: ldloc.s V_4
IL_006c: ldloc.2
IL_006d: ble.s IL_0055
IL_006f: ldloc.3
IL_0070: ldc.i4.1
IL_0071: add
IL_0072: stloc.3
IL_0073: ldloc.3
IL_0074: ldloc.1
IL_0075: ble.s IL_004a
IL_0077: ret
}
");
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayForeachEnumerable()
{
var text = @"
using System;
using System.Collections;
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] array = new []
{
(int*)1,
(int*)2,
};
foreach (var element in (IEnumerable)array)
{
Console.Write((int)element);
}
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
#endregion Pointer conversion tests
#region sizeof tests
[Fact]
public void SizeOfConstant()
{
var text = @"
using System;
class C
{
static void Main()
{
Console.WriteLine(sizeof(sbyte));
Console.WriteLine(sizeof(byte));
Console.WriteLine(sizeof(short));
Console.WriteLine(sizeof(ushort));
Console.WriteLine(sizeof(int));
Console.WriteLine(sizeof(uint));
Console.WriteLine(sizeof(long));
Console.WriteLine(sizeof(ulong));
Console.WriteLine(sizeof(char));
Console.WriteLine(sizeof(float));
Console.WriteLine(sizeof(double));
Console.WriteLine(sizeof(bool));
Console.WriteLine(sizeof(decimal)); //Supported by dev10, but not spec.
}
}
";
var expectedOutput = @"
1
1
2
2
4
4
8
8
2
4
8
1
16
".Trim();
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 80 (0x50)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ldc.i4.1
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ldc.i4.2
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ldc.i4.2
IL_0013: call ""void System.Console.WriteLine(int)""
IL_0018: ldc.i4.4
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ldc.i4.4
IL_001f: call ""void System.Console.WriteLine(int)""
IL_0024: ldc.i4.8
IL_0025: call ""void System.Console.WriteLine(int)""
IL_002a: ldc.i4.8
IL_002b: call ""void System.Console.WriteLine(int)""
IL_0030: ldc.i4.2
IL_0031: call ""void System.Console.WriteLine(int)""
IL_0036: ldc.i4.4
IL_0037: call ""void System.Console.WriteLine(int)""
IL_003c: ldc.i4.8
IL_003d: call ""void System.Console.WriteLine(int)""
IL_0042: ldc.i4.1
IL_0043: call ""void System.Console.WriteLine(int)""
IL_0048: ldc.i4.s 16
IL_004a: call ""void System.Console.WriteLine(int)""
IL_004f: ret
}
");
}
[Fact]
public void SizeOfNonConstant()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(sizeof(S));
Console.WriteLine(sizeof(Outer.Inner));
Console.WriteLine(sizeof(int*));
Console.WriteLine(sizeof(void*));
}
}
struct S
{
public byte b;
}
class Outer
{
public struct Inner
{
public char c;
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
1
2
4
4
".Trim();
}
else
{
expectedOutput = @"
1
2
8
8
".Trim();
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 45 (0x2d)
.maxstack 1
IL_0000: sizeof ""S""
IL_0006: call ""void System.Console.WriteLine(int)""
IL_000b: sizeof ""Outer.Inner""
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: sizeof ""int*""
IL_001c: call ""void System.Console.WriteLine(int)""
IL_0021: sizeof ""void*""
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: ret
}
");
}
[Fact]
public void SizeOfEnum()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(sizeof(E1));
Console.WriteLine(sizeof(E2));
Console.WriteLine(sizeof(E3));
}
}
enum E1 { A }
enum E2 : byte { A }
enum E3 : long { A }
";
var expectedOutput = @"
4
1
8
".Trim();
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 19 (0x13)
.maxstack 1
IL_0000: ldc.i4.4
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ldc.i4.1
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ldc.i4.8
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ret
}
");
}
#endregion sizeof tests
#region Pointer arithmetic tests
[Fact]
public void NumericAdditionChecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S s = new S();
S* p = &s;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul.ovf
IL_0014: add.ovf.un
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul.ovf
IL_001f: conv.i
IL_0020: add.ovf.un
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul.ovf
IL_002b: conv.i
IL_002c: add.ovf.un
IL_002d: ldc.i4.5
IL_002e: conv.i8
IL_002f: sizeof ""S""
IL_0035: conv.ovf.u8
IL_0036: mul.ovf.un
IL_0037: conv.u
IL_0038: add.ovf.un
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericAdditionUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
unchecked
{
S s = new S();
S* p = &s;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul
IL_0014: add
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul
IL_001f: conv.i
IL_0020: add
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul
IL_002b: conv.i
IL_002c: add
IL_002d: pop
IL_002e: ldc.i4.5
IL_002f: conv.i8
IL_0030: sizeof ""S""
IL_0036: conv.i8
IL_0037: mul
IL_0038: conv.u
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericSubtractionChecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S s = new S();
S* p = &s;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul.ovf
IL_0014: sub.ovf.un
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul.ovf
IL_001f: conv.i
IL_0020: sub.ovf.un
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul.ovf
IL_002b: conv.i
IL_002c: sub.ovf.un
IL_002d: ldc.i4.5
IL_002e: conv.i8
IL_002f: sizeof ""S""
IL_0035: conv.ovf.u8
IL_0036: mul.ovf.un
IL_0037: conv.u
IL_0038: sub.ovf.un
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericSubtractionUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
unchecked
{
S s = new S();
S* p = &s;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul
IL_0014: sub
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul
IL_001f: conv.i
IL_0020: sub
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul
IL_002b: conv.i
IL_002c: sub
IL_002d: pop
IL_002e: ldc.i4.5
IL_002f: conv.i8
IL_0030: sizeof ""S""
IL_0036: conv.i8
IL_0037: mul
IL_0038: conv.u
IL_0039: pop
IL_003a: ret
}
");
}
[WorkItem(546750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546750")]
[Fact]
public void NumericAdditionUnchecked_SizeOne()
{
var text = @"
using System;
unsafe class C
{
void Test(int i, uint u, long l, ulong ul)
{
unchecked
{
byte b = 3;
byte* p = &b;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
p = p + i;
p = p + u;
p = p + l;
p = p + ul;
}
}
}
";
// NOTE: even when not optimized.
// NOTE: additional conversions applied to constants of type int and uint.
CompileAndVerify(text, options: TestOptions.UnsafeDebugDll, verify: Verification.Fails).VerifyIL("C.Test", @"
{
// Code size 50 (0x32)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: add
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: add
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: add
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: add
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: add
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: ldarg.2
IL_0022: conv.u
IL_0023: add
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: ldarg.3
IL_0027: conv.i
IL_0028: add
IL_0029: stloc.1
IL_002a: ldloc.1
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: add
IL_002f: stloc.1
IL_0030: nop
IL_0031: ret
}
");
}
[WorkItem(18871, "https://github.com/dotnet/roslyn/issues/18871")]
[WorkItem(546750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546750")]
[Fact]
public void NumericAdditionChecked_SizeOne()
{
var text = @"
using System;
unsafe class C
{
void Test(int i, uint u, long l, ulong ul)
{
checked
{
byte b = 3;
byte* p = &b;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
p = p + i;
p = p + u;
p = p + l;
p = p + ul;
p = p + (-2);
}
}
void Test1(int i, uint u, long l, ulong ul)
{
checked
{
byte b = 3;
byte* p = &b;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
p = p - i;
p = p - u;
p = p - l;
p = p - ul;
p = p - (-1);
}
}
}
";
// NOTE: even when not optimized.
// NOTE: additional conversions applied to constants of type int and uint.
// NOTE: identical to unchecked except "add" becomes "add.ovf.un".
var comp = CompileAndVerify(text, options: TestOptions.UnsafeDebugDll, verify: Verification.Fails);
comp.VerifyIL("C.Test", @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: add.ovf.un
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: add.ovf.un
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: add.ovf.un
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: add.ovf.un
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: conv.i
IL_001f: add.ovf.un
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.2
IL_0023: conv.u
IL_0024: add.ovf.un
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: add.ovf.un
IL_002a: stloc.1
IL_002b: ldloc.1
IL_002c: ldarg.s V_4
IL_002e: conv.u
IL_002f: add.ovf.un
IL_0030: stloc.1
IL_0031: ldloc.1
IL_0032: ldc.i4.s -2
IL_0034: conv.i
IL_0035: add.ovf.un
IL_0036: stloc.1
IL_0037: nop
IL_0038: ret
}");
comp.VerifyIL("C.Test1", @"
{
// Code size 56 (0x38)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: sub.ovf.un
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: sub.ovf.un
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: sub.ovf.un
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: sub.ovf.un
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: conv.i
IL_001f: sub.ovf.un
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.2
IL_0023: conv.u
IL_0024: sub.ovf.un
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: sub.ovf.un
IL_002a: stloc.1
IL_002b: ldloc.1
IL_002c: ldarg.s V_4
IL_002e: conv.u
IL_002f: sub.ovf.un
IL_0030: stloc.1
IL_0031: ldloc.1
IL_0032: ldc.i4.m1
IL_0033: conv.i
IL_0034: sub.ovf.un
IL_0035: stloc.1
IL_0036: nop
IL_0037: ret
}");
}
[Fact]
public void CheckedSignExtend()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
byte* ptr1 = default(byte*);
ptr1 = (byte*)2;
checked
{
// should not overflow regardless of 32/64 bit
ptr1 = ptr1 + 2147483649;
}
Console.WriteLine((long)ptr1);
byte* ptr = (byte*)2;
try
{
checked
{
int i = -1;
// should overflow regardless of 32/64 bit
ptr = ptr + i;
}
Console.WriteLine((long)ptr);
}
catch (OverflowException)
{
Console.WriteLine(""overflow"");
Console.WriteLine((long)ptr);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2147483651
overflow
2", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 67 (0x43)
.maxstack 2
.locals init (byte* V_0, //ptr1
byte* V_1, //ptr
int V_2) //i
IL_0000: ldloca.s V_0
IL_0002: initobj ""byte*""
IL_0008: ldc.i4.2
IL_0009: conv.i
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldc.i4 0x80000001
IL_0011: conv.u
IL_0012: add.ovf.un
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: conv.u8
IL_0016: call ""void System.Console.WriteLine(long)""
IL_001b: ldc.i4.2
IL_001c: conv.i
IL_001d: stloc.1
.try
{
IL_001e: ldc.i4.m1
IL_001f: stloc.2
IL_0020: ldloc.1
IL_0021: ldloc.2
IL_0022: conv.i
IL_0023: add.ovf.un
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: conv.u8
IL_0027: call ""void System.Console.WriteLine(long)""
IL_002c: leave.s IL_0042
}
catch System.OverflowException
{
IL_002e: pop
IL_002f: ldstr ""overflow""
IL_0034: call ""void System.Console.WriteLine(string)""
IL_0039: ldloc.1
IL_003a: conv.u8
IL_003b: call ""void System.Console.WriteLine(long)""
IL_0040: leave.s IL_0042
}
IL_0042: ret
}
");
}
[Fact]
public void Increment()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)0;
checked
{
p++;
}
checked
{
++p;
}
unchecked
{
p++;
}
unchecked
{
++p;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "4", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (S* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: add.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: sizeof ""S""
IL_0013: add.ovf.un
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: sizeof ""S""
IL_001c: add
IL_001d: stloc.0
IL_001e: ldloc.0
IL_001f: sizeof ""S""
IL_0025: add
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: conv.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: ret
}
");
}
[Fact]
public void Decrement()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
checked
{
p--;
}
checked
{
--p;
}
unchecked
{
p--;
}
unchecked
{
--p;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "4", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (S* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: sub.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: sizeof ""S""
IL_0013: sub.ovf.un
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: sizeof ""S""
IL_001c: sub
IL_001d: stloc.0
IL_001e: ldloc.0
IL_001f: sizeof ""S""
IL_0025: sub
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: conv.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: ret
}
");
}
[Fact]
public void IncrementProperty()
{
var text = @"
using System;
unsafe struct S
{
S* P { get; set; }
S* this[int x] { get { return P; } set { P = value; } }
static void Main()
{
S s = new S();
s.P++;
--s[GetIndex()];
Console.Write((int)s.P);
}
static int GetIndex()
{
Console.Write(""I"");
return 1;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "I0", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 74 (0x4a)
.maxstack 3
.locals init (S V_0, //s
S* V_1,
int V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: dup
IL_000b: call ""readonly S* S.P.get""
IL_0010: stloc.1
IL_0011: ldloc.1
IL_0012: sizeof ""S""
IL_0018: add
IL_0019: call ""void S.P.set""
IL_001e: ldloca.s V_0
IL_0020: call ""int S.GetIndex()""
IL_0025: stloc.2
IL_0026: dup
IL_0027: ldloc.2
IL_0028: call ""S* S.this[int].get""
IL_002d: sizeof ""S""
IL_0033: sub
IL_0034: stloc.1
IL_0035: ldloc.2
IL_0036: ldloc.1
IL_0037: call ""void S.this[int].set""
IL_003c: ldloca.s V_0
IL_003e: call ""readonly S* S.P.get""
IL_0043: conv.i4
IL_0044: call ""void System.Console.Write(int)""
IL_0049: ret
}
");
}
[Fact]
public void CompoundAssignment()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
checked
{
p += 1;
p += 2U;
p -= 1L;
p -= 2UL;
}
unchecked
{
p += 1;
p += 2U;
p -= 1L;
p -= 2UL;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "8", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 103 (0x67)
.maxstack 3
.locals init (S* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: add.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: ldc.i4.2
IL_000e: conv.u8
IL_000f: sizeof ""S""
IL_0015: conv.i8
IL_0016: mul.ovf
IL_0017: conv.i
IL_0018: add.ovf.un
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: sizeof ""S""
IL_0021: sub.ovf.un
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: ldc.i4.2
IL_0025: conv.i8
IL_0026: sizeof ""S""
IL_002c: conv.ovf.u8
IL_002d: mul.ovf.un
IL_002e: conv.u
IL_002f: sub.ovf.un
IL_0030: stloc.0
IL_0031: ldloc.0
IL_0032: sizeof ""S""
IL_0038: add
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ldc.i4.2
IL_003c: conv.u8
IL_003d: sizeof ""S""
IL_0043: conv.i8
IL_0044: mul
IL_0045: conv.i
IL_0046: add
IL_0047: stloc.0
IL_0048: ldloc.0
IL_0049: sizeof ""S""
IL_004f: sub
IL_0050: stloc.0
IL_0051: ldloc.0
IL_0052: ldc.i4.2
IL_0053: conv.i8
IL_0054: sizeof ""S""
IL_005a: conv.i8
IL_005b: mul
IL_005c: conv.u
IL_005d: sub
IL_005e: stloc.0
IL_005f: ldloc.0
IL_0060: conv.i4
IL_0061: call ""void System.Console.WriteLine(int)""
IL_0066: ret
}
");
}
[Fact]
public void CompoundAssignProperty()
{
var text = @"
using System;
unsafe struct S
{
S* P { get; set; }
S* this[int x] { get { return P; } set { P = value; } }
static void Main()
{
S s = new S();
s.P += 3;
s[GetIndex()] -= 2;
Console.Write((int)s.P);
}
static int GetIndex()
{
Console.Write(""I"");
return 1;
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"I4";
}
else
{
expectedOutput = @"I8";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 78 (0x4e)
.maxstack 5
.locals init (S V_0, //s
S& V_1,
int V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: dup
IL_000b: call ""readonly S* S.P.get""
IL_0010: ldc.i4.3
IL_0011: conv.i
IL_0012: sizeof ""S""
IL_0018: mul
IL_0019: add
IL_001a: call ""void S.P.set""
IL_001f: ldloca.s V_0
IL_0021: stloc.1
IL_0022: call ""int S.GetIndex()""
IL_0027: stloc.2
IL_0028: ldloc.1
IL_0029: ldloc.2
IL_002a: ldloc.1
IL_002b: ldloc.2
IL_002c: call ""S* S.this[int].get""
IL_0031: ldc.i4.2
IL_0032: conv.i
IL_0033: sizeof ""S""
IL_0039: mul
IL_003a: sub
IL_003b: call ""void S.this[int].set""
IL_0040: ldloca.s V_0
IL_0042: call ""readonly S* S.P.get""
IL_0047: conv.i4
IL_0048: call ""void System.Console.Write(int)""
IL_004d: ret
}
");
}
[Fact]
public void PointerSubtraction_EmptyStruct()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
S* q = (S*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "44", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: sizeof ""S""
IL_000f: div
IL_0010: conv.i8
IL_0011: call ""void System.Console.Write(long)""
IL_0016: ldloc.0
IL_0017: ldloc.1
IL_0018: sub
IL_0019: sizeof ""S""
IL_001f: div
IL_0020: conv.i8
IL_0021: call ""void System.Console.Write(long)""
IL_0026: ret
}
");
}
[Fact]
public void PointerSubtraction_NonEmptyStruct()
{
var text = @"
using System;
unsafe struct S
{
int x; //non-empty struct
static void Main()
{
S* p = (S*)8;
S* q = (S*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "11", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: sizeof ""S""
IL_000f: div
IL_0010: conv.i8
IL_0011: call ""void System.Console.Write(long)""
IL_0016: ldloc.0
IL_0017: ldloc.1
IL_0018: sub
IL_0019: sizeof ""S""
IL_001f: div
IL_0020: conv.i8
IL_0021: call ""void System.Console.Write(long)""
IL_0026: ret
}
");
}
[Fact]
public void PointerSubtraction_ConstantSize()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int* p = (int*)8; //size is known at compile-time
int* q = (int*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "11", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (int* V_0, //p
int* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: ldc.i4.4
IL_000a: div
IL_000b: conv.i8
IL_000c: call ""void System.Console.Write(long)""
IL_0011: ldloc.0
IL_0012: ldloc.1
IL_0013: sub
IL_0014: ldc.i4.4
IL_0015: div
IL_0016: conv.i8
IL_0017: call ""void System.Console.Write(long)""
IL_001c: ret
}
");
}
[Fact]
public void PointerSubtraction_IntegerDivision()
{
var text = @"
using System;
unsafe struct S
{
int x; //size = 4
static void Main()
{
S* p1 = (S*)7; //size is known at compile-time
S* p2 = (S*)9; //size is known at compile-time
S* q = (S*)4;
checked
{
Console.Write(p1 - q);
}
unchecked
{
Console.Write(p2 - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "01", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 43 (0x2b)
.maxstack 2
.locals init (S* V_0, //p1
S* V_1, //p2
S* V_2) //q
IL_0000: ldc.i4.7
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.s 9
IL_0005: conv.i
IL_0006: stloc.1
IL_0007: ldc.i4.4
IL_0008: conv.i
IL_0009: stloc.2
IL_000a: ldloc.0
IL_000b: ldloc.2
IL_000c: sub
IL_000d: sizeof ""S""
IL_0013: div
IL_0014: conv.i8
IL_0015: call ""void System.Console.Write(long)""
IL_001a: ldloc.1
IL_001b: ldloc.2
IL_001c: sub
IL_001d: sizeof ""S""
IL_0023: div
IL_0024: conv.i8
IL_0025: call ""void System.Console.Write(long)""
IL_002a: ret
}
");
}
[WorkItem(544155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544155")]
[Fact]
public void SubtractPointerTypes()
{
var text = @"
using System;
class PointerArithmetic
{
static unsafe void Main()
{
short ia1 = 10;
short* ptr = &ia1;
short* newPtr;
newPtr = ptr - 2;
Console.WriteLine((int)(ptr - newPtr));
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "2", verify: Verification.Fails);
}
#endregion Pointer arithmetic tests
#region Checked pointer arithmetic overflow tests
// 0 - operation name (e.g. "Add")
// 1 - pointed at type name (e.g. "S")
// 2 - operator (e.g. "+")
// 3 - checked/unchecked
private const string CheckedNumericHelperTemplate = @"
unsafe static class Helper
{{
public static void {0}Int({1}* p, int num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}Int: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}Int: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}UInt({1}* p, uint num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}UInt: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}UInt: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}Long({1}* p, long num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}Long: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}Long: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}ULong({1}* p, ulong num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}ULong: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}ULong: Exception at {{0}}"", description);
}}
}}
}}
}}
";
private const string SizedStructs = @"
//sizeof SXX is 2 ^ XX
struct S00 { }
struct S01 { S00 a, b; }
struct S02 { S01 a, b; }
struct S03 { S02 a, b; }
struct S04 { S03 a, b; }
struct S05 { S04 a, b; }
struct S06 { S05 a, b; }
struct S07 { S06 a, b; }
struct S08 { S07 a, b; }
struct S09 { S08 a, b; }
struct S10 { S09 a, b; }
struct S11 { S10 a, b; }
struct S12 { S11 a, b; }
struct S13 { S12 a, b; }
struct S14 { S13 a, b; }
struct S15 { S14 a, b; }
struct S16 { S15 a, b; }
struct S17 { S16 a, b; }
struct S18 { S17 a, b; }
struct S19 { S18 a, b; }
struct S20 { S19 a, b; }
struct S21 { S20 a, b; }
struct S22 { S21 a, b; }
struct S23 { S22 a, b; }
struct S24 { S23 a, b; }
struct S25 { S24 a, b; }
struct S26 { S25 a, b; }
struct S27 { S26 a, b; }
//struct S28 { S27 a, b; } //Can't load type
//struct S29 { S28 a, b; } //Can't load type
//struct S30 { S29 a, b; } //Can't load type
//struct S31 { S30 a, b; } //Can't load type
";
// 0 - pointed-at type
private const string PositiveNumericAdditionCasesTemplate = @"
Helper.AddInt(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddInt(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddInt(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddInt(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
//Helper.AddInt(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
//Helper.AddInt(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddInt(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddInt(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
//Helper.AddInt(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
//Helper.AddInt(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddInt(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddInt(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddInt(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddInt(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddInt(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddInt(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddUInt(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddUInt(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddUInt(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddUInt(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddUInt(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddUInt(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddUInt(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddUInt(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
//Helper.AddUInt(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
//Helper.AddUInt(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddUInt(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddUInt(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddUInt(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddUInt(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddUInt(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddUInt(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddLong(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddLong(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddLong(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddLong(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddLong(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddLong(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddLong(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddLong(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
Helper.AddLong(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
Helper.AddLong(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddLong(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddLong(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddLong(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddLong(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddLong(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddLong(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddULong(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddULong(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddULong(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddULong(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddULong(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddULong(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddULong(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddULong(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
Helper.AddULong(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
Helper.AddULong(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddULong(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddULong(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
Helper.AddULong(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
Helper.AddULong(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddULong(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddULong(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
";
// 0 - pointed-at type
private const string NegativeNumericAdditionCasesTemplate = @"
Helper.AddInt(({0}*)0, -1, ""0 + (-1)"");
Helper.AddInt(({0}*)0, int.MinValue, ""0 + int.MinValue"");
//Helper.AddInt(({0}*)0, long.MinValue, ""0 + long.MinValue"");
Console.WriteLine();
Helper.AddLong(({0}*)0, -1, ""0 + (-1)"");
Helper.AddLong(({0}*)0, int.MinValue, ""0 + int.MinValue"");
Helper.AddLong(({0}*)0, long.MinValue, ""0 + long.MinValue"");
";
// 0 - pointed-at type
private const string PositiveNumericSubtractionCasesTemplate = @"
Helper.SubInt(({0}*)0, 1, ""0 - 1"");
Helper.SubInt(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
//Helper.SubInt(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
//Helper.SubInt(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubInt(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubUInt(({0}*)0, 1, ""0 - 1"");
Helper.SubUInt(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubUInt(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
//Helper.SubUInt(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubUInt(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubLong(({0}*)0, 1, ""0 - 1"");
Helper.SubLong(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubLong(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
Helper.SubLong(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubLong(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubULong(({0}*)0, 1, ""0 - 1"");
Helper.SubULong(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubULong(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
Helper.SubULong(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
Helper.SubULong(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
";
// 0 - pointed-at type
private const string NegativeNumericSubtractionCasesTemplate = @"
Helper.SubInt(({0}*)0, -1, ""0 - -1"");
Helper.SubInt(({0}*)0, int.MinValue, ""0 - int.MinValue"");
Helper.SubInt(({0}*)0, -1 * int.MaxValue, ""0 - -int.MaxValue"");
Console.WriteLine();
Helper.SubLong(({0}*)0, -1L, ""0 - -1"");
Helper.SubLong(({0}*)0, int.MinValue, ""0 - int.MinValue"");
Helper.SubLong(({0}*)0, long.MinValue, ""0 - long.MinValue"");
Helper.SubLong(({0}*)0, -1L * int.MaxValue, ""0 - -int.MaxValue"");
Helper.SubLong(({0}*)0, -1L * uint.MaxValue, ""0 - -uint.MaxValue"");
Helper.SubLong(({0}*)0, -1L * long.MaxValue, ""0 - -long.MaxValue"");
Helper.SubLong(({0}*)0, -1L * long.MaxValue, ""0 - -ulong.MaxValue"");
Helper.SubLong(({0}*)0, -1L * int.MinValue, ""0 - -int.MinValue"");
//Helper.SubLong(({0}*)0, -1L * long.MinValue, ""0 - -long.MinValue"");
";
private static string MakeNumericOverflowTest(string casesTemplate, string pointedAtType, string operationName, string @operator, string checkedness)
{
const string mainClassTemplate = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
{1}
}}
}}
}}
{2}
{3}
";
return string.Format(mainClassTemplate,
checkedness,
string.Format(casesTemplate, pointedAtType),
string.Format(CheckedNumericHelperTemplate, operationName, pointedAtType, @operator, checkedness),
SizedStructs);
}
// Positive numbers, size = 1
[Fact]
public void CheckedNumericAdditionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S00", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: Exception at uint.MaxValue + 1
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: Exception at 1 + uint.MaxValue
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: Exception at 1 + uint.MaxValue
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + long.MaxValue (value = 4294967295)
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: Exception at 1 + uint.MaxValue
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: Exception at uint.MaxValue + 1
AddULong: No exception at 0 + long.MaxValue (value = 4294967295)
AddULong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967295)
AddULong: Exception at 1 + ulong.MaxValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967296)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddLong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddULong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddULong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551615)
AddULong: Exception at 1 + ulong.MaxValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void CheckedNumericAdditionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S02", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: Exception at 0 + int.MaxValue
AddInt: Exception at 1 + int.MaxValue
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: Exception at uint.MaxValue + 1
AddUInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967293)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + int.MaxValue (value = 4294967292)
AddLong: No exception at 1 + int.MaxValue (value = 4294967293)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: Exception at uint.MaxValue + 1
AddLong: Exception at 0 + long.MaxValue
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 4294967292)
AddULong: No exception at 1 + int.MaxValue (value = 4294967293)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: Exception at uint.MaxValue + 1
AddULong: Exception at 0 + long.MaxValue
AddULong: Exception at 1 + long.MaxValue
AddULong: Exception at 0 + ulong.MaxValue
AddULong: Exception at 1 + ulong.MaxValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddUInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddUInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 17179869180)
AddUInt: No exception at 1 + uint.MaxValue (value = 17179869181)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + int.MaxValue (value = 8589934588)
AddLong: No exception at 1 + int.MaxValue (value = 8589934589)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddLong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: Exception at 0 + long.MaxValue
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 8589934588)
AddULong: No exception at 1 + int.MaxValue (value = 8589934589)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddULong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddULong: Exception at 0 + long.MaxValue
AddULong: Exception at 1 + long.MaxValue
AddULong: Exception at 0 + ulong.MaxValue
AddULong: Exception at 1 + ulong.MaxValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void CheckedNumericAdditionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S00", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967295)
AddInt: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + (-1) (value = 4294967295)
AddLong: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551615)
AddInt: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + (-1) (value = 18446744073709551615)
AddLong: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + long.MinValue (value = 9223372036854775808)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: expectedOutput);
}
// Negative numbers, size = 4
[Fact]
public void CheckedNumericAdditionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S02", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967292)
AddInt: Exception at 0 + int.MinValue
AddLong: No exception at 0 + (-1) (value = 4294967292)
AddLong: No exception at 0 + int.MinValue (value = 0)
AddLong: Exception at 0 + long.MinValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551612)
AddInt: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + (-1) (value = 18446744073709551612)
AddLong: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: Exception at 0 + long.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 1
[Fact]
public void CheckedNumericSubtractionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S00", "Sub", "-", "checked");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
SubInt: Exception at 0 - 1
SubInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - 1
SubUInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - 1
SubLong: Exception at 0 - int.MaxValue
SubLong: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - 1
SubULong: Exception at 0 - int.MaxValue
SubULong: Exception at 0 - uint.MaxValue
SubULong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - ulong.MaxValue
");
}
// Positive numbers, size = 4
[Fact]
public void CheckedNumericSubtractionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S02", "Sub", "-", "checked");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
SubInt: Exception at 0 - 1
SubInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - 1
SubUInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - 1
SubLong: Exception at 0 - int.MaxValue
SubLong: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - 1
SubULong: Exception at 0 - int.MaxValue
SubULong: Exception at 0 - uint.MaxValue
SubULong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - ulong.MaxValue
");
}
// Negative numbers, size = 1
[Fact]
public void CheckedNumericSubtractionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S00", "Sub", "-", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
else
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void CheckedNumericSubtractionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S02", "Sub", "-", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: No exception at 0 - int.MinValue (value = 0)
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: No exception at 0 - -int.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void CheckedNumericSubtractionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S* p;
p = (S*)0 + (-1);
System.Console.WriteLine(""No exception from addition"");
try
{
p = (S*)0 - 1;
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception from subtraction"");
}
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: @"
No exception from addition
Exception from subtraction
");
}
[Fact]
public void CheckedNumericAdditionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S* p;
p = (S*)1 + int.MaxValue;
System.Console.WriteLine(""No exception for pointer + int"");
try
{
p = int.MaxValue + (S*)1;
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception for int + pointer"");
}
}
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
No exception for pointer + int
Exception for int + pointer
";
}
else
{
expectedOutput = @"
No exception for pointer + int
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes);
}
[Fact]
public void CheckedPointerSubtractionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)uint.MinValue;
S* q = (S*)uint.MaxValue;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"11";
}
else
{
expectedOutput = @"-4294967295-4294967295";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void CheckedPointerElementAccessQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
fixed (byte* p = new byte[2])
{
p[0] = 12;
// Take a pointer to the second element of the array.
byte* q = p + 1;
// Compute the offset that will wrap around all the way to the preceding byte of memory.
// We do this so that we can overflow, but still end up in valid memory.
ulong offset = sizeof(IntPtr) == sizeof(int) ? uint.MaxValue : ulong.MaxValue;
checked
{
Console.WriteLine(q[offset]);
System.Console.WriteLine(""No exception for element access"");
try
{
Console.WriteLine(*(q + offset));
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception for add-then-dereference"");
}
}
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
12
No exception for element access
Exception for add-then-dereference
");
}
#endregion Checked pointer arithmetic overflow tests
#region Unchecked pointer arithmetic overflow tests
// Positive numbers, size = 1
[Fact]
public void UncheckedNumericAdditionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S00", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 0)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 0)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 0)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 0)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 0)
AddLong: No exception at 0 + long.MaxValue (value = 4294967295)
AddLong: No exception at 1 + long.MaxValue (value = 0)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 0)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 0)
AddULong: No exception at 0 + long.MaxValue (value = 4294967295)
AddULong: No exception at 1 + long.MaxValue (value = 0)
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967295)
AddULong: No exception at 1 + ulong.MaxValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967296)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddLong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddULong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddULong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551615)
AddULong: No exception at 1 + ulong.MaxValue (value = 0)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void UncheckedNumericAdditionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S02", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 3)
AddUInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967293)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 3)
AddLong: No exception at 0 + int.MaxValue (value = 4294967292)
AddLong: No exception at 1 + int.MaxValue (value = 4294967293)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 3)
AddLong: No exception at 0 + long.MaxValue (value = 4294967292)
AddLong: No exception at 1 + long.MaxValue (value = 4294967293)
AddULong: No exception at 0 + int.MaxValue (value = 4294967292)
AddULong: No exception at 1 + int.MaxValue (value = 4294967293)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 3)
AddULong: No exception at 0 + long.MaxValue (value = 4294967292)
AddULong: No exception at 1 + long.MaxValue (value = 4294967293)
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967292)
AddULong: No exception at 1 + ulong.MaxValue (value = 4294967293)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddUInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddUInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 17179869180)
AddUInt: No exception at 1 + uint.MaxValue (value = 17179869181)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + int.MaxValue (value = 8589934588)
AddLong: No exception at 1 + int.MaxValue (value = 8589934589)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddLong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + long.MaxValue (value = 18446744073709551612)
AddLong: No exception at 1 + long.MaxValue (value = 18446744073709551613)
AddULong: No exception at 0 + int.MaxValue (value = 8589934588)
AddULong: No exception at 1 + int.MaxValue (value = 8589934589)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddULong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddULong: No exception at 0 + long.MaxValue (value = 18446744073709551612)
AddULong: No exception at 1 + long.MaxValue (value = 18446744073709551613)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551612)
AddULong: No exception at 1 + ulong.MaxValue (value = 18446744073709551613)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void UncheckedNumericAdditionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S00", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967295)
AddInt: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + (-1) (value = 4294967295)
AddLong: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551615)
AddInt: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + (-1) (value = 18446744073709551615)
AddLong: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + long.MinValue (value = 9223372036854775808)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void UncheckedNumericAdditionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S02", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967292)
AddInt: No exception at 0 + int.MinValue (value = 0)
AddLong: No exception at 0 + (-1) (value = 4294967292)
AddLong: No exception at 0 + int.MinValue (value = 0)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551612)
AddInt: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + (-1) (value = 18446744073709551612)
AddLong: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 1
[Fact]
public void UncheckedNumericSubtractionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S00", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 4294967295)
SubInt: No exception at 0 - int.MaxValue (value = 2147483649)
SubUInt: No exception at 0 - 1 (value = 4294967295)
SubUInt: No exception at 0 - int.MaxValue (value = 2147483649)
SubUInt: No exception at 0 - uint.MaxValue (value = 1)
SubLong: No exception at 0 - 1 (value = 4294967295)
SubLong: No exception at 0 - int.MaxValue (value = 2147483649)
SubLong: No exception at 0 - uint.MaxValue (value = 1)
SubLong: No exception at 0 - long.MaxValue (value = 1)
SubULong: No exception at 0 - 1 (value = 4294967295)
SubULong: No exception at 0 - int.MaxValue (value = 2147483649)
SubULong: No exception at 0 - uint.MaxValue (value = 1)
SubULong: No exception at 0 - long.MaxValue (value = 1)
SubULong: No exception at 0 - ulong.MaxValue (value = 1)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 18446744073709551615)
SubInt: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubUInt: No exception at 0 - 1 (value = 18446744073709551615)
SubUInt: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubUInt: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubLong: No exception at 0 - 1 (value = 18446744073709551615)
SubLong: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubLong: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubLong: No exception at 0 - long.MaxValue (value = 9223372036854775809)
SubULong: No exception at 0 - 1 (value = 18446744073709551615)
SubULong: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubULong: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubULong: No exception at 0 - long.MaxValue (value = 9223372036854775809)
SubULong: No exception at 0 - ulong.MaxValue (value = 1)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void UncheckedNumericSubtractionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S02", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 4294967292)
SubInt: No exception at 0 - int.MaxValue (value = 4)
SubUInt: No exception at 0 - 1 (value = 4294967292)
SubUInt: No exception at 0 - int.MaxValue (value = 4)
SubUInt: No exception at 0 - uint.MaxValue (value = 4)
SubLong: No exception at 0 - 1 (value = 4294967292)
SubLong: No exception at 0 - int.MaxValue (value = 4)
SubLong: No exception at 0 - uint.MaxValue (value = 4)
SubLong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - 1 (value = 4294967292)
SubULong: No exception at 0 - int.MaxValue (value = 4)
SubULong: No exception at 0 - uint.MaxValue (value = 4)
SubULong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - ulong.MaxValue (value = 4)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 18446744073709551612)
SubInt: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubUInt: No exception at 0 - 1 (value = 18446744073709551612)
SubUInt: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubUInt: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubLong: No exception at 0 - 1 (value = 18446744073709551612)
SubLong: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubLong: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubLong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - 1 (value = 18446744073709551612)
SubULong: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubULong: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubULong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - ulong.MaxValue (value = 4)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void UncheckedNumericSubtractionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S00", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 1)
SubInt: No exception at 0 - int.MinValue (value = 2147483648)
SubInt: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -1 (value = 1)
SubLong: No exception at 0 - int.MinValue (value = 2147483648)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -long.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -ulong.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -int.MinValue (value = 2147483648)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 1)
SubInt: No exception at 0 - int.MinValue (value = 2147483648)
SubInt: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -1 (value = 1)
SubLong: No exception at 0 - int.MinValue (value = 2147483648)
SubLong: No exception at 0 - long.MinValue (value = 9223372036854775808)
SubLong: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -long.MaxValue (value = 9223372036854775807)
SubLong: No exception at 0 - -ulong.MaxValue (value = 9223372036854775807)
SubLong: No exception at 0 - -int.MinValue (value = 18446744071562067968)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void UncheckedNumericSubtractionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S02", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 4)
SubInt: No exception at 0 - int.MinValue (value = 0)
SubInt: No exception at 0 - -int.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -1 (value = 4)
SubLong: No exception at 0 - int.MinValue (value = 0)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -long.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -ulong.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -int.MinValue (value = 0)";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 4)
SubInt: No exception at 0 - int.MinValue (value = 8589934592)
SubInt: No exception at 0 - -int.MaxValue (value = 8589934588)
SubLong: No exception at 0 - -1 (value = 4)
SubLong: No exception at 0 - int.MinValue (value = 8589934592)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 8589934588)
SubLong: No exception at 0 - -uint.MaxValue (value = 17179869180)
SubLong: No exception at 0 - -long.MaxValue (value = 18446744073709551612)
SubLong: No exception at 0 - -ulong.MaxValue (value = 18446744073709551612)
SubLong: No exception at 0 - -int.MinValue (value = 18446744065119617024)";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
#endregion Unchecked pointer arithmetic overflow tests
#region Pointer comparison tests
[Fact]
public void PointerComparisonSameType()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)0;
S* q = (S*)1;
unchecked
{
Write(p == q);
Write(p != q);
Write(p <= q);
Write(p >= q);
Write(p < q);
Write(p > q);
}
checked
{
Write(p == q);
Write(p != q);
Write(p <= q);
Write(p >= q);
Write(p < q);
Write(p > q);
}
}
static void Write(bool b)
{
Console.Write(b ? 1 : 0);
}
}
";
// NOTE: all comparisons unsigned.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "011010011010", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 133 (0x85)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.1
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: ceq
IL_000a: call ""void S.Write(bool)""
IL_000f: ldloc.0
IL_0010: ldloc.1
IL_0011: ceq
IL_0013: ldc.i4.0
IL_0014: ceq
IL_0016: call ""void S.Write(bool)""
IL_001b: ldloc.0
IL_001c: ldloc.1
IL_001d: cgt.un
IL_001f: ldc.i4.0
IL_0020: ceq
IL_0022: call ""void S.Write(bool)""
IL_0027: ldloc.0
IL_0028: ldloc.1
IL_0029: clt.un
IL_002b: ldc.i4.0
IL_002c: ceq
IL_002e: call ""void S.Write(bool)""
IL_0033: ldloc.0
IL_0034: ldloc.1
IL_0035: clt.un
IL_0037: call ""void S.Write(bool)""
IL_003c: ldloc.0
IL_003d: ldloc.1
IL_003e: cgt.un
IL_0040: call ""void S.Write(bool)""
IL_0045: ldloc.0
IL_0046: ldloc.1
IL_0047: ceq
IL_0049: call ""void S.Write(bool)""
IL_004e: ldloc.0
IL_004f: ldloc.1
IL_0050: ceq
IL_0052: ldc.i4.0
IL_0053: ceq
IL_0055: call ""void S.Write(bool)""
IL_005a: ldloc.0
IL_005b: ldloc.1
IL_005c: cgt.un
IL_005e: ldc.i4.0
IL_005f: ceq
IL_0061: call ""void S.Write(bool)""
IL_0066: ldloc.0
IL_0067: ldloc.1
IL_0068: clt.un
IL_006a: ldc.i4.0
IL_006b: ceq
IL_006d: call ""void S.Write(bool)""
IL_0072: ldloc.0
IL_0073: ldloc.1
IL_0074: clt.un
IL_0076: call ""void S.Write(bool)""
IL_007b: ldloc.0
IL_007c: ldloc.1
IL_007d: cgt.un
IL_007f: call ""void S.Write(bool)""
IL_0084: ret
}
");
}
[Fact, WorkItem(49639, "https://github.com/dotnet/roslyn/issues/49639")]
public void CompareToNullWithNestedUnconstrainedTypeParameter()
{
var verifier = CompileAndVerify(@"
using System;
unsafe
{
test<int>(null);
S<int> s = default;
test<int>(&s);
static void test<T>(S<T>* s)
{
Console.WriteLine(s == null);
Console.WriteLine(s is null);
}
}
struct S<T> {}
", options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
True
True
False
False", verify: Verification.Skipped);
verifier.VerifyIL("Program.<<Main>$>g__test|0_0<T>(S<T>*)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: conv.u
IL_000d: ceq
IL_000f: call ""void System.Console.WriteLine(bool)""
IL_0014: ret
}
");
}
[Fact, WorkItem(49639, "https://github.com/dotnet/roslyn/issues/49639")]
public void CompareToNullWithPointerToUnmanagedTypeParameter()
{
var verifier = CompileAndVerify(@"
using System;
unsafe
{
test<int>(null);
int i = 0;
test<int>(&i);
static void test<T>(T* t) where T : unmanaged
{
Console.WriteLine(t == null);
Console.WriteLine(t is null);
}
}
", options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
True
True
False
False", verify: Verification.Skipped);
verifier.VerifyIL("Program.<<Main>$>g__test|0_0<T>(T*)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: conv.u
IL_000d: ceq
IL_000f: call ""void System.Console.WriteLine(bool)""
IL_0014: ret
}
");
}
[Theory]
[InlineData("int*")]
[InlineData("delegate*<void>")]
[InlineData("T*")]
[InlineData("delegate*<T>")]
public void CompareToNullInPatternOutsideUnsafe(string pointerType)
{
var comp = CreateCompilation($@"
var c = default(S<int>);
_ = c.Field is null;
unsafe struct S<T> where T : unmanaged
{{
#pragma warning disable CS0649 // Field is unassigned
public {pointerType} Field;
}}
", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (3,5): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// _ = c.Field is null;
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "c.Field").WithLocation(3, 5)
);
}
#endregion Pointer comparison tests
#region stackalloc tests
[Fact]
public void SimpleStackAlloc()
{
var text = @"
unsafe class C
{
void M()
{
int count = 1;
checked
{
int* p = stackalloc int[2];
char* q = stackalloc char[count];
Use(p);
Use(q);
}
unchecked
{
int* p = stackalloc int[2];
char* q = stackalloc char[count];
Use(p);
Use(q);
}
}
static void Use(int * ptr)
{
}
static void Use(char * ptr)
{
}
}
";
// NOTE: conversion is always unchecked, multiplication is always checked.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (int V_0, //count
int* V_1, //p
int* V_2) //p
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.8
IL_0003: conv.u
IL_0004: localloc
IL_0006: stloc.1
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.2
IL_000a: mul.ovf.un
IL_000b: localloc
IL_000d: ldloc.1
IL_000e: call ""void C.Use(int*)""
IL_0013: call ""void C.Use(char*)""
IL_0018: ldc.i4.8
IL_0019: conv.u
IL_001a: localloc
IL_001c: stloc.2
IL_001d: ldloc.0
IL_001e: conv.u
IL_001f: ldc.i4.2
IL_0020: mul.ovf.un
IL_0021: localloc
IL_0023: ldloc.2
IL_0024: call ""void C.Use(int*)""
IL_0029: call ""void C.Use(char*)""
IL_002e: ret
}
");
}
[Fact]
public void StackAllocConversion()
{
var text = @"
unsafe class C
{
void M()
{
void* p = stackalloc int[2];
C q = stackalloc int[2];
}
public static implicit operator C(int* p)
{
return null;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 16 (0x10)
.maxstack 1
.locals init (void* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.u
IL_0002: localloc
IL_0004: stloc.0
IL_0005: ldc.i4.8
IL_0006: conv.u
IL_0007: localloc
IL_0009: call ""C C.op_Implicit(int*)""
IL_000e: pop
IL_000f: ret
}
");
}
[Fact]
public void StackAllocConversionZero()
{
var text = @"
unsafe class C
{
void M()
{
void* p = stackalloc int[0];
C q = stackalloc int[0];
}
public static implicit operator C(int* p)
{
return null;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (void* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldc.i4.0
IL_0004: conv.u
IL_0005: call ""C C.op_Implicit(int*)""
IL_000a: pop
IL_000b: ret
}
");
}
[Fact]
public void StackAllocSpecExample() //Section 18.8
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(IntToString(123));
Console.WriteLine(IntToString(-456));
}
static string IntToString(int value) {
int n = value >= 0? value: -value;
unsafe {
char* buffer = stackalloc char[16];
char* p = buffer + 16;
do {
*--p = (char)(n % 10 + '0');
n /= 10;
} while (n != 0);
if (value < 0) *--p = '-';
return new string(p, 0, (int)(buffer + 16 - p));
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"123
-456
");
}
// See MethodToClassRewriter.VisitAssignmentOperator for an explanation.
[Fact]
public void StackAllocIntoHoistedLocal1()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
var p = stackalloc int[2];
var q = stackalloc int[2];
Action a = () =>
{
var r = stackalloc int[2];
var s = stackalloc int[2];
Action b = () =>
{
p = null; //capture p
r = null; //capture r
};
Use(s);
};
Use(q);
}
static void Use(int * ptr)
{
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
// Note that the stackalloc for p is written into a temp *before* the receiver (i.e. "this")
// for C.<>c__DisplayClass0.p is pushed onto the stack.
verifier.VerifyIL("C.Main", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.8
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* C.<>c__DisplayClass0_0.p""
IL_0012: ldc.i4.8
IL_0013: conv.u
IL_0014: localloc
IL_0016: call ""void C.Use(int*)""
IL_001b: ret
}
");
// Check that the same thing works inside a lambda.
verifier.VerifyIL("C.<>c__DisplayClass0_0.<Main>b__0", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (C.<>c__DisplayClass0_1 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""C.<>c__DisplayClass0_1..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_000d: ldc.i4.8
IL_000e: conv.u
IL_000f: localloc
IL_0011: stloc.1
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: stfld ""int* C.<>c__DisplayClass0_1.r""
IL_0019: ldc.i4.8
IL_001a: conv.u
IL_001b: localloc
IL_001d: call ""void C.Use(int*)""
IL_0022: ret
}
");
}
// See MethodToClassRewriter.VisitAssignmentOperator for an explanation.
[Fact]
public void StackAllocIntoHoistedLocal2()
{
// From native bug #59454 (in DevDiv collection)
var text = @"
unsafe class T
{
delegate int D();
static void Main()
{
int* v = stackalloc int[1];
D d = delegate { return *v; };
System.Console.WriteLine(d());
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails).VerifyIL("T.Main", @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (T.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""T.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.4
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* T.<>c__DisplayClass1_0.v""
IL_0012: ldloc.0
IL_0013: ldftn ""int T.<>c__DisplayClass1_0.<Main>b__0()""
IL_0019: newobj ""T.D..ctor(object, System.IntPtr)""
IL_001e: callvirt ""int T.D.Invoke()""
IL_0023: call ""void System.Console.WriteLine(int)""
IL_0028: ret
}
");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails).VerifyIL("T.Main", @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (T.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""T.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.4
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* T.<>c__DisplayClass1_0.v""
IL_0012: ldloc.0
IL_0013: ldftn ""int T.<>c__DisplayClass1_0.<Main>b__0()""
IL_0019: newobj ""T.D..ctor(object, System.IntPtr)""
IL_001e: callvirt ""int T.D.Invoke()""
IL_0023: call ""void System.Console.WriteLine(int)""
IL_0028: ret
}
");
}
[Fact]
public void CSLegacyStackallocUse32bitChecked()
{
// This is from C# Legacy test where it uses Perl script to call ildasm and check 'mul.ovf' emitted
// $Roslyn\Main\LegacyTest\CSharp\Source\csharp\Source\Conformance\unsafecode\stackalloc\regr001.cs
var text = @"// <Title>Should checked affect stackalloc?</Title>
// <Description>
// The lower level localloc MSIL instruction takes an unsigned native int as input; however the higher level
// stackalloc uses only 32-bits. The example shows the operation overflowing the 32-bit multiply which leads to
// a curious edge condition.
// If compile with /checked we insert a mul.ovf instruction, and this causes a system overflow exception at runtime.
// </Description>
// <RelatedBugs>VSW:489857</RelatedBugs>
using System;
public class C
{
private static unsafe int Main()
{
Int64* intArray = stackalloc Int64[0x7fffffff];
return (int)intArray[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldc.i4 0x7fffffff
IL_0005: conv.u
IL_0006: ldc.i4.8
IL_0007: mul.ovf.un
IL_0008: localloc
IL_000a: ldind.i8
IL_000b: conv.i4
IL_000c: ret
}
");
}
#endregion stackalloc tests
#region Functional tests
[Fact]
public void BubbleSort()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
BubbleSort();
BubbleSort(1);
BubbleSort(2, 1);
BubbleSort(3, 1, 2);
BubbleSort(3, 1, 4, 2);
}
static void BubbleSort(params int[] array)
{
if (array == null)
{
return;
}
fixed (int* begin = array)
{
BubbleSort(begin, end: begin + array.Length);
}
Console.WriteLine(string.Join("", "", array));
}
private static void BubbleSort(int* begin, int* end)
{
for (int* firstUnsorted = begin; firstUnsorted < end; firstUnsorted++)
{
for (int* current = firstUnsorted; current + 1 < end; current++)
{
if (current[0] > current[1])
{
SwapWithNext(current);
}
}
}
}
static void SwapWithNext(int* p)
{
int temp = *p;
p[0] = p[1];
p[1] = temp;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
1
1, 2
1, 2, 3
1, 2, 3, 4");
}
[Fact]
public void BigStructs()
{
var text = @"
unsafe class C
{
static void Main()
{
void* v;
CheckOverflow(""(S15*)0 + sizeof(S15)"", () => v = checked((S15*)0 + sizeof(S15)));
CheckOverflow(""(S15*)0 + sizeof(S16)"", () => v = checked((S15*)0 + sizeof(S16)));
CheckOverflow(""(S16*)0 + sizeof(S15)"", () => v = checked((S16*)0 + sizeof(S15)));
}
static void CheckOverflow(string description, System.Action operation)
{
try
{
operation();
System.Console.WriteLine(""No overflow from {0}"", description);
}
catch (System.OverflowException)
{
System.Console.WriteLine(""Overflow from {0}"", description);
}
}
}
" + SizedStructs;
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
No overflow from (S15*)0 + sizeof(S15)
Overflow from (S15*)0 + sizeof(S16)
Overflow from (S16*)0 + sizeof(S15)";
}
else
{
expectedOutput = @"
No overflow from (S15*)0 + sizeof(S15)
No overflow from (S15*)0 + sizeof(S16)
No overflow from (S16*)0 + sizeof(S15)";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void LambdaConversion()
{
var text = @"
using System;
class Program
{
static void Main()
{
Goo(x => { });
}
static void Goo(F1 f) { Console.WriteLine(1); }
static void Goo(F2 f) { Console.WriteLine(2); }
}
unsafe delegate void F1(int* x);
delegate void F2(int x);
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Passes);
}
[Fact]
public void LocalVariableReuse()
{
var text = @"
unsafe class C
{
int this[string s] { get { return 0; } set { } }
void Test()
{
{
this[""not pinned"".ToString()] += 2; //creates an unpinned string local (for the argument)
}
fixed (char* p = ""pinned"") //creates a pinned string local
{
}
{
this[""not pinned"".ToString()] += 2; //reuses the unpinned string local
}
fixed (char* p = ""pinned"") //reuses the pinned string local
{
}
}
}
";
// NOTE: one pinned string temp and one unpinned string temp.
// That is, pinned temps are reused in by other pinned temps
// but not by unpinned temps and vice versa.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.Test", @"
{
// Code size 99 (0x63)
.maxstack 4
.locals init (string V_0,
char* V_1, //p
pinned string V_2,
char* V_3) //p
IL_0000: ldstr ""not pinned""
IL_0005: callvirt ""string object.ToString()""
IL_000a: stloc.0
IL_000b: ldarg.0
IL_000c: ldloc.0
IL_000d: ldarg.0
IL_000e: ldloc.0
IL_000f: call ""int C.this[string].get""
IL_0014: ldc.i4.2
IL_0015: add
IL_0016: call ""void C.this[string].set""
IL_001b: ldstr ""pinned""
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: conv.u
IL_0023: stloc.1
IL_0024: ldloc.1
IL_0025: brfalse.s IL_002f
IL_0027: ldloc.1
IL_0028: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_002d: add
IL_002e: stloc.1
IL_002f: ldnull
IL_0030: stloc.2
IL_0031: ldstr ""not pinned""
IL_0036: callvirt ""string object.ToString()""
IL_003b: stloc.0
IL_003c: ldarg.0
IL_003d: ldloc.0
IL_003e: ldarg.0
IL_003f: ldloc.0
IL_0040: call ""int C.this[string].get""
IL_0045: ldc.i4.2
IL_0046: add
IL_0047: call ""void C.this[string].set""
IL_004c: ldstr ""pinned""
IL_0051: stloc.2
IL_0052: ldloc.2
IL_0053: conv.u
IL_0054: stloc.3
IL_0055: ldloc.3
IL_0056: brfalse.s IL_0060
IL_0058: ldloc.3
IL_0059: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_005e: add
IL_005f: stloc.3
IL_0060: ldnull
IL_0061: stloc.2
IL_0062: ret
}");
}
[WorkItem(544229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544229")]
[Fact]
public void UnsafeTypeAsAttributeArgument()
{
var template = @"
using System;
namespace System
{{
class Int32 {{ }}
}}
[A(Type = typeof({0}))]
class A : Attribute
{{
public Type Type;
static void Main()
{{
var a = (A)typeof(A).GetCustomAttributes(false)[0];
Console.WriteLine(a.Type == typeof({0}));
}}
}}
";
CompileAndVerify(string.Format(template, "int"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int*"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int**"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int[]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int[][]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int*[]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
}
#endregion Functional tests
#region Regression tests
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void MixedSafeAndUnsafeFields()
{
var text =
@"struct Perf_Contexts
{
int data;
private int SuppressUnused(int x) { data = x; return data; }
}
public sealed class ChannelServices
{
static unsafe Perf_Contexts* GetPrivateContextsPerfCounters() { return null; }
private static int I1 = 12;
unsafe private static Perf_Contexts* perf_Contexts = GetPrivateContextsPerfCounters();
private static int I2 = 13;
private static int SuppressUnused(int x) { return I1 + I2; }
}
public class Test
{
public static void Main()
{
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails).VerifyDiagnostics();
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void SafeFieldBeforeUnsafeField()
{
var text = @"
class C
{
int x = 1;
unsafe int* p = (int*)2;
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics(
// (4,9): warning CS0414: The field 'C.x' is assigned but its value is never used
// int x = 1;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x"));
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void SafeFieldAfterUnsafeField()
{
var text = @"
class C
{
unsafe int* p = (int*)2;
int x = 1;
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics(
// (5,9): warning CS0414: The field 'C.x' is assigned but its value is never used
// int x = 1;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x"));
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026"), WorkItem(598170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598170")]
[Fact]
public void FixedPassByRef()
{
var text = @"
class Test
{
unsafe static int printAddress(out int* pI)
{
pI = null;
System.Console.WriteLine((ulong)pI);
return 1;
}
unsafe static int printAddress1(ref int* pI)
{
pI = null;
System.Console.WriteLine((ulong)pI);
return 1;
}
static int Main()
{
int retval = 0;
S s = new S();
unsafe
{
retval = Test.printAddress(out s.i);
retval = Test.printAddress1(ref s.i);
}
if (retval == 0)
System.Console.WriteLine(""Failed."");
return retval;
}
}
unsafe struct S
{
public fixed int i[1];
}
";
var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (24,44): error CS1510: A ref or out argument must be an assignable variable
// retval = Test.printAddress(out s.i);
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "s.i"),
// (25,45): error CS1510: A ref or out argument must be an assignable variable
// retval = Test.printAddress1(ref s.i);
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "s.i"));
}
[Fact, WorkItem(545293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545293"), WorkItem(881188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/881188")]
public void EmptyAndFixedBufferStructIsInitialized()
{
var text = @"
public struct EmptyStruct { }
unsafe public struct FixedStruct { fixed char c[10]; }
public struct OuterStruct
{
EmptyStruct ES;
FixedStruct FS;
override public string ToString() { return (ES.ToString() + FS.ToString()); }
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyDiagnostics(
// (8,17): warning CS0649: Field 'OuterStruct.FS' is never assigned to, and will always have its default value
// FixedStruct FS;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "FS").WithArguments("OuterStruct.FS", "").WithLocation(8, 17),
// (7,17): warning CS0649: Field 'OuterStruct.ES' is never assigned to, and will always have its default value
// EmptyStruct ES;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ES").WithArguments("OuterStruct.ES", "").WithLocation(7, 17)
);
}
[Fact, WorkItem(545296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545296"), WorkItem(545999, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545999")]
public void FixedBufferAndStatementWithFixedArrayElementAsInitializer()
{
var text = @"
unsafe public struct FixedStruct
{
fixed int i[1];
fixed char c[10];
override public string ToString() {
fixed (char* pc = this.c) { return pc[0].ToString(); }
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics();
comp.VerifyIL("FixedStruct.ToString", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: ldflda ""char* FixedStruct.c""
IL_0006: ldflda ""char FixedStruct.<c>e__FixedBuffer.FixedElementField""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: call ""string char.ToString()""
IL_0013: ret
}
");
}
[Fact]
public void FixedBufferAndStatementWithFixedArrayElementAsInitializerExe()
{
var text = @"
class Program
{
unsafe static void Main(string[] args)
{
FixedStruct s = new FixedStruct();
s.c[0] = 'A';
s.c[1] = 'B';
s.c[2] = 'C';
FixedStruct[] arr = { s };
System.Console.Write(arr[0].ToString());
}
}
unsafe public struct FixedStruct
{
public fixed char c[10];
override public string ToString()
{
fixed (char* pc = this.c)
{
System.Console.Write(pc[0]);
System.Console.Write(pc[1].ToString());
return pc[2].ToString();
}
}
}";
var comp = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "ABC", verify: Verification.Fails).VerifyDiagnostics();
comp.VerifyIL("FixedStruct.ToString", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: ldflda ""char* FixedStruct.c""
IL_0006: ldflda ""char FixedStruct.<c>e__FixedBuffer.FixedElementField""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: dup
IL_000f: ldind.u2
IL_0010: call ""void System.Console.Write(char)""
IL_0015: dup
IL_0016: ldc.i4.2
IL_0017: add
IL_0018: call ""string char.ToString()""
IL_001d: call ""void System.Console.Write(string)""
IL_0022: ldc.i4.2
IL_0023: conv.i
IL_0024: ldc.i4.2
IL_0025: mul
IL_0026: add
IL_0027: call ""string char.ToString()""
IL_002c: ret
}
");
}
[Fact, WorkItem(545299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545299")]
public void FixedStatementInlambda()
{
var text = @"
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
unsafe class C<T> where T : struct
{
public void Goo()
{
Func<T, char> d = delegate
{
fixed (char* p = ""blah"")
{
for (char* pp = p; pp != null; pp++)
return *pp;
}
return 'c';
};
Console.WriteLine(d(default(T)));
}
}
class A
{
static void Main()
{
new C<int>().Goo();
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "b", verify: Verification.Fails);
}
[Fact, WorkItem(546865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546865")]
public void DontStackScheduleLocalPerformingPointerConversion()
{
var text = @"
using System;
unsafe struct S1
{
public char* charPointer;
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1();
fixed (char* p = ""hello"")
{
s1.charPointer = p;
ulong UserData = (ulong)&s1;
Test1(UserData);
}
}
static void Test1(ulong number)
{
S1* structPointer = (S1*)number;
Console.WriteLine(new string(structPointer->charPointer));
}
static ulong Test2()
{
S1* structPointer = (S1*)null; // null to pointer
int* intPointer = (int*)structPointer; // pointer to pointer
void* voidPointer = (void*)intPointer; // pointer to void
ulong number = (ulong)voidPointer; // pointer to integer
return number;
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "hello", verify: Verification.Fails);
// Note that the pointer local is not scheduled on the stack.
verifier.VerifyIL("Test.Test1", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S1* V_0) //structPointer
IL_0000: ldarg.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldfld ""char* S1.charPointer""
IL_0009: newobj ""string..ctor(char*)""
IL_000e: call ""void System.Console.WriteLine(string)""
IL_0013: ret
}");
// All locals retained.
verifier.VerifyIL("Test.Test2", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (S1* V_0, //structPointer
int* V_1, //intPointer
void* V_2) //voidPointer
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: conv.u8
IL_0009: ret
}");
}
[Fact, WorkItem(546807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546807")]
public void PointerMemberAccessReadonlyField()
{
var text = @"
using System;
unsafe class C
{
public S1* S1;
}
unsafe struct S1
{
public readonly int* X;
public int* Y;
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1();
C c = new C();
c.S1 = &s1;
Console.WriteLine(null == c.S1->X);
Console.WriteLine(null == c.S1->Y);
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
True
True");
// NOTE: ldobj before ldfld S1.X, but not before ldfld S1.Y.
verifier.VerifyIL("Test.Main", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (S1 V_0, //s1
C V_1) //c
IL_0000: ldloca.s V_0
IL_0002: initobj ""S1""
IL_0008: newobj ""C..ctor()""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldloca.s V_0
IL_0011: conv.u
IL_0012: stfld ""S1* C.S1""
IL_0017: ldc.i4.0
IL_0018: conv.u
IL_0019: ldloc.1
IL_001a: ldfld ""S1* C.S1""
IL_001f: ldfld ""int* S1.X""
IL_0024: ceq
IL_0026: call ""void System.Console.WriteLine(bool)""
IL_002b: ldc.i4.0
IL_002c: conv.u
IL_002d: ldloc.1
IL_002e: ldfld ""S1* C.S1""
IL_0033: ldfld ""int* S1.Y""
IL_0038: ceq
IL_003a: call ""void System.Console.WriteLine(bool)""
IL_003f: ret
}
");
}
[Fact, WorkItem(546807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546807")]
public void PointerMemberAccessCall()
{
var text = @"
using System;
unsafe class C
{
public S1* S1;
}
unsafe struct S1
{
public int X;
public void Instance()
{
Console.WriteLine(this.X);
}
}
static class Extensions
{
public static void Extension(this S1 s1)
{
Console.WriteLine(s1.X);
}
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1 { X = 2 };
C c = new C();
c.S1 = &s1;
c.S1->Instance();
c.S1->Extension();
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
2
2");
// NOTE: ldobj before extension call, but not before instance call.
verifier.VerifyIL("Test.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S1 V_0, //s1
S1 V_1)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S1""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.2
IL_000b: stfld ""int S1.X""
IL_0010: ldloc.1
IL_0011: stloc.0
IL_0012: newobj ""C..ctor()""
IL_0017: dup
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: stfld ""S1* C.S1""
IL_0020: dup
IL_0021: ldfld ""S1* C.S1""
IL_0026: call ""void S1.Instance()""
IL_002b: ldfld ""S1* C.S1""
IL_0030: ldobj ""S1""
IL_0035: call ""void Extensions.Extension(S1)""
IL_003a: ret
}");
}
[Fact, WorkItem(531327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531327")]
public void PointerParameter()
{
var text = @"
using System;
unsafe struct S1
{
static void M(N.S2* ps2){}
}
namespace N
{
public struct S2
{
public int F;
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll.WithConcurrentBuild(false), verify: Verification.Passes);
}
[Fact, WorkItem(531327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531327")]
public void PointerReturn()
{
var text = @"
using System;
namespace N
{
public struct S2
{
public int F;
}
}
unsafe struct S1
{
static N.S2* M(int ps2){return null;}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll.WithConcurrentBuild(false), verify: Verification.Fails);
}
[Fact, WorkItem(748530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/748530")]
public void Repro748530()
{
var text = @"
unsafe class A
{
public unsafe struct ListNode
{
internal ListNode(int data, ListNode* pNext)
{
}
}
}
";
var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics();
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
uint offset = 0x80000000;
byte* wrong = data + offset;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (byte* V_0, //data
uint V_1, //offset
byte* V_2) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldc.i4 0x80000000
IL_000c: stloc.1
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: add
IL_0011: stloc.2
IL_0012: ldstr ""{0:X}""
IL_0017: ldloc.2
IL_0018: conv.u8
IL_0019: box ""ulong""
IL_001e: call ""void System.Console.WriteLine(string, object)""
IL_0023: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv001()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
short* data = (short*)0x76543210;
uint offset = 0x40000000;
short* wrong = data + offset;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 40 (0x28)
.maxstack 3
.locals init (short* V_0, //data
uint V_1, //offset
short* V_2) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldc.i4 0x40000000
IL_000c: stloc.1
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: conv.u8
IL_0010: ldc.i4.2
IL_0011: conv.i8
IL_0012: mul
IL_0013: conv.i
IL_0014: add
IL_0015: stloc.2
IL_0016: ldstr ""{0:X}""
IL_001b: ldloc.2
IL_001c: conv.u8
IL_001d: box ""ulong""
IL_0022: call ""void System.Console.WriteLine(string, object)""
IL_0027: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv002()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
byte* wrong = data + 0x80000000u;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (byte* V_0, //data
byte* V_1) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4 0x80000000
IL_000d: conv.u
IL_000e: add
IL_000f: stloc.1
IL_0010: ldstr ""{0:X}""
IL_0015: ldloc.1
IL_0016: conv.u8
IL_0017: box ""ulong""
IL_001c: call ""void System.Console.WriteLine(string, object)""
IL_0021: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv002a()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
byte* wrong = data + 0x7FFFFFFFu;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F654320F", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (byte* V_0, //data
byte* V_1) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4 0x7fffffff
IL_000d: add
IL_000e: stloc.1
IL_000f: ldstr ""{0:X}""
IL_0014: ldloc.1
IL_0015: conv.u8
IL_0016: box ""ulong""
IL_001b: call ""void System.Console.WriteLine(string, object)""
IL_0020: ret
}
");
}
[WorkItem(857598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/857598")]
[Fact]
public void VoidToNullable()
{
var text = @"
unsafe class C
{
public int? x = (int?)(void*)0;
}
class c1
{
public static void Main()
{
var x = new C();
System.Console.WriteLine(x.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Passes);
compVerifier.VerifyIL("C..ctor", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.i
IL_0003: conv.i4
IL_0004: newobj ""int?..ctor(int)""
IL_0009: stfld ""int? C.x""
IL_000e: ldarg.0
IL_000f: call ""object..ctor()""
IL_0014: ret
}
");
}
[WorkItem(907771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907771")]
[Fact]
public void UnsafeBeforeReturn001()
{
var text = @"
using System;
public unsafe class C
{
private static readonly byte[] _emptyArray = new byte[0];
public static void Main()
{
System.Console.WriteLine(ToManagedByteArray(2));
}
public static byte[] ToManagedByteArray(uint byteCount)
{
if (byteCount == 0)
{
return _emptyArray; // degenerate case
}
else
{
byte[] bytes = new byte[byteCount];
fixed (byte* pBytes = bytes)
{
}
return bytes;
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "System.Byte[]", verify: Verification.Fails);
compVerifier.VerifyIL("C.ToManagedByteArray", @"
{
// Code size 42 (0x2a)
.maxstack 3
.locals init (byte* V_0, //pBytes
pinned byte[] V_1)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0009
IL_0003: ldsfld ""byte[] C._emptyArray""
IL_0008: ret
IL_0009: ldarg.0
IL_000a: newarr ""byte""
IL_000f: dup
IL_0010: dup
IL_0011: stloc.1
IL_0012: brfalse.s IL_0019
IL_0014: ldloc.1
IL_0015: ldlen
IL_0016: conv.i4
IL_0017: brtrue.s IL_001e
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: br.s IL_0027
IL_001e: ldloc.1
IL_001f: ldc.i4.0
IL_0020: ldelema ""byte""
IL_0025: conv.u
IL_0026: stloc.0
IL_0027: ldnull
IL_0028: stloc.1
IL_0029: ret
}
");
}
[WorkItem(907771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907771")]
[Fact]
public void UnsafeBeforeReturn002()
{
var text = @"
using System;
public unsafe class C
{
private static readonly byte[] _emptyArray = new byte[0];
public static void Main()
{
System.Console.WriteLine(ToManagedByteArray(2));
}
public static byte[] ToManagedByteArray(uint byteCount)
{
if (byteCount == 0)
{
return _emptyArray; // degenerate case
}
else
{
byte[] bytes = new byte[byteCount];
fixed (byte* pBytes = bytes)
{
}
return bytes;
}
}
}
";
var v = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: "System.Byte[]", verify: Verification.Fails);
v.VerifyIL("C.ToManagedByteArray", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (bool V_0,
byte[] V_1,
byte[] V_2, //bytes
byte* V_3, //pBytes
pinned byte[] V_4)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: ceq
IL_0005: stloc.0
~IL_0006: ldloc.0
IL_0007: brfalse.s IL_0012
-IL_0009: nop
-IL_000a: ldsfld ""byte[] C._emptyArray""
IL_000f: stloc.1
IL_0010: br.s IL_003e
-IL_0012: nop
-IL_0013: ldarg.0
IL_0014: newarr ""byte""
IL_0019: stloc.2
-IL_001a: ldloc.2
IL_001b: dup
IL_001c: stloc.s V_4
IL_001e: brfalse.s IL_0026
IL_0020: ldloc.s V_4
IL_0022: ldlen
IL_0023: conv.i4
IL_0024: brtrue.s IL_002b
IL_0026: ldc.i4.0
IL_0027: conv.u
IL_0028: stloc.3
IL_0029: br.s IL_0035
IL_002b: ldloc.s V_4
IL_002d: ldc.i4.0
IL_002e: ldelema ""byte""
IL_0033: conv.u
IL_0034: stloc.3
-IL_0035: nop
-IL_0036: nop
~IL_0037: ldnull
IL_0038: stloc.s V_4
-IL_003a: ldloc.2
IL_003b: stloc.1
IL_003c: br.s IL_003e
-IL_003e: ldloc.1
IL_003f: ret
}
", sequencePoints: "C.ToManagedByteArray");
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void SystemIntPtrInSignature_BreakingChange()
{
// NOTE: the IL is intentionally not compliant with ECMA spec
// in particular Metadata spec II.23.2.16 (Short form signatures) says that
// [mscorlib]System.IntPtr is not supposed to be used in metadata
// and short-version 'native int' is supposed to be used instead.
var ilSource =
@"
.class public AddressHelper{
.method public hidebysig static valuetype [mscorlib]System.IntPtr AddressOf<T>(!!0& t){
ldarg 0
ldind.i
ret
}
}
";
var csharpSource =
@"
class Program
{
static void Main(string[] args)
{
var s = string.Empty;
var i = AddressHelper.AddressOf(ref s);
System.Console.WriteLine(i);
}
}
";
var cscomp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource);
var expected = new[] {
// (7,35): error CS0570: 'AddressHelper.AddressOf<T>(?)' is not supported by the language
// var i = AddressHelper.AddressOf(ref s);
Diagnostic(ErrorCode.ERR_BindToBogus, "AddressOf").WithArguments("AddressHelper.AddressOf<T>(?)").WithLocation(7, 35)
};
cscomp.VerifyDiagnostics(expected);
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void SystemIntPtrInSignature_BreakingChange_001()
{
var ilSource =
@"
.class public AddressHelper{
.method public hidebysig static native int AddressOf<T>(!!0& t){
ldc.i4.5
conv.u
ret
}
}
";
var csharpSource =
@"
class Program
{
static void Main(string[] args)
{
var s = string.Empty;
var i = AddressHelper.AddressOf(ref s);
System.Console.WriteLine(i);
}
}
";
var compilation = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var result = CompileAndVerify(compilation, expectedOutput: "5");
}
[Fact, WorkItem(7550, "https://github.com/dotnet/roslyn/issues/7550")]
public void EnsureNullPointerIsPoppedIfUnused()
{
string source = @"
public class A
{
public unsafe byte* Ptr;
static void Main()
{
unsafe
{
var x = new A();
byte* ptr = (x == null) ? null : x.Ptr;
}
System.Console.WriteLine(""OK"");
}
}
";
CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "OK", verify: Verification.Passes);
}
[Fact, WorkItem(40768, "https://github.com/dotnet/roslyn/issues/40768")]
public void DoesNotEmitArrayDotEmptyForEmptyPointerArrayParams()
{
var source = @"
using System;
public static class Program
{
public static unsafe void Main()
{
Console.WriteLine(Test());
}
public static unsafe int Test(params int*[] types)
{
return types.Length;
}
}";
var comp = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails);
comp.VerifyIL("Program.Main", @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: newarr ""int*""
IL_0006: call ""int Program.Test(params int*[])""
IL_000b: call ""void System.Console.WriteLine(int)""
IL_0010: ret
}");
}
[Fact]
public void DoesEmitArrayDotEmptyForEmptyPointerArrayArrayParams()
{
var source = @"
using System;
public static class Program
{
public static unsafe void Main()
{
Console.WriteLine(Test());
}
public static unsafe int Test(params int*[][] types)
{
return types.Length;
}
}";
var comp = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0");
comp.VerifyIL("Program.Main", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: call ""int*[][] System.Array.Empty<int*[]>()""
IL_0005: call ""int Program.Test(params int*[][])""
IL_000a: call ""void System.Console.WriteLine(int)""
IL_000f: ret
}");
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class UnsafeTests : EmitMetadataTestBase
{
#region AddressOf tests
[Fact]
public void AddressOfLocal_Unused()
{
var text = @"
unsafe class C
{
void M()
{
int x;
int* p = &x;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes);
compVerifier.VerifyIL("C.M", @"
{
// Code size 4 (0x4)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldloca.s V_0
IL_0002: pop
IL_0003: ret
}
");
}
[Fact]
public void AddressOfLocal_Used()
{
var text = @"
unsafe class C
{
void M(int* param)
{
int x;
int* p = &x;
M(p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 2
.locals init (int V_0, //x
int* V_1) //p
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldarg.0
IL_0005: ldloc.1
IL_0006: call ""void C.M(int*)""
IL_000b: ret
}
");
}
[Fact]
public void AddressOfParameter_Unused()
{
var text = @"
unsafe class C
{
void M(int x)
{
int* p = &x;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes);
compVerifier.VerifyIL("C.M", @"
{
// Code size 4 (0x4)
.maxstack 1
IL_0000: ldarga.s V_1
IL_0002: pop
IL_0003: ret
}
");
}
[Fact]
public void AddressOfParameter_Used()
{
var text = @"
unsafe class C
{
void M(int x, int* param)
{
int* p = &x;
M(x, p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 13 (0xd)
.maxstack 3
.locals init (int* V_0) //p
IL_0000: ldarga.s V_1
IL_0002: conv.u
IL_0003: stloc.0
IL_0004: ldarg.0
IL_0005: ldarg.1
IL_0006: ldloc.0
IL_0007: call ""void C.M(int, int*)""
IL_000c: ret
}
");
}
[Fact]
public void AddressOfStructField()
{
var text = @"
unsafe class C
{
void M()
{
S1 s;
S1* p1 = &s;
S2* p2 = &s.s;
int* p3 = &s.s.x;
Goo(s, p1, p2, p3);
}
void Goo(S1 s, S1* p1, S2* p2, int* p3) { }
}
struct S1
{
public S2 s;
}
struct S2
{
public int x;
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 38 (0x26)
.maxstack 5
.locals init (S1 V_0, //s
S1* V_1, //p1
S2* V_2, //p2
int* V_3) //p3
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldloca.s V_0
IL_0006: ldflda ""S2 S1.s""
IL_000b: conv.u
IL_000c: stloc.2
IL_000d: ldloca.s V_0
IL_000f: ldflda ""S2 S1.s""
IL_0014: ldflda ""int S2.x""
IL_0019: conv.u
IL_001a: stloc.3
IL_001b: ldarg.0
IL_001c: ldloc.0
IL_001d: ldloc.1
IL_001e: ldloc.2
IL_001f: ldloc.3
IL_0020: call ""void C.Goo(S1, S1*, S2*, int*)""
IL_0025: ret
}
");
}
[Fact]
public void AddressOfSuppressOptimization()
{
var text = @"
unsafe class C
{
static void M()
{
int x = 123;
Goo(&x); // should not optimize into 'Goo(&123)'
}
static void Goo(int* p) { }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: call ""void C.Goo(int*)""
IL_000b: ret
}
");
}
#endregion AddressOf tests
#region Dereference tests
[Fact]
public void DereferenceLocal()
{
var text = @"
unsafe class C
{
static void Main()
{
int x = 123;
int* p = &x;
System.Console.WriteLine(*p);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "123", verify: Verification.Fails);
// NOTE: p is optimized away, but & and * aren't.
compVerifier.VerifyIL("C.Main", @"
{
// Code size 13 (0xd)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.s 123
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: ldind.i4
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ret
}
");
}
[Fact]
public void DereferenceParameter()
{
var text = @"
unsafe class C
{
static void Main()
{
long x = 456;
System.Console.WriteLine(Dereference(&x));
}
static long Dereference(long* p)
{
return *p;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "456", verify: Verification.Fails);
compVerifier.VerifyIL("C.Dereference", @"
{
// Code size 3 (0x3)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldind.i8
IL_0002: ret
}
");
}
[Fact]
public void DereferenceWrite()
{
var text = @"
unsafe class C
{
static void Main()
{
int x = 1;
int* p = &x;
*p = 2;
System.Console.WriteLine(x);
}
}
";
var compVerifierOptimized = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "2", verify: Verification.Fails);
// NOTE: p is optimized away, but & and * aren't.
compVerifierOptimized.VerifyIL("C.Main", @"
{
// Code size 14 (0xe)
.maxstack 2
.locals init (int V_0) //x
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: conv.u
IL_0005: ldc.i4.2
IL_0006: stind.i4
IL_0007: ldloc.0
IL_0008: call ""void System.Console.WriteLine(int)""
IL_000d: ret
}
");
var compVerifierUnoptimized = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: "2", verify: Verification.Fails);
compVerifierUnoptimized.VerifyIL("C.Main", @"
{
// Code size 18 (0x12)
.maxstack 2
.locals init (int V_0, //x
int* V_1) //p
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.2
IL_0009: stind.i4
IL_000a: ldloc.0
IL_000b: call ""void System.Console.WriteLine(int)""
IL_0010: nop
IL_0011: ret
}
");
}
[Fact]
public void DereferenceStruct()
{
var text = @"
unsafe struct S
{
S* p;
byte x;
static void Main()
{
S s;
S* sp = &s;
(*sp).p = sp;
(*sp).x = 1;
System.Console.WriteLine((*(s.p)).x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (S V_0, //s
S* V_1) //sp
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: stloc.1
IL_0004: ldloc.1
IL_0005: ldloc.1
IL_0006: stfld ""S* S.p""
IL_000b: ldloc.1
IL_000c: ldc.i4.1
IL_000d: stfld ""byte S.x""
IL_0012: ldloc.0
IL_0013: ldfld ""S* S.p""
IL_0018: ldfld ""byte S.x""
IL_001d: call ""void System.Console.WriteLine(int)""
IL_0022: ret
}
");
}
[Fact]
public void DereferenceSwap()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
byte b1 = 2;
byte b2 = 7;
Console.WriteLine(""Before: {0} {1}"", b1, b2);
Swap(&b1, &b2);
Console.WriteLine(""After: {0} {1}"", b1, b2);
}
static void Swap(byte* p1, byte* p2)
{
byte tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"Before: 2 7
After: 7 2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Swap", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (byte V_0) //tmp
IL_0000: ldarg.0
IL_0001: ldind.u1
IL_0002: stloc.0
IL_0003: ldarg.0
IL_0004: ldarg.1
IL_0005: ldind.u1
IL_0006: stind.i1
IL_0007: ldarg.1
IL_0008: ldloc.0
IL_0009: stind.i1
IL_000a: ret
}
");
}
[Fact]
public void DereferenceIsLValue1()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
char c = 'a';
char* p = &c;
Console.Write(c);
Incr(ref *p);
Console.Write(c);
}
static void Incr(ref char c)
{
c++;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"ab", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 24 (0x18)
.maxstack 2
.locals init (char V_0) //c
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: ldloc.0
IL_0007: call ""void System.Console.Write(char)""
IL_000c: call ""void C.Incr(ref char)""
IL_0011: ldloc.0
IL_0012: call ""void System.Console.Write(char)""
IL_0017: ret
}
");
}
[Fact]
public void DereferenceIsLValue2()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 1;
S* p = &s;
Console.Write(s.x);
(*p).Mutate();
Console.Write(s.x);
}
void Mutate()
{
x++;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: call ""void S.Mutate()""
IL_001b: ldloc.0
IL_001c: ldfld ""int S.x""
IL_0021: call ""void System.Console.Write(int)""
IL_0026: ret
}
");
}
#endregion Dereference tests
#region Pointer member access tests
[Fact]
public void PointerMemberAccessRead()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write(p->x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldfld ""int S.x""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldfld ""int S.x""
IL_0010: call ""void System.Console.Write(int)""
IL_0015: ret
}
");
}
[Fact]
public void PointerMemberAccessWrite()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write(s.x);
p->x = 4;
Console.Write(s.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: ldc.i4.4
IL_0017: stfld ""int S.x""
IL_001c: ldloc.0
IL_001d: ldfld ""int S.x""
IL_0022: call ""void System.Console.Write(int)""
IL_0027: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldloc.0
IL_000c: ldfld ""int S.x""
IL_0011: call ""void System.Console.Write(int)""
IL_0016: ldc.i4.4
IL_0017: stfld ""int S.x""
IL_001c: ldloc.0
IL_001d: ldfld ""int S.x""
IL_0022: call ""void System.Console.Write(int)""
IL_0027: ret
}
");
}
[Fact]
public void PointerMemberAccessInvoke()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s;
S* p = &s;
p->M();
p->M(1);
p->M(1, 2);
}
void M() { Console.Write(1); }
void M(int x) { Console.Write(2); }
}
static class Extensions
{
public static void M(this S s, int x, int y) { Console.Write(3); }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: dup
IL_0004: call ""void S.M()""
IL_0009: dup
IL_000a: ldc.i4.1
IL_000b: call ""void S.M(int)""
IL_0010: ldobj ""S""
IL_0015: ldc.i4.1
IL_0016: ldc.i4.2
IL_0017: call ""void Extensions.M(S, int, int)""
IL_001c: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: conv.u
IL_0003: dup
IL_0004: call ""void S.M()""
IL_0009: dup
IL_000a: ldc.i4.1
IL_000b: call ""void S.M(int)""
IL_0010: ldobj ""S""
IL_0015: ldc.i4.1
IL_0016: ldc.i4.2
IL_0017: call ""void Extensions.M(S, int, int)""
IL_001c: ret
}
");
}
[Fact]
public void PointerMemberAccessInvoke001()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s;
S* p = &s;
Test(ref p);
}
static void Test(ref S* p)
{
p->M();
p->M(1);
p->M(1, 2);
}
void M() { Console.Write(1); }
void M(int x) { Console.Write(2); }
}
static class Extensions
{
public static void M(this S s, int x, int y) { Console.Write(3); }
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Test(ref S*)", @"
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldind.i
IL_0002: call ""void S.M()""
IL_0007: ldarg.0
IL_0008: ldind.i
IL_0009: ldc.i4.1
IL_000a: call ""void S.M(int)""
IL_000f: ldarg.0
IL_0010: ldind.i
IL_0011: ldobj ""S""
IL_0016: ldc.i4.1
IL_0017: ldc.i4.2
IL_0018: call ""void Extensions.M(S, int, int)""
IL_001d: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("S.Test(ref S*)", @"
{
// Code size 30 (0x1e)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldind.i
IL_0002: call ""void S.M()""
IL_0007: ldarg.0
IL_0008: ldind.i
IL_0009: ldc.i4.1
IL_000a: call ""void S.M(int)""
IL_000f: ldarg.0
IL_0010: ldind.i
IL_0011: ldobj ""S""
IL_0016: ldc.i4.1
IL_0017: ldc.i4.2
IL_0018: call ""void Extensions.M(S, int, int)""
IL_001d: ret
}
");
}
[Fact]
public void PointerMemberAccessMutate()
{
var text = @"
using System;
unsafe struct S
{
int x;
static void Main()
{
S s;
s.x = 3;
S* p = &s;
Console.Write((p->x)++);
Console.Write((p->x)++);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (S V_0, //s
int V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: ldflda ""int S.x""
IL_0011: dup
IL_0012: ldind.i4
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: add
IL_0017: stind.i4
IL_0018: ldloc.1
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldflda ""int S.x""
IL_0023: dup
IL_0024: ldind.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: stind.i4
IL_002a: ldloc.1
IL_002b: call ""void System.Console.Write(int)""
IL_0030: ret
}
");
compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"34", verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 49 (0x31)
.maxstack 4
.locals init (S V_0, //s
int V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.3
IL_0003: stfld ""int S.x""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: ldflda ""int S.x""
IL_0011: dup
IL_0012: ldind.i4
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.1
IL_0016: add
IL_0017: stind.i4
IL_0018: ldloc.1
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldflda ""int S.x""
IL_0023: dup
IL_0024: ldind.i4
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldc.i4.1
IL_0028: add
IL_0029: stind.i4
IL_002a: ldloc.1
IL_002b: call ""void System.Console.Write(int)""
IL_0030: ret
}
");
}
#endregion Pointer member access tests
#region Pointer element access tests
[Fact]
public void PointerElementAccessCheckedAndUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S s = new S();
S* p = &s;
int i = (int)p;
uint ui = (uint)p;
long l = (long)p;
ulong ul = (ulong)p;
checked
{
s = p[i];
s = p[ui];
s = p[l];
s = p[ul];
}
unchecked
{
s = p[i];
s = p[ui];
s = p[l];
s = p[ul];
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
// The conversions differ from dev10 in the same way as for numeric addition.
// Note that, unlike for numeric addition, the add operation is never checked.
compVerifier.VerifyIL("S.Main", @"
{
// Code size 170 (0xaa)
.maxstack 4
.locals init (S V_0, //s
int V_1, //i
uint V_2, //ui
long V_3, //l
ulong V_4) //ul
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: dup
IL_000c: conv.i4
IL_000d: stloc.1
IL_000e: dup
IL_000f: conv.u4
IL_0010: stloc.2
IL_0011: dup
IL_0012: conv.u8
IL_0013: stloc.3
IL_0014: dup
IL_0015: conv.u8
IL_0016: stloc.s V_4
IL_0018: dup
IL_0019: ldloc.1
IL_001a: conv.i
IL_001b: sizeof ""S""
IL_0021: mul.ovf
IL_0022: add
IL_0023: ldobj ""S""
IL_0028: stloc.0
IL_0029: dup
IL_002a: ldloc.2
IL_002b: conv.u8
IL_002c: sizeof ""S""
IL_0032: conv.i8
IL_0033: mul.ovf
IL_0034: conv.i
IL_0035: add
IL_0036: ldobj ""S""
IL_003b: stloc.0
IL_003c: dup
IL_003d: ldloc.3
IL_003e: sizeof ""S""
IL_0044: conv.i8
IL_0045: mul.ovf
IL_0046: conv.i
IL_0047: add
IL_0048: ldobj ""S""
IL_004d: stloc.0
IL_004e: dup
IL_004f: ldloc.s V_4
IL_0051: sizeof ""S""
IL_0057: conv.ovf.u8
IL_0058: mul.ovf.un
IL_0059: conv.u
IL_005a: add
IL_005b: ldobj ""S""
IL_0060: stloc.0
IL_0061: dup
IL_0062: ldloc.1
IL_0063: conv.i
IL_0064: sizeof ""S""
IL_006a: mul
IL_006b: add
IL_006c: ldobj ""S""
IL_0071: stloc.0
IL_0072: dup
IL_0073: ldloc.2
IL_0074: conv.u8
IL_0075: sizeof ""S""
IL_007b: conv.i8
IL_007c: mul
IL_007d: conv.i
IL_007e: add
IL_007f: ldobj ""S""
IL_0084: stloc.0
IL_0085: dup
IL_0086: ldloc.3
IL_0087: sizeof ""S""
IL_008d: conv.i8
IL_008e: mul
IL_008f: conv.i
IL_0090: add
IL_0091: ldobj ""S""
IL_0096: stloc.0
IL_0097: ldloc.s V_4
IL_0099: sizeof ""S""
IL_009f: conv.i8
IL_00a0: mul
IL_00a1: conv.u
IL_00a2: add
IL_00a3: ldobj ""S""
IL_00a8: stloc.0
IL_00a9: ret
}
");
}
[Fact]
public void PointerElementAccessWrite()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int* p = null;
p[1] = 2;
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
compVerifier.VerifyIL("S.Main", @"
{
// Code size 9 (0x9)
.maxstack 2
.locals init (int* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldc.i4.4
IL_0005: add
IL_0006: ldc.i4.2
IL_0007: stind.i4
IL_0008: ret
}
");
}
[Fact]
public void PointerElementAccessMutate()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int[] array = new int[3];
fixed (int* p = array)
{
p[1] += ++p[0];
p[2] -= p[1]--;
}
foreach (int element in array)
{
Console.WriteLine(element);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
1
0
-1", verify: Verification.Fails);
}
[Fact]
public void PointerElementAccessNested()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
fixed (int* q = new int[3])
{
q[0] = 2;
q[1] = 0;
q[2] = 1;
Console.Write(q[q[q[q[q[q[*q]]]]]]);
Console.Write(q[q[q[q[q[q[q[*q]]]]]]]);
Console.Write(q[q[q[q[q[q[q[q[*q]]]]]]]]);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "210", verify: Verification.Fails);
}
[Fact]
public void PointerElementAccessZero()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int x = 1;
int* p = &x;
Console.WriteLine(p[0]);
}
}
";
// NOTE: no pointer arithmetic - just dereference p.
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0) //x
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldloca.s V_0
IL_0004: conv.u
IL_0005: ldind.i4
IL_0006: call ""void System.Console.WriteLine(int)""
IL_000b: ret
}
");
}
#endregion Pointer element access tests
#region Fixed statement tests
[Fact]
public void FixedStatementField()
{
var text = @"
using System;
unsafe class C
{
int x;
static void Main()
{
C c = new C();
fixed (int* p = &c.x)
{
*p = 1;
}
Console.WriteLine(c.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"1", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 30 (0x1e)
.maxstack 3
.locals init (pinned int& V_0)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: ldc.i4.1
IL_000f: stind.i4
IL_0010: ldc.i4.0
IL_0011: conv.u
IL_0012: stloc.0
IL_0013: ldfld ""int C.x""
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ret
}
");
}
[Fact]
public void FixedStatementThis()
{
var text = @"
public class Program
{
public static void Main()
{
S1 s = default;
s.Test();
}
unsafe readonly struct S1
{
readonly int x;
public void Test()
{
fixed(void* p = &this)
{
*(int*)p = 123;
}
ref readonly S1 r = ref this;
fixed (S1* p = &r)
{
System.Console.WriteLine(p->x);
}
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"123", verify: Verification.Fails);
compVerifier.VerifyIL("Program.S1.Test()", @"
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (void* V_0, //p
pinned Program.S1& V_1)
IL_0000: ldarg.0
IL_0001: stloc.1
IL_0002: ldloc.1
IL_0003: conv.u
IL_0004: stloc.0
IL_0005: ldloc.0
IL_0006: ldc.i4.s 123
IL_0008: stind.i4
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldarg.0
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: ldfld ""int Program.S1.x""
IL_0015: call ""void System.Console.WriteLine(int)""
IL_001a: ldc.i4.0
IL_001b: conv.u
IL_001c: stloc.1
IL_001d: ret
}
");
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[Fact]
public void FixedStatementMultipleFields()
{
var text = @"
using System;
unsafe class C
{
int x;
readonly int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldflda ""int C.y""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: stind.i4
IL_001b: ldc.i4.2
IL_001c: stind.i4
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.2
IL_0023: dup
IL_0024: ldfld ""int C.x""
IL_0029: call ""void System.Console.Write(int)""
IL_002e: ldfld ""int C.y""
IL_0033: call ""void System.Console.Write(int)""
IL_0038: ret
}
");
}
[WorkItem(22306, "https://github.com/dotnet/roslyn/issues/22306")]
[Fact]
public void FixedStatementMultipleMethods()
{
var text = @"
using System;
unsafe class C
{
int x;
readonly int y;
ref int X()=>ref x;
ref readonly int this[int i]=>ref y;
static void Main()
{
C c = new C();
fixed (int* p = &c.X(), q = &c[3])
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 58 (0x3a)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: callvirt ""ref int C.X()""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldc.i4.3
IL_0011: callvirt ""ref readonly int C.this[int].get""
IL_0016: stloc.2
IL_0017: ldloc.2
IL_0018: conv.u
IL_0019: ldloc.0
IL_001a: ldc.i4.1
IL_001b: stind.i4
IL_001c: ldc.i4.2
IL_001d: stind.i4
IL_001e: ldc.i4.0
IL_001f: conv.u
IL_0020: stloc.1
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.2
IL_0024: dup
IL_0025: ldfld ""int C.x""
IL_002a: call ""void System.Console.Write(int)""
IL_002f: ldfld ""int C.y""
IL_0034: call ""void System.Console.Write(int)""
IL_0039: ret
}
");
}
[WorkItem(546866, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546866")]
[Fact]
public void FixedStatementProperty()
{
var text =
@"class C
{
string P { get { return null; } }
char[] Q { get { return null; } }
unsafe static void M(C c)
{
fixed (char* o = c.P)
{
}
fixed (char* o = c.Q)
{
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.M(C)",
@"
{
// Code size 55 (0x37)
.maxstack 2
.locals init (char* V_0, //o
pinned string V_1,
char* V_2, //o
pinned char[] V_3)
IL_0000: ldarg.0
IL_0001: callvirt ""string C.P.get""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: ldnull
IL_0016: stloc.1
IL_0017: ldarg.0
IL_0018: callvirt ""char[] C.Q.get""
IL_001d: dup
IL_001e: stloc.3
IL_001f: brfalse.s IL_0026
IL_0021: ldloc.3
IL_0022: ldlen
IL_0023: conv.i4
IL_0024: brtrue.s IL_002b
IL_0026: ldc.i4.0
IL_0027: conv.u
IL_0028: stloc.2
IL_0029: br.s IL_0034
IL_002b: ldloc.3
IL_002c: ldc.i4.0
IL_002d: ldelema ""char""
IL_0032: conv.u
IL_0033: stloc.2
IL_0034: ldnull
IL_0035: stloc.3
IL_0036: ret
}
");
}
[Fact]
public void FixedStatementMultipleOptimized()
{
var text = @"
using System;
unsafe class C
{
int x;
int y;
static void Main()
{
C c = new C();
fixed (int* p = &c.x, q = &c.y)
{
*p = 1;
*q = 2;
}
Console.Write(c.x);
Console.Write(c.y);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"12", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 57 (0x39)
.maxstack 4
.locals init (int* V_0, //p
pinned int& V_1,
pinned int& V_2)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""int C.x""
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: dup
IL_0010: ldflda ""int C.y""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: ldloc.0
IL_0019: ldc.i4.1
IL_001a: stind.i4
IL_001b: ldc.i4.2
IL_001c: stind.i4
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.2
IL_0023: dup
IL_0024: ldfld ""int C.x""
IL_0029: call ""void System.Console.Write(int)""
IL_002e: ldfld ""int C.y""
IL_0033: call ""void System.Console.Write(int)""
IL_0038: ret
}
");
}
[Fact]
public void FixedStatementReferenceParameter()
{
var text = @"
using System;
class C
{
static void Main()
{
char ch;
M(out ch);
Console.WriteLine(ch);
}
unsafe static void M(out char ch)
{
fixed (char* p = &ch)
{
*p = 'a';
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"a", verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 11 (0xb)
.maxstack 2
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: conv.u
IL_0004: ldc.i4.s 97
IL_0006: stind.i2
IL_0007: ldc.i4.0
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ret
}
");
}
[Fact]
public void FixedStatementReferenceParameterDebug()
{
var text = @"
using System;
class C
{
static void Main()
{
char ch;
M(out ch);
Console.WriteLine(ch);
}
unsafe static void M(out char ch)
{
fixed (char* p = &ch)
{
*p = 'a';
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"a", verify: Verification.Fails);
compVerifier.VerifyIL("C.M", @"
{
// Code size 16 (0x10)
.maxstack 2
.locals init (char* V_0, //p
pinned char& V_1)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: stloc.1
IL_0003: ldloc.1
IL_0004: conv.u
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.s 97
IL_000a: stind.i2
IL_000b: nop
IL_000c: ldc.i4.0
IL_000d: conv.u
IL_000e: stloc.1
IL_000f: ret
}
");
}
[Fact]
public void FixedStatementStringLiteral()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
fixed (char* p = ""hello"")
{
Console.WriteLine(*p);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"h", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
-IL_0000: nop
IL_0001: ldstr ""hello""
IL_0006: stloc.1
-IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
-IL_0015: nop
-IL_0016: ldloc.0
IL_0017: ldind.u2
IL_0018: call ""void System.Console.WriteLine(char)""
IL_001d: nop
-IL_001e: nop
~IL_001f: ldnull
IL_0020: stloc.1
-IL_0021: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementStringVariable()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
string s = ""hello"";
fixed (char* p = s)
{
Console.Write(*p);
}
s = null;
fixed (char* p = s)
{
Console.Write(p == null);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: @"hTrue", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 72 (0x48)
.maxstack 2
.locals init (string V_0, //s
char* V_1, //p
pinned string V_2,
char* V_3, //p
pinned string V_4)
-IL_0000: nop
-IL_0001: ldstr ""hello""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: stloc.2
-IL_0009: ldloc.2
IL_000a: conv.u
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: brfalse.s IL_0017
IL_000f: ldloc.1
IL_0010: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0015: add
IL_0016: stloc.1
-IL_0017: nop
-IL_0018: ldloc.1
IL_0019: ldind.u2
IL_001a: call ""void System.Console.Write(char)""
IL_001f: nop
-IL_0020: nop
~IL_0021: ldnull
IL_0022: stloc.2
-IL_0023: ldnull
IL_0024: stloc.0
IL_0025: ldloc.0
IL_0026: stloc.s V_4
-IL_0028: ldloc.s V_4
IL_002a: conv.u
IL_002b: stloc.3
IL_002c: ldloc.3
IL_002d: brfalse.s IL_0037
IL_002f: ldloc.3
IL_0030: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0035: add
IL_0036: stloc.3
-IL_0037: nop
-IL_0038: ldloc.3
IL_0039: ldc.i4.0
IL_003a: conv.u
IL_003b: ceq
IL_003d: call ""void System.Console.Write(bool)""
IL_0042: nop
-IL_0043: nop
~IL_0044: ldnull
IL_0045: stloc.s V_4
-IL_0047: ret
}
", sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementStringVariableOptimized()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
string s = ""hello"";
fixed (char* p = s)
{
Console.Write(*p);
}
s = null;
fixed (char* p = s)
{
Console.Write(p == null);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"hTrue", verify: Verification.Fails);
// Null checks and branches are much simpler, but string temps are NOT optimized away.
compVerifier.VerifyIL("C.Main", @"
{
// Code size 58 (0x3a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char* V_2) //p
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldind.u2
IL_0016: call ""void System.Console.Write(char)""
IL_001b: ldnull
IL_001c: stloc.1
IL_001d: ldnull
IL_001e: stloc.1
IL_001f: ldloc.1
IL_0020: conv.u
IL_0021: stloc.2
IL_0022: ldloc.2
IL_0023: brfalse.s IL_002d
IL_0025: ldloc.2
IL_0026: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_002b: add
IL_002c: stloc.2
IL_002d: ldloc.2
IL_002e: ldc.i4.0
IL_002f: conv.u
IL_0030: ceq
IL_0032: call ""void System.Console.Write(bool)""
IL_0037: ldnull
IL_0038: stloc.1
IL_0039: ret
}
");
}
[Fact]
public void FixedStatementOneDimensionalArray()
{
var text = @"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (int* V_0, //p
pinned int[] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[] C.a""
IL_000b: ldc.i4.0
IL_000c: ldelem.i4
IL_000d: call ""void System.Console.Write(int)""
IL_0012: dup
IL_0013: ldfld ""int[] C.a""
IL_0018: dup
IL_0019: stloc.1
IL_001a: brfalse.s IL_0021
IL_001c: ldloc.1
IL_001d: ldlen
IL_001e: conv.i4
IL_001f: brtrue.s IL_0026
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.0
IL_0024: br.s IL_002f
IL_0026: ldloc.1
IL_0027: ldc.i4.0
IL_0028: ldelema ""int""
IL_002d: conv.u
IL_002e: stloc.0
IL_002f: ldloc.0
IL_0030: ldc.i4.1
IL_0031: stind.i4
IL_0032: ldnull
IL_0033: stloc.1
IL_0034: ldfld ""int[] C.a""
IL_0039: ldc.i4.0
IL_003a: ldelem.i4
IL_003b: call ""void System.Console.Write(int)""
IL_0040: ret
}
");
}
[Fact]
public void FixedStatementOneDimensionalArrayOptimized()
{
var text = @"
using System;
unsafe class C
{
int[] a = new int[1];
static void Main()
{
C c = new C();
Console.Write(c.a[0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (int* V_0, //p
pinned int[] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[] C.a""
IL_000b: ldc.i4.0
IL_000c: ldelem.i4
IL_000d: call ""void System.Console.Write(int)""
IL_0012: dup
IL_0013: ldfld ""int[] C.a""
IL_0018: dup
IL_0019: stloc.1
IL_001a: brfalse.s IL_0021
IL_001c: ldloc.1
IL_001d: ldlen
IL_001e: conv.i4
IL_001f: brtrue.s IL_0026
IL_0021: ldc.i4.0
IL_0022: conv.u
IL_0023: stloc.0
IL_0024: br.s IL_002f
IL_0026: ldloc.1
IL_0027: ldc.i4.0
IL_0028: ldelema ""int""
IL_002d: conv.u
IL_002e: stloc.0
IL_002f: ldloc.0
IL_0030: ldc.i4.1
IL_0031: stind.i4
IL_0032: ldnull
IL_0033: stloc.1
IL_0034: ldfld ""int[] C.a""
IL_0039: ldc.i4.0
IL_003a: ldelem.i4
IL_003b: call ""void System.Console.Write(int)""
IL_0040: ret
}
");
}
[Fact]
public void FixedStatementMultiDimensionalArrayOptimized()
{
var text = @"
using System;
unsafe class C
{
int[,] a = new int[1,1];
static void Main()
{
C c = new C();
Console.Write(c.a[0, 0]);
fixed (int* p = c.a)
{
*p = 1;
}
Console.Write(c.a[0, 0]);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"01", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 79 (0x4f)
.maxstack 4
.locals init (int* V_0, //p
pinned int[,] V_1)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldfld ""int[,] C.a""
IL_000b: ldc.i4.0
IL_000c: ldc.i4.0
IL_000d: call ""int[*,*].Get""
IL_0012: call ""void System.Console.Write(int)""
IL_0017: dup
IL_0018: ldfld ""int[,] C.a""
IL_001d: dup
IL_001e: stloc.1
IL_001f: brfalse.s IL_0029
IL_0021: ldloc.1
IL_0022: callvirt ""int System.Array.Length.get""
IL_0027: brtrue.s IL_002e
IL_0029: ldc.i4.0
IL_002a: conv.u
IL_002b: stloc.0
IL_002c: br.s IL_0038
IL_002e: ldloc.1
IL_002f: ldc.i4.0
IL_0030: ldc.i4.0
IL_0031: call ""int[*,*].Address""
IL_0036: conv.u
IL_0037: stloc.0
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: stind.i4
IL_003b: ldnull
IL_003c: stloc.1
IL_003d: ldfld ""int[,] C.a""
IL_0042: ldc.i4.0
IL_0043: ldc.i4.0
IL_0044: call ""int[*,*].Get""
IL_0049: call ""void System.Console.Write(int)""
IL_004e: ret
}
");
}
[Fact]
public void FixedStatementMixed()
{
var text = @"
using System;
unsafe class C
{
char c = 'a';
char[] a = new char[1];
static void Main()
{
C c = new C();
fixed (char* p = &c.c, q = c.a, r = ""hello"")
{
Console.Write((int)*p);
Console.Write((int)*q);
Console.Write((int)*r);
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"970104", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 99 (0x63)
.maxstack 2
.locals init (char* V_0, //p
char* V_1, //q
char* V_2, //r
pinned char& V_3,
pinned char[] V_4,
pinned string V_5)
IL_0000: newobj ""C..ctor()""
IL_0005: dup
IL_0006: ldflda ""char C.c""
IL_000b: stloc.3
IL_000c: ldloc.3
IL_000d: conv.u
IL_000e: stloc.0
IL_000f: ldfld ""char[] C.a""
IL_0014: dup
IL_0015: stloc.s V_4
IL_0017: brfalse.s IL_001f
IL_0019: ldloc.s V_4
IL_001b: ldlen
IL_001c: conv.i4
IL_001d: brtrue.s IL_0024
IL_001f: ldc.i4.0
IL_0020: conv.u
IL_0021: stloc.1
IL_0022: br.s IL_002e
IL_0024: ldloc.s V_4
IL_0026: ldc.i4.0
IL_0027: ldelema ""char""
IL_002c: conv.u
IL_002d: stloc.1
IL_002e: ldstr ""hello""
IL_0033: stloc.s V_5
IL_0035: ldloc.s V_5
IL_0037: conv.u
IL_0038: stloc.2
IL_0039: ldloc.2
IL_003a: brfalse.s IL_0044
IL_003c: ldloc.2
IL_003d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0042: add
IL_0043: stloc.2
IL_0044: ldloc.0
IL_0045: ldind.u2
IL_0046: call ""void System.Console.Write(int)""
IL_004b: ldloc.1
IL_004c: ldind.u2
IL_004d: call ""void System.Console.Write(int)""
IL_0052: ldloc.2
IL_0053: ldind.u2
IL_0054: call ""void System.Console.Write(int)""
IL_0059: ldc.i4.0
IL_005a: conv.u
IL_005b: stloc.3
IL_005c: ldnull
IL_005d: stloc.s V_4
IL_005f: ldnull
IL_0060: stloc.s V_5
IL_0062: ret
}
");
}
[Fact]
public void FixedStatementInTryOfTryFinally()
{
var text = @"
unsafe class C
{
static void nop() { }
void Test()
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
nop();
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 32 (0x20)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_001f
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
}
finally
{
IL_0019: call ""void C.nop()""
IL_001e: endfinally
}
IL_001f: ret
}
");
}
[Fact]
public void FixedStatementInTryOfTryCatch()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
fixed (char* p = ""hello"")
{
}
}
catch
{
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: leave.s IL_001e
}
catch object
{
IL_001b: pop
IL_001c: leave.s IL_001e
}
IL_001e: ret
}
");
}
[Fact]
public void FixedStatementInFinally()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
}
finally
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: leave.s IL_0019
}
finally
{
IL_0002: ldstr ""hello""
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: conv.u
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: brfalse.s IL_0016
IL_000e: ldloc.0
IL_000f: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0014: add
IL_0015: stloc.0
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInCatchOfTryCatch()
{
var text = @"
unsafe class C
{
void nop() { }
void Test()
{
try
{
nop();
}
catch
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test",
@"{
// Code size 34 (0x22)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldarg.0
IL_0001: call ""void C.nop()""
IL_0006: leave.s IL_0021
}
catch object
{
IL_0008: pop
IL_0009: ldstr ""hello""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: conv.u
IL_0011: stloc.0
IL_0012: ldloc.0
IL_0013: brfalse.s IL_001d
IL_0015: ldloc.0
IL_0016: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001b: add
IL_001c: stloc.0
IL_001d: ldnull
IL_001e: stloc.1
IL_001f: leave.s IL_0021
}
IL_0021: ret
}");
}
[Fact]
public void FixedStatementInCatchOfTryCatchFinally()
{
var text = @"
unsafe class C
{
static void nop() { }
void Test()
{
try
{
nop();
}
catch
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: call ""void C.nop()""
IL_0005: leave.s IL_0023
}
catch object
{
IL_0007: pop
.try
{
IL_0008: ldstr ""hello""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: brfalse.s IL_001c
IL_0014: ldloc.0
IL_0015: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001a: add
IL_001b: stloc.0
IL_001c: leave.s IL_0021
}
finally
{
IL_001e: ldnull
IL_001f: stloc.1
IL_0020: endfinally
}
IL_0021: leave.s IL_0023
}
IL_0023: ret
}
");
}
[Fact]
public void FixedStatementInFixed_NoBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Neither inner nor outer has finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""hello""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldnull
IL_0029: stloc.3
IL_002a: ldnull
IL_002b: stloc.1
IL_002c: ret
}
");
}
[Fact]
public void FixedStatementInFixed_InnerBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
goto label;
}
}
label: ;
}
}
";
// Inner and outer both have finally blocks.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 50 (0x32)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
.try
{
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: nop
.try
{
IL_0015: ldstr ""hello""
IL_001a: stloc.3
IL_001b: ldloc.3
IL_001c: conv.u
IL_001d: stloc.2
IL_001e: ldloc.2
IL_001f: brfalse.s IL_0029
IL_0021: ldloc.2
IL_0022: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0027: add
IL_0028: stloc.2
IL_0029: leave.s IL_0031
}
finally
{
IL_002b: ldnull
IL_002c: stloc.3
IL_002d: endfinally
}
}
finally
{
IL_002e: ldnull
IL_002f: stloc.1
IL_0030: endfinally
}
IL_0031: ret
}
");
}
[Fact]
public void FixedStatementInFixed_OuterBranch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* q = ""goodbye"")
{
fixed (char* p = ""hello"")
{
}
goto label;
}
label: ;
}
}
";
// Outer has finally, inner does not.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 48 (0x30)
.maxstack 2
.locals init (char* V_0, //q
pinned string V_1,
char* V_2, //p
pinned string V_3)
.try
{
IL_0000: ldstr ""goodbye""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""hello""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldnull
IL_0029: stloc.3
IL_002a: leave.s IL_002f
}
finally
{
IL_002c: ldnull
IL_002d: stloc.1
IL_002e: endfinally
}
IL_002f: ret
}
");
}
[Fact]
public void FixedStatementInFixed_Nesting()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p1 = ""A"")
{
fixed (char* p2 = ""B"")
{
fixed (char* p3 = ""C"")
{
}
fixed (char* p4 = ""D"")
{
}
}
fixed (char* p5 = ""E"")
{
fixed (char* p6 = ""F"")
{
}
fixed (char* p7 = ""G"")
{
}
}
}
}
}
";
// This test checks two things:
// 1) nothing blows up with triple-nesting, and
// 2) none of the fixed statements has a try-finally.
// CONSIDER: Shorter test that performs the same checks.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 187 (0xbb)
.maxstack 2
.locals init (char* V_0, //p1
pinned string V_1,
char* V_2, //p2
pinned string V_3,
char* V_4, //p3
pinned string V_5,
char* V_6, //p4
char* V_7, //p5
char* V_8, //p6
char* V_9) //p7
IL_0000: ldstr ""A""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldstr ""B""
IL_0019: stloc.3
IL_001a: ldloc.3
IL_001b: conv.u
IL_001c: stloc.2
IL_001d: ldloc.2
IL_001e: brfalse.s IL_0028
IL_0020: ldloc.2
IL_0021: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0026: add
IL_0027: stloc.2
IL_0028: ldstr ""C""
IL_002d: stloc.s V_5
IL_002f: ldloc.s V_5
IL_0031: conv.u
IL_0032: stloc.s V_4
IL_0034: ldloc.s V_4
IL_0036: brfalse.s IL_0042
IL_0038: ldloc.s V_4
IL_003a: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_003f: add
IL_0040: stloc.s V_4
IL_0042: ldnull
IL_0043: stloc.s V_5
IL_0045: ldstr ""D""
IL_004a: stloc.s V_5
IL_004c: ldloc.s V_5
IL_004e: conv.u
IL_004f: stloc.s V_6
IL_0051: ldloc.s V_6
IL_0053: brfalse.s IL_005f
IL_0055: ldloc.s V_6
IL_0057: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_005c: add
IL_005d: stloc.s V_6
IL_005f: ldnull
IL_0060: stloc.s V_5
IL_0062: ldnull
IL_0063: stloc.3
IL_0064: ldstr ""E""
IL_0069: stloc.3
IL_006a: ldloc.3
IL_006b: conv.u
IL_006c: stloc.s V_7
IL_006e: ldloc.s V_7
IL_0070: brfalse.s IL_007c
IL_0072: ldloc.s V_7
IL_0074: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0079: add
IL_007a: stloc.s V_7
IL_007c: ldstr ""F""
IL_0081: stloc.s V_5
IL_0083: ldloc.s V_5
IL_0085: conv.u
IL_0086: stloc.s V_8
IL_0088: ldloc.s V_8
IL_008a: brfalse.s IL_0096
IL_008c: ldloc.s V_8
IL_008e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0093: add
IL_0094: stloc.s V_8
IL_0096: ldnull
IL_0097: stloc.s V_5
IL_0099: ldstr ""G""
IL_009e: stloc.s V_5
IL_00a0: ldloc.s V_5
IL_00a2: conv.u
IL_00a3: stloc.s V_9
IL_00a5: ldloc.s V_9
IL_00a7: brfalse.s IL_00b3
IL_00a9: ldloc.s V_9
IL_00ab: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_00b0: add
IL_00b1: stloc.s V_9
IL_00b3: ldnull
IL_00b4: stloc.s V_5
IL_00b6: ldnull
IL_00b7: stloc.3
IL_00b8: ldnull
IL_00b9: stloc.1
IL_00ba: ret
}
");
}
[Fact]
public void FixedStatementInUsing()
{
var text = @"
unsafe class C
{
void Test()
{
using (System.IDisposable d = null)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// CONSIDER: This is sort of silly since the using is optimized away.
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInLock()
{
var text = @"
unsafe class C
{
void Test()
{
lock (this)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup not in finally (matches dev11, but not clear why).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (C V_0,
bool V_1,
char* V_2, //p
pinned string V_3)
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
.try
{
IL_0004: ldloc.0
IL_0005: ldloca.s V_1
IL_0007: call ""void System.Threading.Monitor.Enter(object, ref bool)""
IL_000c: ldstr ""hello""
IL_0011: stloc.3
IL_0012: ldloc.3
IL_0013: conv.u
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: brfalse.s IL_0020
IL_0018: ldloc.2
IL_0019: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001e: add
IL_001f: stloc.2
IL_0020: ldnull
IL_0021: stloc.3
IL_0022: leave.s IL_002e
}
finally
{
IL_0024: ldloc.1
IL_0025: brfalse.s IL_002d
IL_0027: ldloc.0
IL_0028: call ""void System.Threading.Monitor.Exit(object)""
IL_002d: endfinally
}
IL_002e: ret
}
");
}
[Fact]
public void FixedStatementInForEach_NoDispose()
{
var text = @"
unsafe class C
{
void Test(int[] array)
{
foreach (int i in array)
{
fixed (char* p = ""hello"")
{
}
}
}
}
";
// Cleanup in finally.
// CONSIDER: dev11 is smarter and skips the try-finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 46 (0x2e)
.maxstack 2
.locals init (int[] V_0,
int V_1,
char* V_2, //p
pinned string V_3)
IL_0000: ldarg.1
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: br.s IL_0027
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: ldelem.i4
IL_0009: pop
.try
{
IL_000a: ldstr ""hello""
IL_000f: stloc.3
IL_0010: ldloc.3
IL_0011: conv.u
IL_0012: stloc.2
IL_0013: ldloc.2
IL_0014: brfalse.s IL_001e
IL_0016: ldloc.2
IL_0017: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_001c: add
IL_001d: stloc.2
IL_001e: leave.s IL_0023
}
finally
{
IL_0020: ldnull
IL_0021: stloc.3
IL_0022: endfinally
}
IL_0023: ldloc.1
IL_0024: ldc.i4.1
IL_0025: add
IL_0026: stloc.1
IL_0027: ldloc.1
IL_0028: ldloc.0
IL_0029: ldlen
IL_002a: conv.i4
IL_002b: blt.s IL_0006
IL_002d: ret
}
");
}
[Fact]
public void FixedStatementInForEach_Dispose()
{
var text = @"
unsafe class C
{
void Test(Enumerable e)
{
foreach (var x in e)
{
fixed (char* p = ""hello"")
{
}
}
}
}
class Enumerable
{
public Enumerator GetEnumerator() { return new Enumerator(); }
}
class Enumerator : System.IDisposable
{
int x;
public int Current { get { return x; } }
public bool MoveNext() { return ++x < 4; }
void System.IDisposable.Dispose() { }
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 62 (0x3e)
.maxstack 2
.locals init (Enumerator V_0,
char* V_1, //p
pinned string V_2)
IL_0000: ldarg.1
IL_0001: callvirt ""Enumerator Enumerable.GetEnumerator()""
IL_0006: stloc.0
.try
{
IL_0007: br.s IL_0029
IL_0009: ldloc.0
IL_000a: callvirt ""int Enumerator.Current.get""
IL_000f: pop
.try
{
IL_0010: ldstr ""hello""
IL_0015: stloc.2
IL_0016: ldloc.2
IL_0017: conv.u
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: brfalse.s IL_0024
IL_001c: ldloc.1
IL_001d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0022: add
IL_0023: stloc.1
IL_0024: leave.s IL_0029
}
finally
{
IL_0026: ldnull
IL_0027: stloc.2
IL_0028: endfinally
}
IL_0029: ldloc.0
IL_002a: callvirt ""bool Enumerator.MoveNext()""
IL_002f: brtrue.s IL_0009
IL_0031: leave.s IL_003d
}
finally
{
IL_0033: ldloc.0
IL_0034: brfalse.s IL_003c
IL_0036: ldloc.0
IL_0037: callvirt ""void System.IDisposable.Dispose()""
IL_003c: endfinally
}
IL_003d: ret
}
");
}
[Fact]
public void FixedStatementInLambda1()
{
var text = @"
unsafe class C
{
void Test()
{
System.Action a = () =>
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
};
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}");
}
[Fact]
public void FixedStatementInLambda2()
{
var text = @"
unsafe class C
{
void Test()
{
try
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
}
};
}
finally
{
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
[Fact]
public void FixedStatementInLambda3()
{
var text = @"
unsafe class C
{
void Test()
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
};
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<Test>b__0_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInFieldInitializer1()
{
var text = @"
unsafe class C
{
System.Action a = () =>
{
try
{
fixed (char* p = ""hello"")
{
}
}
finally
{
}
};
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<.ctor>b__1_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementInFieldInitializer2()
{
var text = @"
unsafe class C
{
System.Action a = () =>
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
};
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.<>c.<.ctor>b__1_0()", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_LoopBreak()
{
var text = @"
unsafe class C
{
void Test()
{
while(true)
{
fixed (char* p = ""hello"")
{
break;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_001a
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
IL_001a: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_LoopContinue()
{
var text = @"
unsafe class C
{
void Test()
{
while(true)
{
fixed (char* p = ""hello"")
{
continue;
}
}
}
}
";
// Cleanup in finally.
// CONSIDER: dev11 doesn't have a finally here, but that seems incorrect.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_SwitchBreak()
{
var text = @"
unsafe class C
{
void Test()
{
switch (1)
{
case 1:
fixed (char* p = ""hello"")
{
break;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 27 (0x1b)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_001a
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
IL_001a: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_SwitchGoto()
{
var text = @"
unsafe class C
{
void Test()
{
switch (1)
{
case 1:
fixed (char* p = ""hello"")
{
goto case 1;
}
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_BackwardGoto()
{
var text = @"
unsafe class C
{
void Test()
{
label:
fixed (char* p = ""hello"")
{
goto label;
}
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: nop
.try
{
IL_0001: ldstr ""hello""
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: conv.u
IL_0009: stloc.0
IL_000a: ldloc.0
IL_000b: brfalse.s IL_0015
IL_000d: ldloc.0
IL_000e: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0013: add
IL_0014: stloc.0
IL_0015: leave.s IL_0000
}
finally
{
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: endfinally
}
}
");
}
[Fact]
public void FixedStatementWithBranchOut_ForwardGoto()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
goto label;
}
label: ;
}
}
";
// Cleanup in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 26 (0x1a)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
.try
{
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: leave.s IL_0019
}
finally
{
IL_0016: ldnull
IL_0017: stloc.1
IL_0018: endfinally
}
IL_0019: ret
}
");
}
[Fact]
public void FixedStatementWithBranchOut_Throw()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
throw null;
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 22 (0x16)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: throw
}
");
}
[Fact]
public void FixedStatementWithBranchOut_Return()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
return;
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_Loop()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
for (int i = 0; i < 10; i++)
{
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
int V_2) //i
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldc.i4.0
IL_0015: stloc.2
IL_0016: br.s IL_001c
IL_0018: ldloc.2
IL_0019: ldc.i4.1
IL_001a: add
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: ldc.i4.s 10
IL_001f: blt.s IL_0018
IL_0021: ldnull
IL_0022: stloc.1
IL_0023: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_InternalGoto()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
goto label;
label: ;
}
}
}
";
// NOTE: Dev11 uses a finally here, but it's unnecessary.
// From GotoChecker::VisitGOTO:
// We have an unrealized goto, so we do not know whether it
// branches out or not. We should be conservative and assume that
// it does.
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
[Fact]
public void FixedStatementWithNoBranchOut_Switch()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ""hello"")
{
switch(*p)
{
case 'a':
Test();
goto case 'b';
case 'b':
Test();
goto case 'c';
case 'c':
Test();
goto case 'd';
case 'd':
Test();
goto case 'e';
case 'e':
Test();
goto case 'f';
case 'f':
Test();
goto default;
default:
Test();
break;
}
}
}
}
";
// Cleanup not in finally.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 103 (0x67)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char V_2)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldind.u2
IL_0016: stloc.2
IL_0017: ldloc.2
IL_0018: ldc.i4.s 97
IL_001a: sub
IL_001b: switch (
IL_003a,
IL_0040,
IL_0046,
IL_004c,
IL_0052,
IL_0058)
IL_0038: br.s IL_005e
IL_003a: ldarg.0
IL_003b: call ""void C.Test()""
IL_0040: ldarg.0
IL_0041: call ""void C.Test()""
IL_0046: ldarg.0
IL_0047: call ""void C.Test()""
IL_004c: ldarg.0
IL_004d: call ""void C.Test()""
IL_0052: ldarg.0
IL_0053: call ""void C.Test()""
IL_0058: ldarg.0
IL_0059: call ""void C.Test()""
IL_005e: ldarg.0
IL_005f: call ""void C.Test()""
IL_0064: ldnull
IL_0065: stloc.1
IL_0066: ret
}
");
}
[Fact]
public void FixedStatementWithParenthesizedStringExpression()
{
var text = @"
unsafe class C
{
void Test()
{
fixed (char* p = ((""hello"")))
{
}
}
}";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).
VerifyIL("C.Test", @"
{
// Code size 23 (0x17)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1)
IL_0000: ldstr ""hello""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldnull
IL_0015: stloc.1
IL_0016: ret
}
");
}
#endregion Fixed statement tests
#region Custom fixed statement tests
[Fact]
public void SimpleCaseOfCustomFixed()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
static class FixableExt
{
public static ref int GetPinnableReference(this Fixable self)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: newobj ""Fixable..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_000d
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: br.s IL_0015
IL_000d: call ""ref int Fixable.GetPinnableReference()""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: conv.u
IL_0015: ldc.i4.4
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.0
IL_0020: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixedExt()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
}
class Fixable
{
public ref int GetPinnableReference<T>() => throw null;
}
static class FixableExt
{
public static ref int GetPinnableReference<T>(this T self)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: newobj ""Fixable..ctor()""
IL_0005: dup
IL_0006: brtrue.s IL_000d
IL_0008: pop
IL_0009: ldc.i4.0
IL_000a: conv.u
IL_000b: br.s IL_0015
IL_000d: call ""ref int FixableExt.GetPinnableReference<Fixable>(Fixable)""
IL_0012: stloc.0
IL_0013: ldloc.0
IL_0014: conv.u
IL_0015: ldc.i4.4
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.WriteLine(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.0
IL_0020: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixed_oldVersion()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2);
compVerifier.VerifyDiagnostics(
// (6,25): error CS8320: Feature 'extensible fixed statement' is not available in C# 7.2. Please use language version 7.3 or greater.
// fixed (int* p = new Fixable())
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "new Fixable()").WithArguments("extensible fixed statement", "7.3").WithLocation(6, 25)
);
}
[Fact]
public void SimpleCaseOfCustomFixedNull()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (Fixable)null)
{
System.Console.WriteLine((int)p);
}
}
class Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"0", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 26 (0x1a)
.maxstack 1
.locals init (pinned int& V_0)
IL_0000: ldnull
IL_0001: brtrue.s IL_0007
IL_0003: ldc.i4.0
IL_0004: conv.u
IL_0005: br.s IL_0010
IL_0007: ldnull
IL_0008: call ""ref int C.Fixable.GetPinnableReference()""
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: conv.u
IL_0010: conv.i4
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: ldc.i4.0
IL_0017: conv.u
IL_0018: stloc.0
IL_0019: ret
}
");
}
[Fact]
public void SimpleCaseOfCustomFixedStruct()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.WriteLine(p[1]);
}
}
struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
}";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (pinned int& V_0,
C.Fixable V_1)
IL_0000: ldloca.s V_1
IL_0002: dup
IL_0003: initobj ""C.Fixable""
IL_0009: call ""ref int C.Fixable.GetPinnableReference()""
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: conv.u
IL_0011: ldc.i4.4
IL_0012: add
IL_0013: ldind.i4
IL_0014: call ""void System.Console.WriteLine(int)""
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: ret
}
");
}
[Fact]
public void CustomFixedStructNullable()
{
var text = @"
unsafe class C
{
public static void Main()
{
Fixable? f = new Fixable();
fixed (int* p = f)
{
System.Console.WriteLine(p[1]);
}
}
}
public struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
public static class FixableExt
{
public static ref int GetPinnableReference(this Fixable? f)
{
return ref f.Value.GetPinnableReference();
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (Fixable V_0,
pinned int& V_1)
IL_0000: ldloca.s V_0
IL_0002: initobj ""Fixable""
IL_0008: ldloc.0
IL_0009: newobj ""Fixable?..ctor(Fixable)""
IL_000e: call ""ref int FixableExt.GetPinnableReference(Fixable?)""
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: conv.u
IL_0016: ldc.i4.4
IL_0017: add
IL_0018: ldind.i4
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ldc.i4.0
IL_001f: conv.u
IL_0020: stloc.1
IL_0021: ret
}
");
}
[Fact]
public void CustomFixedStructNullableErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
Fixable? f = new Fixable();
fixed (int* p = f)
{
System.Console.WriteLine(p[1]);
}
}
}
public struct Fixable
{
public ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (8,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "f").WithLocation(8, 25)
);
}
[Fact]
public void CustomFixedErrAmbiguous()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
public static class FixableExt1
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS0121: The call is ambiguous between the following methods or properties: 'FixableExt.GetPinnableReference(in Fixable)' and 'FixableExt1.GetPinnableReference(in Fixable)'
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_AmbigCall, "new Fixable(1)").WithArguments("FixableExt.GetPinnableReference(in Fixable)", "FixableExt1.GetPinnableReference(in Fixable)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25),
// (12,25): error CS0121: The call is ambiguous between the following methods or properties: 'FixableExt.GetPinnableReference(in Fixable)' and 'FixableExt1.GetPinnableReference(in Fixable)'
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_AmbigCall, "f").WithArguments("FixableExt.GetPinnableReference(in Fixable)", "FixableExt1.GetPinnableReference(in Fixable)").WithLocation(12, 25),
// (12,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = f)
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "f").WithLocation(12, 25)
);
}
[Fact]
public void CustomFixedErrDynamic()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (dynamic)(new Fixable(1)))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = (dynamic)(new Fixable(1)))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "(dynamic)(new Fixable(1))").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedErrBad()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = (HocusPocus)(new Fixable(1)))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,26): error CS0246: The type or namespace name 'HocusPocus' could not be found (are you missing a using directive or an assembly reference?)
// fixed (int* p = (HocusPocus)(new Fixable(1)))
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "HocusPocus").WithArguments("HocusPocus").WithLocation(6, 26)
);
}
[Fact]
public void SimpleCaseOfCustomFixedGeneric()
{
var text = @"
unsafe class C
{
public static void Main()
{
Test(42);
Test((object)null);
}
public static void Test<T>(T arg)
{
fixed (int* p = arg)
{
System.Console.Write(p == null? 0: p[1]);
}
}
}
static class FixAllExt
{
public static ref int GetPinnableReference<T>(this T dummy)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"20", verify: Verification.Fails);
compVerifier.VerifyIL("C.Test<T>(T)", @"
{
// Code size 49 (0x31)
.maxstack 2
.locals init (int* V_0, //p
pinned int& V_1)
IL_0000: ldarg.0
IL_0001: box ""T""
IL_0006: brtrue.s IL_000c
IL_0008: ldc.i4.0
IL_0009: conv.u
IL_000a: br.s IL_001b
IL_000c: ldarga.s V_0
IL_000e: ldobj ""T""
IL_0013: call ""ref int FixAllExt.GetPinnableReference<T>(T)""
IL_0018: stloc.1
IL_0019: ldloc.1
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: ldloc.0
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: beq.s IL_0027
IL_0021: ldloc.0
IL_0022: ldc.i4.4
IL_0023: add
IL_0024: ldind.i4
IL_0025: br.s IL_0028
IL_0027: ldc.i4.0
IL_0028: call ""void System.Console.Write(int)""
IL_002d: ldc.i4.0
IL_002e: conv.u
IL_002f: stloc.1
IL_0030: ret
}
");
}
[Fact]
public void CustomFixedStructSideeffects()
{
var text = @"
unsafe class C
{
public static void Main()
{
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test(ref FixableStruct arg)
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
struct FixableStruct
{
public int x;
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyIL("C.Test(ref FixableStruct)", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: call ""ref int FixableStruct.GetPinnableReference()""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.4
IL_000a: add
IL_000b: ldind.i4
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void CustomFixedClassSideeffects()
{
var text = @"
using System;
unsafe class C
{
public static void Main()
{
var b = new FixableClass();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test(ref FixableClass arg)
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
class FixableClass
{
public int x;
[Obsolete]
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyDiagnostics(
// (14,29): warning CS0612: 'FixableClass.GetPinnableReference()' is obsolete
// fixed (int* p = arg)
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "arg").WithArguments("FixableClass.GetPinnableReference()").WithLocation(14, 29)
);
// note that defensive copy is created
compVerifier.VerifyIL("C.Test(ref FixableClass)", @"
{
// Code size 30 (0x1e)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: ldind.ref
IL_0002: dup
IL_0003: brtrue.s IL_000a
IL_0005: pop
IL_0006: ldc.i4.0
IL_0007: conv.u
IL_0008: br.s IL_0012
IL_000a: call ""ref int FixableClass.GetPinnableReference()""
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: conv.u
IL_0012: ldc.i4.4
IL_0013: add
IL_0014: ldind.i4
IL_0015: call ""void System.Console.Write(int)""
IL_001a: ldc.i4.0
IL_001b: conv.u
IL_001c: stloc.0
IL_001d: ret
}
");
}
[Fact]
public void CustomFixedGenericSideeffects()
{
var text = @"
unsafe class C
{
public static void Main()
{
var a = new FixableClass();
Test(ref a);
System.Console.WriteLine(a.x);
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test<T>(ref T arg) where T: IFixable
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
interface IFixable
{
ref int GetPinnableReference();
}
class FixableClass : IFixable
{
public int x;
public ref int GetPinnableReference()
{
x = 123;
return ref (new int[] { 1, 2, 3 })[0];
}
}
struct FixableStruct : IFixable
{
public int x;
public ref int GetPinnableReference()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"2123
5456");
compVerifier.VerifyIL("C.Test<T>(ref T)", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (pinned int& V_0,
T V_1)
IL_0000: ldarg.0
IL_0001: ldloca.s V_1
IL_0003: initobj ""T""
IL_0009: ldloc.1
IL_000a: box ""T""
IL_000f: brtrue.s IL_0026
IL_0011: ldobj ""T""
IL_0016: stloc.1
IL_0017: ldloca.s V_1
IL_0019: ldloc.1
IL_001a: box ""T""
IL_001f: brtrue.s IL_0026
IL_0021: pop
IL_0022: ldc.i4.0
IL_0023: conv.u
IL_0024: br.s IL_0034
IL_0026: constrained. ""T""
IL_002c: callvirt ""ref int IFixable.GetPinnableReference()""
IL_0031: stloc.0
IL_0032: ldloc.0
IL_0033: conv.u
IL_0034: ldc.i4.4
IL_0035: add
IL_0036: ldind.i4
IL_0037: call ""void System.Console.Write(int)""
IL_003c: ldc.i4.0
IL_003d: conv.u
IL_003e: stloc.0
IL_003f: ret
}
");
}
[Fact]
public void CustomFixedGenericRefExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
var b = new FixableStruct();
Test(ref b);
System.Console.WriteLine(b.x);
}
public static void Test<T>(ref T arg) where T: struct, IFixable
{
fixed (int* p = arg)
{
System.Console.Write(p[1]);
}
}
}
public interface IFixable
{
ref int GetPinnableReferenceImpl();
}
public struct FixableStruct : IFixable
{
public int x;
public ref int GetPinnableReferenceImpl()
{
x = 456;
return ref (new int[] { 4, 5, 6 })[0];
}
}
public static class FixableExt
{
public static ref int GetPinnableReference<T>(ref this T f) where T: struct, IFixable
{
return ref f.GetPinnableReferenceImpl();
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"5456");
compVerifier.VerifyIL("C.Test<T>(ref T)", @"
{
// Code size 21 (0x15)
.maxstack 2
.locals init (pinned int& V_0)
IL_0000: ldarg.0
IL_0001: call ""ref int FixableExt.GetPinnableReference<T>(ref T)""
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.4
IL_000a: add
IL_000b: ldind.i4
IL_000c: call ""void System.Console.Write(int)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.0
IL_0014: ret
}
");
}
[Fact]
public void CustomFixedStructInExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref readonly int GetPinnableReference(in this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"23", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 61 (0x3d)
.maxstack 3
.locals init (Fixable V_0, //f
pinned int& V_1,
Fixable V_2)
IL_0000: ldc.i4.1
IL_0001: newobj ""Fixable..ctor(int)""
IL_0006: stloc.2
IL_0007: ldloca.s V_2
IL_0009: call ""ref readonly int FixableExt.GetPinnableReference(in Fixable)""
IL_000e: stloc.1
IL_000f: ldloc.1
IL_0010: conv.u
IL_0011: ldc.i4.4
IL_0012: add
IL_0013: ldind.i4
IL_0014: call ""void System.Console.Write(int)""
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.1
IL_001c: ldloca.s V_0
IL_001e: ldc.i4.1
IL_001f: call ""Fixable..ctor(int)""
IL_0024: ldloca.s V_0
IL_0026: call ""ref readonly int FixableExt.GetPinnableReference(in Fixable)""
IL_002b: stloc.1
IL_002c: ldloc.1
IL_002d: conv.u
IL_002e: ldc.i4.2
IL_002f: conv.i
IL_0030: ldc.i4.4
IL_0031: mul
IL_0032: add
IL_0033: ldind.i4
IL_0034: call ""void System.Console.Write(int)""
IL_0039: ldc.i4.0
IL_003a: conv.u
IL_003b: stloc.1
IL_003c: ret
}
");
}
[Fact]
public void CustomFixedStructRefExtension()
{
var text = @"
unsafe class C
{
public static void Main()
{
var f = new Fixable(1);
fixed (int* p = f)
{
System.Console.Write(p[2]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref int GetPinnableReference(ref this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"3", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 3
.locals init (Fixable V_0, //f
pinned int& V_1)
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: call ""Fixable..ctor(int)""
IL_0008: ldloca.s V_0
IL_000a: call ""ref int FixableExt.GetPinnableReference(ref Fixable)""
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: conv.u
IL_0012: ldc.i4.2
IL_0013: conv.i
IL_0014: ldc.i4.4
IL_0015: mul
IL_0016: add
IL_0017: ldind.i4
IL_0018: call ""void System.Console.Write(int)""
IL_001d: ldc.i4.0
IL_001e: conv.u
IL_001f: stloc.1
IL_0020: ret
}
");
}
[Fact]
public void CustomFixedStructRefExtensionErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
public static ref int GetPinnableReference(ref this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS1510: A ref or out value must be an assignable variable
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "new Fixable(1)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr01()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
private static ref int GetPinnableReference(this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS8385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr01_oldVersion()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
}
public static class FixableExt
{
private static ref int GetPinnableReference(this Fixable f)
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_2);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr02()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public static ref int GetPinnableReference()
{
return ref (new int[]{1,2,3})[0];
}
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25),
// (6,25): error CS0176: Member 'Fixable.GetPinnableReference()' cannot be accessed with an instance reference; qualify it with a type name instead
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ObjectProhibited, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference()").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr03()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS1955: Non-invocable member 'Fixable.GetPinnableReference' cannot be used like a method.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr04()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference<T>() => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS0411: The type arguments for method 'Fixable.GetPinnableReference<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference<T>()").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr05_Obsolete()
{
var text = @"
using System;
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
[Obsolete(""hi"", true)]
public ref int GetPinnableReference() => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (8,25): error CS0619: 'Fixable.GetPinnableReference()' is obsolete: 'hi'
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "new Fixable(1)").WithArguments("Fixable.GetPinnableReference()", "hi").WithLocation(8, 25)
);
}
[Fact]
public void CustomFixedStructVariousErr06_UseSite()
{
var missing_cs = "public struct Missing { }";
var missing = CreateCompilationWithMscorlib45(missing_cs, options: TestOptions.DebugDll, assemblyName: "missing");
var lib_cs = @"
public struct Fixable
{
public Fixable(int arg){}
public ref Missing GetPinnableReference() => throw null;
}
";
var lib = CreateCompilationWithMscorlib45(lib_cs, references: new[] { missing.EmitToImageReference() }, options: TestOptions.DebugDll);
var source =
@"
unsafe class C
{
public static void Main()
{
fixed (void* p = new Fixable(1))
{
}
}
}
";
var comp = CreateCompilationWithMscorlib45(source, references: new[] { lib.EmitToImageReference() }, options: TestOptions.UnsafeDebugDll);
comp.VerifyDiagnostics(
// (6,26): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// fixed (void* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_NoTypeDef, "new Fixable(1)").WithArguments("Missing", "missing, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 26),
// (6,26): error CS9385: The given expression cannot be used in a fixed statement
// fixed (void* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 26)
);
}
[Fact]
public void CustomFixedStructVariousErr07_Optional()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable(1))
{
System.Console.Write(p[1]);
}
}
}
public struct Fixable
{
public Fixable(int arg){}
public ref int GetPinnableReference(int x = 0) => ref (new int[]{1,2,3})[0];
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): warning CS0280: 'Fixable' does not implement the 'fixed' pattern. 'Fixable.GetPinnableReference(int)' has the wrong signature.
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.WRN_PatternBadSignature, "new Fixable(1)").WithArguments("Fixable", "fixed", "Fixable.GetPinnableReference(int)").WithLocation(6, 25),
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable(1))
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable(1)").WithLocation(6, 25)
);
}
[Fact]
public void FixStringMissingAllHelpers()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (char* p = string.Empty)
{
}
}
}
";
var comp = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
comp.MakeMemberMissing(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__get_OffsetToStringData);
comp.VerifyEmitDiagnostics(
// (6,26): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData'
// fixed (char* p = string.Empty)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "string.Empty").WithArguments("System.Runtime.CompilerServices.RuntimeHelpers", "get_OffsetToStringData").WithLocation(6, 26)
);
}
[Fact]
public void FixStringArrayExtensionHelpersIgnored()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (char* p = ""A"")
{
*p = default;
}
fixed (char* p = new char[1])
{
*p = default;
}
}
}
public static class FixableExt
{
public static ref char GetPinnableReference(this string self) => throw null;
public static ref char GetPinnableReference(this char[] self) => throw null;
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"");
compVerifier.VerifyIL("C.Main()", @"
{
// Code size 60 (0x3c)
.maxstack 2
.locals init (char* V_0, //p
pinned string V_1,
char* V_2, //p
pinned char[] V_3)
IL_0000: ldstr ""A""
IL_0005: stloc.1
IL_0006: ldloc.1
IL_0007: conv.u
IL_0008: stloc.0
IL_0009: ldloc.0
IL_000a: brfalse.s IL_0014
IL_000c: ldloc.0
IL_000d: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0012: add
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: ldc.i4.0
IL_0016: stind.i2
IL_0017: ldnull
IL_0018: stloc.1
IL_0019: ldc.i4.1
IL_001a: newarr ""char""
IL_001f: dup
IL_0020: stloc.3
IL_0021: brfalse.s IL_0028
IL_0023: ldloc.3
IL_0024: ldlen
IL_0025: conv.i4
IL_0026: brtrue.s IL_002d
IL_0028: ldc.i4.0
IL_0029: conv.u
IL_002a: stloc.2
IL_002b: br.s IL_0036
IL_002d: ldloc.3
IL_002e: ldc.i4.0
IL_002f: ldelema ""char""
IL_0034: conv.u
IL_0035: stloc.2
IL_0036: ldloc.2
IL_0037: ldc.i4.0
IL_0038: stind.i2
IL_0039: ldnull
IL_003a: stloc.3
IL_003b: ret
}
");
}
[Fact]
public void CustomFixedDelegateErr()
{
var text = @"
unsafe class C
{
public static void Main()
{
fixed (int* p = new Fixable())
{
System.Console.Write(p[1]);
}
}
}
public delegate ref int ReturnsRef();
public struct Fixable
{
public Fixable(int arg){}
public ReturnsRef GetPinnableReference => null;
}
";
var compVerifier = CreateCompilationWithMscorlib46(text, options: TestOptions.UnsafeReleaseExe);
compVerifier.VerifyDiagnostics(
// (6,25): error CS9385: The given expression cannot be used in a fixed statement
// fixed (int* p = new Fixable())
Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "new Fixable()").WithLocation(6, 25)
);
}
#endregion Custom fixed statement tests
#region Pointer conversion tests
[Fact]
public void ConvertNullToPointer()
{
var template = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
char ch = 'a';
char* p = &ch;
Console.WriteLine(p == null);
p = null;
Console.WriteLine(p == null);
}}
}}
}}
";
var expectedIL = @"
{
// Code size 31 (0x1f)
.maxstack 2
.locals init (char V_0, //ch
char* V_1) //p
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: ldc.i4.0
IL_0009: conv.u
IL_000a: ceq
IL_000c: call ""void System.Console.WriteLine(bool)""
IL_0011: ldc.i4.0
IL_0012: conv.u
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: ldc.i4.0
IL_0016: conv.u
IL_0017: ceq
IL_0019: call ""void System.Console.WriteLine(bool)""
IL_001e: ret
}
";
var expectedOutput = @"False
True";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[Fact]
public void ConvertPointerToPointerOrVoid()
{
var template = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
char ch = 'a';
char* c1 = &ch;
void* v1 = c1;
void* v2 = (void**)v1;
char* c2 = (char*)v2;
Console.WriteLine(*c2);
}}
}}
}}
";
var expectedIL = @"
{
// Code size 19 (0x13)
.maxstack 1
.locals init (char V_0, //ch
void* V_1, //v1
void* V_2, //v2
char* V_3) //c2
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: ldloca.s V_0
IL_0005: conv.u
IL_0006: stloc.1
IL_0007: ldloc.1
IL_0008: stloc.2
IL_0009: ldloc.2
IL_000a: stloc.3
IL_000b: ldloc.3
IL_000c: ldind.u2
IL_000d: call ""void System.Console.WriteLine(char)""
IL_0012: ret
}
";
var expectedOutput = @"a";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[Fact]
public void ConvertPointerToNumericUnchecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
unchecked
{
sb = (sbyte)pi;
b = (byte)pi;
s = (short)pi;
us = (ushort)pi;
i = (int)pi;
ui = (uint)pi;
l = (long)pi;
ul = (ulong)pi;
sb = (sbyte)pv;
b = (byte)pv;
s = (short)pv;
us = (ushort)pv;
i = (int)pv;
ui = (uint)pv;
l = (long)pv;
ul = (ulong)pv;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 65 (0x41)
.maxstack 1
IL_0000: ldarg.1
IL_0001: conv.i1
IL_0002: starg.s V_3
IL_0004: ldarg.1
IL_0005: conv.u1
IL_0006: starg.s V_4
IL_0008: ldarg.1
IL_0009: conv.i2
IL_000a: starg.s V_5
IL_000c: ldarg.1
IL_000d: conv.u2
IL_000e: starg.s V_6
IL_0010: ldarg.1
IL_0011: conv.i4
IL_0012: starg.s V_7
IL_0014: ldarg.1
IL_0015: conv.u4
IL_0016: starg.s V_8
IL_0018: ldarg.1
IL_0019: conv.u8
IL_001a: starg.s V_9
IL_001c: ldarg.1
IL_001d: conv.u8
IL_001e: starg.s V_10
IL_0020: ldarg.2
IL_0021: conv.i1
IL_0022: starg.s V_3
IL_0024: ldarg.2
IL_0025: conv.u1
IL_0026: starg.s V_4
IL_0028: ldarg.2
IL_0029: conv.i2
IL_002a: starg.s V_5
IL_002c: ldarg.2
IL_002d: conv.u2
IL_002e: starg.s V_6
IL_0030: ldarg.2
IL_0031: conv.i4
IL_0032: starg.s V_7
IL_0034: ldarg.2
IL_0035: conv.u4
IL_0036: starg.s V_8
IL_0038: ldarg.2
IL_0039: conv.u8
IL_003a: starg.s V_9
IL_003c: ldarg.2
IL_003d: conv.u8
IL_003e: starg.s V_10
IL_0040: ret
}
");
}
[Fact]
public void ConvertPointerToNumericChecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
checked
{
sb = (sbyte)pi;
b = (byte)pi;
s = (short)pi;
us = (ushort)pi;
i = (int)pi;
ui = (uint)pi;
l = (long)pi;
ul = (ulong)pi;
sb = (sbyte)pv;
b = (byte)pv;
s = (short)pv;
us = (ushort)pv;
i = (int)pv;
ui = (uint)pv;
l = (long)pv;
ul = (ulong)pv;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 65 (0x41)
.maxstack 1
IL_0000: ldarg.1
IL_0001: conv.ovf.i1.un
IL_0002: starg.s V_3
IL_0004: ldarg.1
IL_0005: conv.ovf.u1.un
IL_0006: starg.s V_4
IL_0008: ldarg.1
IL_0009: conv.ovf.i2.un
IL_000a: starg.s V_5
IL_000c: ldarg.1
IL_000d: conv.ovf.u2.un
IL_000e: starg.s V_6
IL_0010: ldarg.1
IL_0011: conv.ovf.i4.un
IL_0012: starg.s V_7
IL_0014: ldarg.1
IL_0015: conv.ovf.u4.un
IL_0016: starg.s V_8
IL_0018: ldarg.1
IL_0019: conv.ovf.i8.un
IL_001a: starg.s V_9
IL_001c: ldarg.1
IL_001d: conv.u8
IL_001e: starg.s V_10
IL_0020: ldarg.2
IL_0021: conv.ovf.i1.un
IL_0022: starg.s V_3
IL_0024: ldarg.2
IL_0025: conv.ovf.u1.un
IL_0026: starg.s V_4
IL_0028: ldarg.2
IL_0029: conv.ovf.i2.un
IL_002a: starg.s V_5
IL_002c: ldarg.2
IL_002d: conv.ovf.u2.un
IL_002e: starg.s V_6
IL_0030: ldarg.2
IL_0031: conv.ovf.i4.un
IL_0032: starg.s V_7
IL_0034: ldarg.2
IL_0035: conv.ovf.u4.un
IL_0036: starg.s V_8
IL_0038: ldarg.2
IL_0039: conv.ovf.i8.un
IL_003a: starg.s V_9
IL_003c: ldarg.2
IL_003d: conv.u8
IL_003e: starg.s V_10
IL_0040: ret
}
");
}
[Fact]
public void ConvertNumericToPointerUnchecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
unchecked
{
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 79 (0x4f)
.maxstack 1
IL_0000: ldarg.3
IL_0001: conv.i
IL_0002: starg.s V_1
IL_0004: ldarg.s V_4
IL_0006: conv.u
IL_0007: starg.s V_1
IL_0009: ldarg.s V_5
IL_000b: conv.i
IL_000c: starg.s V_1
IL_000e: ldarg.s V_6
IL_0010: conv.u
IL_0011: starg.s V_1
IL_0013: ldarg.s V_7
IL_0015: conv.i
IL_0016: starg.s V_1
IL_0018: ldarg.s V_8
IL_001a: conv.u
IL_001b: starg.s V_1
IL_001d: ldarg.s V_9
IL_001f: conv.u
IL_0020: starg.s V_1
IL_0022: ldarg.s V_10
IL_0024: conv.u
IL_0025: starg.s V_1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: starg.s V_2
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: starg.s V_2
IL_0030: ldarg.s V_5
IL_0032: conv.i
IL_0033: starg.s V_2
IL_0035: ldarg.s V_6
IL_0037: conv.u
IL_0038: starg.s V_2
IL_003a: ldarg.s V_7
IL_003c: conv.i
IL_003d: starg.s V_2
IL_003f: ldarg.s V_8
IL_0041: conv.u
IL_0042: starg.s V_2
IL_0044: ldarg.s V_9
IL_0046: conv.u
IL_0047: starg.s V_2
IL_0049: ldarg.s V_10
IL_004b: conv.u
IL_004c: starg.s V_2
IL_004e: ret
}
");
}
[Fact]
public void ConvertNumericToPointerChecked()
{
var text = @"
using System;
unsafe class C
{
void M(int* pi, void* pv, sbyte sb, byte b, short s, ushort us, int i, uint ui, long l, ulong ul)
{
checked
{
pi = (int*)sb;
pi = (int*)b;
pi = (int*)s;
pi = (int*)us;
pi = (int*)i;
pi = (int*)ui;
pi = (int*)l;
pi = (int*)ul;
pv = (void*)sb;
pv = (void*)b;
pv = (void*)s;
pv = (void*)us;
pv = (void*)i;
pv = (void*)ui;
pv = (void*)l;
pv = (void*)ul;
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 79 (0x4f)
.maxstack 1
IL_0000: ldarg.3
IL_0001: conv.ovf.u
IL_0002: starg.s V_1
IL_0004: ldarg.s V_4
IL_0006: conv.u
IL_0007: starg.s V_1
IL_0009: ldarg.s V_5
IL_000b: conv.ovf.u
IL_000c: starg.s V_1
IL_000e: ldarg.s V_6
IL_0010: conv.u
IL_0011: starg.s V_1
IL_0013: ldarg.s V_7
IL_0015: conv.ovf.u
IL_0016: starg.s V_1
IL_0018: ldarg.s V_8
IL_001a: conv.u
IL_001b: starg.s V_1
IL_001d: ldarg.s V_9
IL_001f: conv.ovf.u
IL_0020: starg.s V_1
IL_0022: ldarg.s V_10
IL_0024: conv.ovf.u.un
IL_0025: starg.s V_1
IL_0027: ldarg.3
IL_0028: conv.ovf.u
IL_0029: starg.s V_2
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: starg.s V_2
IL_0030: ldarg.s V_5
IL_0032: conv.ovf.u
IL_0033: starg.s V_2
IL_0035: ldarg.s V_6
IL_0037: conv.u
IL_0038: starg.s V_2
IL_003a: ldarg.s V_7
IL_003c: conv.ovf.u
IL_003d: starg.s V_2
IL_003f: ldarg.s V_8
IL_0041: conv.u
IL_0042: starg.s V_2
IL_0044: ldarg.s V_9
IL_0046: conv.ovf.u
IL_0047: starg.s V_2
IL_0049: ldarg.s V_10
IL_004b: conv.ovf.u.un
IL_004c: starg.s V_2
IL_004e: ret
}
");
}
[Fact]
public void ConvertClassToPointerUDC()
{
var template = @"
using System;
unsafe class C
{{
void M(int* pi, void* pv, Explicit e, Implicit i)
{{
{0}
{{
e = (Explicit)pi;
e = (Explicit)pv;
i = pi;
i = pv;
pi = (int*)e;
pv = (int*)e;
pi = i;
pv = i;
}}
}}
}}
unsafe class Explicit
{{
public static explicit operator Explicit(void* p)
{{
return null;
}}
public static explicit operator int*(Explicit e)
{{
return null;
}}
}}
unsafe class Implicit
{{
public static implicit operator Implicit(void* p)
{{
return null;
}}
public static implicit operator int*(Implicit e)
{{
return null;
}}
}}
";
var expectedIL = @"
{
// Code size 67 (0x43)
.maxstack 1
IL_0000: ldarg.1
IL_0001: call ""Explicit Explicit.op_Explicit(void*)""
IL_0006: starg.s V_3
IL_0008: ldarg.2
IL_0009: call ""Explicit Explicit.op_Explicit(void*)""
IL_000e: starg.s V_3
IL_0010: ldarg.1
IL_0011: call ""Implicit Implicit.op_Implicit(void*)""
IL_0016: starg.s V_4
IL_0018: ldarg.2
IL_0019: call ""Implicit Implicit.op_Implicit(void*)""
IL_001e: starg.s V_4
IL_0020: ldarg.3
IL_0021: call ""int* Explicit.op_Explicit(Explicit)""
IL_0026: starg.s V_1
IL_0028: ldarg.3
IL_0029: call ""int* Explicit.op_Explicit(Explicit)""
IL_002e: starg.s V_2
IL_0030: ldarg.s V_4
IL_0032: call ""int* Implicit.op_Implicit(Implicit)""
IL_0037: starg.s V_1
IL_0039: ldarg.s V_4
IL_003b: call ""int* Implicit.op_Implicit(Implicit)""
IL_0040: starg.s V_2
IL_0042: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
}
[Fact]
public void ConvertIntPtrToPointer()
{
var template = @"
using System;
unsafe class C
{{
void M(int* pi, void* pv, IntPtr i, UIntPtr u)
{{
{0}
{{
i = (IntPtr)pi;
i = (IntPtr)pv;
u = (UIntPtr)pi;
u = (UIntPtr)pv;
pi = (int*)i;
pv = (int*)i;
pi = (int*)u;
pv = (int*)u;
}}
}}
}}
";
// Nothing special here - just more UDCs.
var expectedIL = @"
{
// Code size 67 (0x43)
.maxstack 1
IL_0000: ldarg.1
IL_0001: call ""System.IntPtr System.IntPtr.op_Explicit(void*)""
IL_0006: starg.s V_3
IL_0008: ldarg.2
IL_0009: call ""System.IntPtr System.IntPtr.op_Explicit(void*)""
IL_000e: starg.s V_3
IL_0010: ldarg.1
IL_0011: call ""System.UIntPtr System.UIntPtr.op_Explicit(void*)""
IL_0016: starg.s V_4
IL_0018: ldarg.2
IL_0019: call ""System.UIntPtr System.UIntPtr.op_Explicit(void*)""
IL_001e: starg.s V_4
IL_0020: ldarg.3
IL_0021: call ""void* System.IntPtr.op_Explicit(System.IntPtr)""
IL_0026: starg.s V_1
IL_0028: ldarg.3
IL_0029: call ""void* System.IntPtr.op_Explicit(System.IntPtr)""
IL_002e: starg.s V_2
IL_0030: ldarg.s V_4
IL_0032: call ""void* System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0037: starg.s V_1
IL_0039: ldarg.s V_4
IL_003b: call ""void* System.UIntPtr.op_Explicit(System.UIntPtr)""
IL_0040: starg.s V_2
IL_0042: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", expectedIL);
}
[Fact]
public void FixedStatementConversion()
{
var template = @"
using System;
unsafe class C
{{
char c = 'a';
char[] a = new char[1];
static void Main()
{{
{0}
{{
C c = new C();
fixed (void* p = &c.c, q = c.a, r = ""hello"")
{{
Console.Write((int)*(char*)p);
Console.Write((int)*(char*)q);
Console.Write((int)*(char*)r);
}}
}}
}}
}}
";
// NB: "pinned System.IntPtr&" (which ildasm displays as "pinned native int&"), not void.
var expectedIL = @"
{
// Code size 112 (0x70)
.maxstack 2
.locals init (C V_0, //c
void* V_1, //p
void* V_2, //q
void* V_3, //r
pinned char& V_4,
pinned char[] V_5,
pinned string V_6)
-IL_0000: nop
-IL_0001: nop
-IL_0002: newobj ""C..ctor()""
IL_0007: stloc.0
IL_0008: ldloc.0
IL_0009: ldflda ""char C.c""
IL_000e: stloc.s V_4
-IL_0010: ldloc.s V_4
IL_0012: conv.u
IL_0013: stloc.1
-IL_0014: ldloc.0
IL_0015: ldfld ""char[] C.a""
IL_001a: dup
IL_001b: stloc.s V_5
IL_001d: brfalse.s IL_0025
IL_001f: ldloc.s V_5
IL_0021: ldlen
IL_0022: conv.i4
IL_0023: brtrue.s IL_002a
IL_0025: ldc.i4.0
IL_0026: conv.u
IL_0027: stloc.2
IL_0028: br.s IL_0034
IL_002a: ldloc.s V_5
IL_002c: ldc.i4.0
IL_002d: ldelema ""char""
IL_0032: conv.u
IL_0033: stloc.2
IL_0034: ldstr ""hello""
IL_0039: stloc.s V_6
-IL_003b: ldloc.s V_6
IL_003d: conv.u
IL_003e: stloc.3
IL_003f: ldloc.3
IL_0040: brfalse.s IL_004a
IL_0042: ldloc.3
IL_0043: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_0048: add
IL_0049: stloc.3
-IL_004a: nop
-IL_004b: ldloc.1
IL_004c: ldind.u2
IL_004d: call ""void System.Console.Write(int)""
IL_0052: nop
-IL_0053: ldloc.2
IL_0054: ldind.u2
IL_0055: call ""void System.Console.Write(int)""
IL_005a: nop
-IL_005b: ldloc.3
IL_005c: ldind.u2
IL_005d: call ""void System.Console.Write(int)""
IL_0062: nop
-IL_0063: nop
~IL_0064: ldc.i4.0
IL_0065: conv.u
IL_0066: stloc.s V_4
IL_0068: ldnull
IL_0069: stloc.s V_5
IL_006b: ldnull
IL_006c: stloc.s V_6
-IL_006e: nop
-IL_006f: ret
}
";
var expectedOutput = @"970104";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL, sequencePoints: "C.Main");
CompileAndVerify(string.Format(template, "checked "), options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL, sequencePoints: "C.Main");
}
[Fact]
public void FixedStatementVoidPointerPointer()
{
var template = @"
using System;
unsafe class C
{{
void* v;
static void Main()
{{
{0}
{{
char ch = 'a';
C c = new C();
c.v = &ch;
fixed (void** p = &c.v)
{{
Console.Write(*(char*)*p);
}}
}}
}}
}}
";
// NB: "pinned void*&", as in Dev10.
var expectedIL = @"
{
// Code size 36 (0x24)
.maxstack 3
.locals init (char V_0, //ch
pinned void*& V_1)
IL_0000: ldc.i4.s 97
IL_0002: stloc.0
IL_0003: newobj ""C..ctor()""
IL_0008: dup
IL_0009: ldloca.s V_0
IL_000b: conv.u
IL_000c: stfld ""void* C.v""
IL_0011: ldflda ""void* C.v""
IL_0016: stloc.1
IL_0017: ldloc.1
IL_0018: conv.u
IL_0019: ldind.i
IL_001a: ldind.u2
IL_001b: call ""void System.Console.Write(char)""
IL_0020: ldc.i4.0
IL_0021: conv.u
IL_0022: stloc.1
IL_0023: ret
}
";
var expectedOutput = @"a";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("C.Main", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayConversion()
{
var template = @"
using System;
unsafe class C
{{
void M(int*[] api, void*[] apv, Array a)
{{
{0}
{{
a = api;
a = apv;
api = (int*[])a;
apv = (void*[])a;
}}
}}
}}
";
var expectedIL = @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.1
IL_0001: starg.s V_3
IL_0003: ldarg.2
IL_0004: starg.s V_3
IL_0006: ldarg.3
IL_0007: castclass ""int*[]""
IL_000c: starg.s V_1
IL_000e: ldarg.3
IL_000f: castclass ""void*[]""
IL_0014: starg.s V_2
IL_0016: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayConversionRuntimeError()
{
var text = @"
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] api = new int*[1];
System.Array a = api;
a.GetValue(0);
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayEnumerableConversion()
{
var template = @"
using System.Collections;
unsafe class C
{{
void M(int*[] api, void*[] apv, IEnumerable e)
{{
{0}
{{
e = api;
e = apv;
api = (int*[])e;
apv = (void*[])e;
}}
}}
}}
";
var expectedIL = @"
{
// Code size 23 (0x17)
.maxstack 1
IL_0000: ldarg.1
IL_0001: starg.s V_3
IL_0003: ldarg.2
IL_0004: starg.s V_3
IL_0006: ldarg.3
IL_0007: castclass ""int*[]""
IL_000c: starg.s V_1
IL_000e: ldarg.3
IL_000f: castclass ""void*[]""
IL_0014: starg.s V_2
IL_0016: ret
}
";
CompileAndVerify(string.Format(template, "unchecked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
CompileAndVerify(string.Format(template, "checked"), options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyIL("C.M", expectedIL);
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayEnumerableConversionRuntimeError()
{
var text = @"
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] api = new int*[1];
System.Collections.IEnumerable e = api;
var enumerator = e.GetEnumerator();
enumerator.MoveNext();
var current = enumerator.Current;
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
[Fact]
public void PointerArrayForeachSingle()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int*[] array = new []
{
(int*)1,
(int*)2,
};
foreach (var element in array)
{
Console.Write((int)element);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "12", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 41 (0x29)
.maxstack 4
.locals init (int*[] V_0,
int V_1)
IL_0000: ldc.i4.2
IL_0001: newarr ""int*""
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldc.i4.1
IL_0009: conv.i
IL_000a: stelem.i
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldc.i4.2
IL_000e: conv.i
IL_000f: stelem.i
IL_0010: stloc.0
IL_0011: ldc.i4.0
IL_0012: stloc.1
IL_0013: br.s IL_0022
IL_0015: ldloc.0
IL_0016: ldloc.1
IL_0017: ldelem.i
IL_0018: conv.i4
IL_0019: call ""void System.Console.Write(int)""
IL_001e: ldloc.1
IL_001f: ldc.i4.1
IL_0020: add
IL_0021: stloc.1
IL_0022: ldloc.1
IL_0023: ldloc.0
IL_0024: ldlen
IL_0025: conv.i4
IL_0026: blt.s IL_0015
IL_0028: ret
}
");
}
[Fact]
public void PointerArrayForeachMultiple()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
int*[,] array = new [,]
{
{ (int*)1, (int*)2, },
{ (int*)3, (int*)4, },
};
foreach (var element in array)
{
Console.Write((int)element);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "1234", verify: Verification.Fails).VerifyIL("C.Main", @"
{
// Code size 120 (0x78)
.maxstack 5
.locals init (int*[,] V_0,
int V_1,
int V_2,
int V_3,
int V_4)
IL_0000: ldc.i4.2
IL_0001: ldc.i4.2
IL_0002: newobj ""int*[*,*]..ctor""
IL_0007: dup
IL_0008: ldc.i4.0
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: conv.i
IL_000c: call ""int*[*,*].Set""
IL_0011: dup
IL_0012: ldc.i4.0
IL_0013: ldc.i4.1
IL_0014: ldc.i4.2
IL_0015: conv.i
IL_0016: call ""int*[*,*].Set""
IL_001b: dup
IL_001c: ldc.i4.1
IL_001d: ldc.i4.0
IL_001e: ldc.i4.3
IL_001f: conv.i
IL_0020: call ""int*[*,*].Set""
IL_0025: dup
IL_0026: ldc.i4.1
IL_0027: ldc.i4.1
IL_0028: ldc.i4.4
IL_0029: conv.i
IL_002a: call ""int*[*,*].Set""
IL_002f: stloc.0
IL_0030: ldloc.0
IL_0031: ldc.i4.0
IL_0032: callvirt ""int System.Array.GetUpperBound(int)""
IL_0037: stloc.1
IL_0038: ldloc.0
IL_0039: ldc.i4.1
IL_003a: callvirt ""int System.Array.GetUpperBound(int)""
IL_003f: stloc.2
IL_0040: ldloc.0
IL_0041: ldc.i4.0
IL_0042: callvirt ""int System.Array.GetLowerBound(int)""
IL_0047: stloc.3
IL_0048: br.s IL_0073
IL_004a: ldloc.0
IL_004b: ldc.i4.1
IL_004c: callvirt ""int System.Array.GetLowerBound(int)""
IL_0051: stloc.s V_4
IL_0053: br.s IL_006a
IL_0055: ldloc.0
IL_0056: ldloc.3
IL_0057: ldloc.s V_4
IL_0059: call ""int*[*,*].Get""
IL_005e: conv.i4
IL_005f: call ""void System.Console.Write(int)""
IL_0064: ldloc.s V_4
IL_0066: ldc.i4.1
IL_0067: add
IL_0068: stloc.s V_4
IL_006a: ldloc.s V_4
IL_006c: ldloc.2
IL_006d: ble.s IL_0055
IL_006f: ldloc.3
IL_0070: ldc.i4.1
IL_0071: add
IL_0072: stloc.3
IL_0073: ldloc.3
IL_0074: ldloc.1
IL_0075: ble.s IL_004a
IL_0077: ret
}
");
}
[ConditionalFact(typeof(DesktopOnly))]
public void PointerArrayForeachEnumerable()
{
var text = @"
using System;
using System.Collections;
unsafe class C
{
static void Main()
{
System.Globalization.CultureInfo saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
try
{
int*[] array = new []
{
(int*)1,
(int*)2,
};
foreach (var element in (IEnumerable)array)
{
Console.Write((int)element);
}
}
finally
{
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture;
}
}
}
";
CompileAndVerifyException<NotSupportedException>(text, "Type is not supported.", allowUnsafe: true, verify: Verification.Fails);
}
#endregion Pointer conversion tests
#region sizeof tests
[Fact]
public void SizeOfConstant()
{
var text = @"
using System;
class C
{
static void Main()
{
Console.WriteLine(sizeof(sbyte));
Console.WriteLine(sizeof(byte));
Console.WriteLine(sizeof(short));
Console.WriteLine(sizeof(ushort));
Console.WriteLine(sizeof(int));
Console.WriteLine(sizeof(uint));
Console.WriteLine(sizeof(long));
Console.WriteLine(sizeof(ulong));
Console.WriteLine(sizeof(char));
Console.WriteLine(sizeof(float));
Console.WriteLine(sizeof(double));
Console.WriteLine(sizeof(bool));
Console.WriteLine(sizeof(decimal)); //Supported by dev10, but not spec.
}
}
";
var expectedOutput = @"
1
1
2
2
4
4
8
8
2
4
8
1
16
".Trim();
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 80 (0x50)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ldc.i4.1
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ldc.i4.2
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ldc.i4.2
IL_0013: call ""void System.Console.WriteLine(int)""
IL_0018: ldc.i4.4
IL_0019: call ""void System.Console.WriteLine(int)""
IL_001e: ldc.i4.4
IL_001f: call ""void System.Console.WriteLine(int)""
IL_0024: ldc.i4.8
IL_0025: call ""void System.Console.WriteLine(int)""
IL_002a: ldc.i4.8
IL_002b: call ""void System.Console.WriteLine(int)""
IL_0030: ldc.i4.2
IL_0031: call ""void System.Console.WriteLine(int)""
IL_0036: ldc.i4.4
IL_0037: call ""void System.Console.WriteLine(int)""
IL_003c: ldc.i4.8
IL_003d: call ""void System.Console.WriteLine(int)""
IL_0042: ldc.i4.1
IL_0043: call ""void System.Console.WriteLine(int)""
IL_0048: ldc.i4.s 16
IL_004a: call ""void System.Console.WriteLine(int)""
IL_004f: ret
}
");
}
[Fact]
public void SizeOfNonConstant()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(sizeof(S));
Console.WriteLine(sizeof(Outer.Inner));
Console.WriteLine(sizeof(int*));
Console.WriteLine(sizeof(void*));
}
}
struct S
{
public byte b;
}
class Outer
{
public struct Inner
{
public char c;
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
1
2
4
4
".Trim();
}
else
{
expectedOutput = @"
1
2
8
8
".Trim();
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 45 (0x2d)
.maxstack 1
IL_0000: sizeof ""S""
IL_0006: call ""void System.Console.WriteLine(int)""
IL_000b: sizeof ""Outer.Inner""
IL_0011: call ""void System.Console.WriteLine(int)""
IL_0016: sizeof ""int*""
IL_001c: call ""void System.Console.WriteLine(int)""
IL_0021: sizeof ""void*""
IL_0027: call ""void System.Console.WriteLine(int)""
IL_002c: ret
}
");
}
[Fact]
public void SizeOfEnum()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(sizeof(E1));
Console.WriteLine(sizeof(E2));
Console.WriteLine(sizeof(E3));
}
}
enum E1 { A }
enum E2 : byte { A }
enum E3 : long { A }
";
var expectedOutput = @"
4
1
8
".Trim();
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes).VerifyIL("C.Main", @"
{
// Code size 19 (0x13)
.maxstack 1
IL_0000: ldc.i4.4
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ldc.i4.1
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ldc.i4.8
IL_000d: call ""void System.Console.WriteLine(int)""
IL_0012: ret
}
");
}
#endregion sizeof tests
#region Pointer arithmetic tests
[Fact]
public void NumericAdditionChecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S s = new S();
S* p = &s;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul.ovf
IL_0014: add.ovf.un
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul.ovf
IL_001f: conv.i
IL_0020: add.ovf.un
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul.ovf
IL_002b: conv.i
IL_002c: add.ovf.un
IL_002d: ldc.i4.5
IL_002e: conv.i8
IL_002f: sizeof ""S""
IL_0035: conv.ovf.u8
IL_0036: mul.ovf.un
IL_0037: conv.u
IL_0038: add.ovf.un
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericAdditionUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
unchecked
{
S s = new S();
S* p = &s;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul
IL_0014: add
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul
IL_001f: conv.i
IL_0020: add
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul
IL_002b: conv.i
IL_002c: add
IL_002d: pop
IL_002e: ldc.i4.5
IL_002f: conv.i8
IL_0030: sizeof ""S""
IL_0036: conv.i8
IL_0037: mul
IL_0038: conv.u
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericSubtractionChecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S s = new S();
S* p = &s;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul.ovf
IL_0014: sub.ovf.un
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul.ovf
IL_001f: conv.i
IL_0020: sub.ovf.un
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul.ovf
IL_002b: conv.i
IL_002c: sub.ovf.un
IL_002d: ldc.i4.5
IL_002e: conv.i8
IL_002f: sizeof ""S""
IL_0035: conv.ovf.u8
IL_0036: mul.ovf.un
IL_0037: conv.u
IL_0038: sub.ovf.un
IL_0039: pop
IL_003a: ret
}
");
}
[Fact]
public void NumericSubtractionUnchecked()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
unchecked
{
S s = new S();
S* p = &s;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
}
}
}
";
// Dev10 has conv.u after IL_000d and conv.i8 in place of conv.u8 at IL_0017.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S V_0) //s
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: conv.u
IL_000b: ldc.i4.2
IL_000c: conv.i
IL_000d: sizeof ""S""
IL_0013: mul
IL_0014: sub
IL_0015: ldc.i4.3
IL_0016: conv.u8
IL_0017: sizeof ""S""
IL_001d: conv.i8
IL_001e: mul
IL_001f: conv.i
IL_0020: sub
IL_0021: ldc.i4.4
IL_0022: conv.i8
IL_0023: sizeof ""S""
IL_0029: conv.i8
IL_002a: mul
IL_002b: conv.i
IL_002c: sub
IL_002d: pop
IL_002e: ldc.i4.5
IL_002f: conv.i8
IL_0030: sizeof ""S""
IL_0036: conv.i8
IL_0037: mul
IL_0038: conv.u
IL_0039: pop
IL_003a: ret
}
");
}
[WorkItem(546750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546750")]
[Fact]
public void NumericAdditionUnchecked_SizeOne()
{
var text = @"
using System;
unsafe class C
{
void Test(int i, uint u, long l, ulong ul)
{
unchecked
{
byte b = 3;
byte* p = &b;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
p = p + i;
p = p + u;
p = p + l;
p = p + ul;
}
}
}
";
// NOTE: even when not optimized.
// NOTE: additional conversions applied to constants of type int and uint.
CompileAndVerify(text, options: TestOptions.UnsafeDebugDll, verify: Verification.Fails).VerifyIL("C.Test", @"
{
// Code size 50 (0x32)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: add
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: add
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: add
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: add
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: add
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: ldarg.2
IL_0022: conv.u
IL_0023: add
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: ldarg.3
IL_0027: conv.i
IL_0028: add
IL_0029: stloc.1
IL_002a: ldloc.1
IL_002b: ldarg.s V_4
IL_002d: conv.u
IL_002e: add
IL_002f: stloc.1
IL_0030: nop
IL_0031: ret
}
");
}
[WorkItem(18871, "https://github.com/dotnet/roslyn/issues/18871")]
[WorkItem(546750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546750")]
[Fact]
public void NumericAdditionChecked_SizeOne()
{
var text = @"
using System;
unsafe class C
{
void Test(int i, uint u, long l, ulong ul)
{
checked
{
byte b = 3;
byte* p = &b;
p = p + 2;
p = p + 3u;
p = p + 4l;
p = p + 5ul;
p = p + i;
p = p + u;
p = p + l;
p = p + ul;
p = p + (-2);
}
}
void Test1(int i, uint u, long l, ulong ul)
{
checked
{
byte b = 3;
byte* p = &b;
p = p - 2;
p = p - 3u;
p = p - 4l;
p = p - 5ul;
p = p - i;
p = p - u;
p = p - l;
p = p - ul;
p = p - (-1);
}
}
}
";
// NOTE: even when not optimized.
// NOTE: additional conversions applied to constants of type int and uint.
// NOTE: identical to unchecked except "add" becomes "add.ovf.un".
var comp = CompileAndVerify(text, options: TestOptions.UnsafeDebugDll, verify: Verification.Fails);
comp.VerifyIL("C.Test", @"
{
// Code size 57 (0x39)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: add.ovf.un
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: add.ovf.un
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: add.ovf.un
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: add.ovf.un
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: conv.i
IL_001f: add.ovf.un
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.2
IL_0023: conv.u
IL_0024: add.ovf.un
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: add.ovf.un
IL_002a: stloc.1
IL_002b: ldloc.1
IL_002c: ldarg.s V_4
IL_002e: conv.u
IL_002f: add.ovf.un
IL_0030: stloc.1
IL_0031: ldloc.1
IL_0032: ldc.i4.s -2
IL_0034: conv.i
IL_0035: add.ovf.un
IL_0036: stloc.1
IL_0037: nop
IL_0038: ret
}");
comp.VerifyIL("C.Test1", @"
{
// Code size 56 (0x38)
.maxstack 2
.locals init (byte V_0, //b
byte* V_1) //p
IL_0000: nop
IL_0001: nop
IL_0002: ldc.i4.3
IL_0003: stloc.0
IL_0004: ldloca.s V_0
IL_0006: conv.u
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldc.i4.2
IL_000a: sub.ovf.un
IL_000b: stloc.1
IL_000c: ldloc.1
IL_000d: ldc.i4.3
IL_000e: sub.ovf.un
IL_000f: stloc.1
IL_0010: ldloc.1
IL_0011: ldc.i4.4
IL_0012: conv.i8
IL_0013: conv.i
IL_0014: sub.ovf.un
IL_0015: stloc.1
IL_0016: ldloc.1
IL_0017: ldc.i4.5
IL_0018: conv.i8
IL_0019: conv.u
IL_001a: sub.ovf.un
IL_001b: stloc.1
IL_001c: ldloc.1
IL_001d: ldarg.1
IL_001e: conv.i
IL_001f: sub.ovf.un
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldarg.2
IL_0023: conv.u
IL_0024: sub.ovf.un
IL_0025: stloc.1
IL_0026: ldloc.1
IL_0027: ldarg.3
IL_0028: conv.i
IL_0029: sub.ovf.un
IL_002a: stloc.1
IL_002b: ldloc.1
IL_002c: ldarg.s V_4
IL_002e: conv.u
IL_002f: sub.ovf.un
IL_0030: stloc.1
IL_0031: ldloc.1
IL_0032: ldc.i4.m1
IL_0033: conv.i
IL_0034: sub.ovf.un
IL_0035: stloc.1
IL_0036: nop
IL_0037: ret
}");
}
[Fact]
public void CheckedSignExtend()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
byte* ptr1 = default(byte*);
ptr1 = (byte*)2;
checked
{
// should not overflow regardless of 32/64 bit
ptr1 = ptr1 + 2147483649;
}
Console.WriteLine((long)ptr1);
byte* ptr = (byte*)2;
try
{
checked
{
int i = -1;
// should overflow regardless of 32/64 bit
ptr = ptr + i;
}
Console.WriteLine((long)ptr);
}
catch (OverflowException)
{
Console.WriteLine(""overflow"");
Console.WriteLine((long)ptr);
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2147483651
overflow
2", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 67 (0x43)
.maxstack 2
.locals init (byte* V_0, //ptr1
byte* V_1, //ptr
int V_2) //i
IL_0000: ldloca.s V_0
IL_0002: initobj ""byte*""
IL_0008: ldc.i4.2
IL_0009: conv.i
IL_000a: stloc.0
IL_000b: ldloc.0
IL_000c: ldc.i4 0x80000001
IL_0011: conv.u
IL_0012: add.ovf.un
IL_0013: stloc.0
IL_0014: ldloc.0
IL_0015: conv.u8
IL_0016: call ""void System.Console.WriteLine(long)""
IL_001b: ldc.i4.2
IL_001c: conv.i
IL_001d: stloc.1
.try
{
IL_001e: ldc.i4.m1
IL_001f: stloc.2
IL_0020: ldloc.1
IL_0021: ldloc.2
IL_0022: conv.i
IL_0023: add.ovf.un
IL_0024: stloc.1
IL_0025: ldloc.1
IL_0026: conv.u8
IL_0027: call ""void System.Console.WriteLine(long)""
IL_002c: leave.s IL_0042
}
catch System.OverflowException
{
IL_002e: pop
IL_002f: ldstr ""overflow""
IL_0034: call ""void System.Console.WriteLine(string)""
IL_0039: ldloc.1
IL_003a: conv.u8
IL_003b: call ""void System.Console.WriteLine(long)""
IL_0040: leave.s IL_0042
}
IL_0042: ret
}
");
}
[Fact]
public void Increment()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)0;
checked
{
p++;
}
checked
{
++p;
}
unchecked
{
p++;
}
unchecked
{
++p;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "4", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (S* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: add.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: sizeof ""S""
IL_0013: add.ovf.un
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: sizeof ""S""
IL_001c: add
IL_001d: stloc.0
IL_001e: ldloc.0
IL_001f: sizeof ""S""
IL_0025: add
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: conv.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: ret
}
");
}
[Fact]
public void Decrement()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
checked
{
p--;
}
checked
{
--p;
}
unchecked
{
p--;
}
unchecked
{
--p;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "4", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (S* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: sub.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: sizeof ""S""
IL_0013: sub.ovf.un
IL_0014: stloc.0
IL_0015: ldloc.0
IL_0016: sizeof ""S""
IL_001c: sub
IL_001d: stloc.0
IL_001e: ldloc.0
IL_001f: sizeof ""S""
IL_0025: sub
IL_0026: stloc.0
IL_0027: ldloc.0
IL_0028: conv.i4
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: ret
}
");
}
[Fact]
public void IncrementProperty()
{
var text = @"
using System;
unsafe struct S
{
S* P { get; set; }
S* this[int x] { get { return P; } set { P = value; } }
static void Main()
{
S s = new S();
s.P++;
--s[GetIndex()];
Console.Write((int)s.P);
}
static int GetIndex()
{
Console.Write(""I"");
return 1;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "I0", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 74 (0x4a)
.maxstack 3
.locals init (S V_0, //s
S* V_1,
int V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: dup
IL_000b: call ""readonly S* S.P.get""
IL_0010: stloc.1
IL_0011: ldloc.1
IL_0012: sizeof ""S""
IL_0018: add
IL_0019: call ""void S.P.set""
IL_001e: ldloca.s V_0
IL_0020: call ""int S.GetIndex()""
IL_0025: stloc.2
IL_0026: dup
IL_0027: ldloc.2
IL_0028: call ""S* S.this[int].get""
IL_002d: sizeof ""S""
IL_0033: sub
IL_0034: stloc.1
IL_0035: ldloc.2
IL_0036: ldloc.1
IL_0037: call ""void S.this[int].set""
IL_003c: ldloca.s V_0
IL_003e: call ""readonly S* S.P.get""
IL_0043: conv.i4
IL_0044: call ""void System.Console.Write(int)""
IL_0049: ret
}
");
}
[Fact]
public void CompoundAssignment()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
checked
{
p += 1;
p += 2U;
p -= 1L;
p -= 2UL;
}
unchecked
{
p += 1;
p += 2U;
p -= 1L;
p -= 2UL;
}
Console.WriteLine((int)p);
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "8", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 103 (0x67)
.maxstack 3
.locals init (S* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: sizeof ""S""
IL_000a: add.ovf.un
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: ldc.i4.2
IL_000e: conv.u8
IL_000f: sizeof ""S""
IL_0015: conv.i8
IL_0016: mul.ovf
IL_0017: conv.i
IL_0018: add.ovf.un
IL_0019: stloc.0
IL_001a: ldloc.0
IL_001b: sizeof ""S""
IL_0021: sub.ovf.un
IL_0022: stloc.0
IL_0023: ldloc.0
IL_0024: ldc.i4.2
IL_0025: conv.i8
IL_0026: sizeof ""S""
IL_002c: conv.ovf.u8
IL_002d: mul.ovf.un
IL_002e: conv.u
IL_002f: sub.ovf.un
IL_0030: stloc.0
IL_0031: ldloc.0
IL_0032: sizeof ""S""
IL_0038: add
IL_0039: stloc.0
IL_003a: ldloc.0
IL_003b: ldc.i4.2
IL_003c: conv.u8
IL_003d: sizeof ""S""
IL_0043: conv.i8
IL_0044: mul
IL_0045: conv.i
IL_0046: add
IL_0047: stloc.0
IL_0048: ldloc.0
IL_0049: sizeof ""S""
IL_004f: sub
IL_0050: stloc.0
IL_0051: ldloc.0
IL_0052: ldc.i4.2
IL_0053: conv.i8
IL_0054: sizeof ""S""
IL_005a: conv.i8
IL_005b: mul
IL_005c: conv.u
IL_005d: sub
IL_005e: stloc.0
IL_005f: ldloc.0
IL_0060: conv.i4
IL_0061: call ""void System.Console.WriteLine(int)""
IL_0066: ret
}
");
}
[Fact]
public void CompoundAssignProperty()
{
var text = @"
using System;
unsafe struct S
{
S* P { get; set; }
S* this[int x] { get { return P; } set { P = value; } }
static void Main()
{
S s = new S();
s.P += 3;
s[GetIndex()] -= 2;
Console.Write((int)s.P);
}
static int GetIndex()
{
Console.Write(""I"");
return 1;
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"I4";
}
else
{
expectedOutput = @"I8";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 78 (0x4e)
.maxstack 5
.locals init (S V_0, //s
S& V_1,
int V_2)
IL_0000: ldloca.s V_0
IL_0002: initobj ""S""
IL_0008: ldloca.s V_0
IL_000a: dup
IL_000b: call ""readonly S* S.P.get""
IL_0010: ldc.i4.3
IL_0011: conv.i
IL_0012: sizeof ""S""
IL_0018: mul
IL_0019: add
IL_001a: call ""void S.P.set""
IL_001f: ldloca.s V_0
IL_0021: stloc.1
IL_0022: call ""int S.GetIndex()""
IL_0027: stloc.2
IL_0028: ldloc.1
IL_0029: ldloc.2
IL_002a: ldloc.1
IL_002b: ldloc.2
IL_002c: call ""S* S.this[int].get""
IL_0031: ldc.i4.2
IL_0032: conv.i
IL_0033: sizeof ""S""
IL_0039: mul
IL_003a: sub
IL_003b: call ""void S.this[int].set""
IL_0040: ldloca.s V_0
IL_0042: call ""readonly S* S.P.get""
IL_0047: conv.i4
IL_0048: call ""void System.Console.Write(int)""
IL_004d: ret
}
");
}
[Fact]
public void PointerSubtraction_EmptyStruct()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)8;
S* q = (S*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "44", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: sizeof ""S""
IL_000f: div
IL_0010: conv.i8
IL_0011: call ""void System.Console.Write(long)""
IL_0016: ldloc.0
IL_0017: ldloc.1
IL_0018: sub
IL_0019: sizeof ""S""
IL_001f: div
IL_0020: conv.i8
IL_0021: call ""void System.Console.Write(long)""
IL_0026: ret
}
");
}
[Fact]
public void PointerSubtraction_NonEmptyStruct()
{
var text = @"
using System;
unsafe struct S
{
int x; //non-empty struct
static void Main()
{
S* p = (S*)8;
S* q = (S*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "11", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 39 (0x27)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: sizeof ""S""
IL_000f: div
IL_0010: conv.i8
IL_0011: call ""void System.Console.Write(long)""
IL_0016: ldloc.0
IL_0017: ldloc.1
IL_0018: sub
IL_0019: sizeof ""S""
IL_001f: div
IL_0020: conv.i8
IL_0021: call ""void System.Console.Write(long)""
IL_0026: ret
}
");
}
[Fact]
public void PointerSubtraction_ConstantSize()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
int* p = (int*)8; //size is known at compile-time
int* q = (int*)4;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "11", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 29 (0x1d)
.maxstack 2
.locals init (int* V_0, //p
int* V_1) //q
IL_0000: ldc.i4.8
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.4
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: sub
IL_0009: ldc.i4.4
IL_000a: div
IL_000b: conv.i8
IL_000c: call ""void System.Console.Write(long)""
IL_0011: ldloc.0
IL_0012: ldloc.1
IL_0013: sub
IL_0014: ldc.i4.4
IL_0015: div
IL_0016: conv.i8
IL_0017: call ""void System.Console.Write(long)""
IL_001c: ret
}
");
}
[Fact]
public void PointerSubtraction_IntegerDivision()
{
var text = @"
using System;
unsafe struct S
{
int x; //size = 4
static void Main()
{
S* p1 = (S*)7; //size is known at compile-time
S* p2 = (S*)9; //size is known at compile-time
S* q = (S*)4;
checked
{
Console.Write(p1 - q);
}
unchecked
{
Console.Write(p2 - q);
}
}
}
";
// NOTE: don't use checked subtraction or division in either case (matches dev10).
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "01", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 43 (0x2b)
.maxstack 2
.locals init (S* V_0, //p1
S* V_1, //p2
S* V_2) //q
IL_0000: ldc.i4.7
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.s 9
IL_0005: conv.i
IL_0006: stloc.1
IL_0007: ldc.i4.4
IL_0008: conv.i
IL_0009: stloc.2
IL_000a: ldloc.0
IL_000b: ldloc.2
IL_000c: sub
IL_000d: sizeof ""S""
IL_0013: div
IL_0014: conv.i8
IL_0015: call ""void System.Console.Write(long)""
IL_001a: ldloc.1
IL_001b: ldloc.2
IL_001c: sub
IL_001d: sizeof ""S""
IL_0023: div
IL_0024: conv.i8
IL_0025: call ""void System.Console.Write(long)""
IL_002a: ret
}
");
}
[WorkItem(544155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544155")]
[Fact]
public void SubtractPointerTypes()
{
var text = @"
using System;
class PointerArithmetic
{
static unsafe void Main()
{
short ia1 = 10;
short* ptr = &ia1;
short* newPtr;
newPtr = ptr - 2;
Console.WriteLine((int)(ptr - newPtr));
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "2", verify: Verification.Fails);
}
#endregion Pointer arithmetic tests
#region Checked pointer arithmetic overflow tests
// 0 - operation name (e.g. "Add")
// 1 - pointed at type name (e.g. "S")
// 2 - operator (e.g. "+")
// 3 - checked/unchecked
private const string CheckedNumericHelperTemplate = @"
unsafe static class Helper
{{
public static void {0}Int({1}* p, int num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}Int: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}Int: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}UInt({1}* p, uint num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}UInt: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}UInt: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}Long({1}* p, long num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}Long: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}Long: Exception at {{0}}"", description);
}}
}}
}}
public static void {0}ULong({1}* p, ulong num, string description)
{{
{3}
{{
try
{{
p = p {2} num;
Console.WriteLine(""{0}ULong: No exception at {{0}} (value = {{1}})"",
description, (ulong)p);
}}
catch (OverflowException)
{{
Console.WriteLine(""{0}ULong: Exception at {{0}}"", description);
}}
}}
}}
}}
";
private const string SizedStructs = @"
//sizeof SXX is 2 ^ XX
struct S00 { }
struct S01 { S00 a, b; }
struct S02 { S01 a, b; }
struct S03 { S02 a, b; }
struct S04 { S03 a, b; }
struct S05 { S04 a, b; }
struct S06 { S05 a, b; }
struct S07 { S06 a, b; }
struct S08 { S07 a, b; }
struct S09 { S08 a, b; }
struct S10 { S09 a, b; }
struct S11 { S10 a, b; }
struct S12 { S11 a, b; }
struct S13 { S12 a, b; }
struct S14 { S13 a, b; }
struct S15 { S14 a, b; }
struct S16 { S15 a, b; }
struct S17 { S16 a, b; }
struct S18 { S17 a, b; }
struct S19 { S18 a, b; }
struct S20 { S19 a, b; }
struct S21 { S20 a, b; }
struct S22 { S21 a, b; }
struct S23 { S22 a, b; }
struct S24 { S23 a, b; }
struct S25 { S24 a, b; }
struct S26 { S25 a, b; }
struct S27 { S26 a, b; }
//struct S28 { S27 a, b; } //Can't load type
//struct S29 { S28 a, b; } //Can't load type
//struct S30 { S29 a, b; } //Can't load type
//struct S31 { S30 a, b; } //Can't load type
";
// 0 - pointed-at type
private const string PositiveNumericAdditionCasesTemplate = @"
Helper.AddInt(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddInt(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddInt(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddInt(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
//Helper.AddInt(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
//Helper.AddInt(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddInt(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddInt(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
//Helper.AddInt(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
//Helper.AddInt(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddInt(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddInt(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddInt(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddInt(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddInt(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddInt(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddUInt(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddUInt(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddUInt(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddUInt(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddUInt(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddUInt(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddUInt(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddUInt(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
//Helper.AddUInt(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
//Helper.AddUInt(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddUInt(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddUInt(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddUInt(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddUInt(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddUInt(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddUInt(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddLong(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddLong(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddLong(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddLong(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddLong(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddLong(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddLong(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddLong(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
Helper.AddLong(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
Helper.AddLong(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddLong(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddLong(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
//Helper.AddLong(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
//Helper.AddLong(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddLong(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddLong(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
Console.WriteLine();
Helper.AddULong(({0}*)0, int.MaxValue, ""0 + int.MaxValue"");
Helper.AddULong(({0}*)1, int.MaxValue, ""1 + int.MaxValue"");
Helper.AddULong(({0}*)int.MaxValue, 0, ""int.MaxValue + 0"");
Helper.AddULong(({0}*)int.MaxValue, 1, ""int.MaxValue + 1"");
Helper.AddULong(({0}*)0, uint.MaxValue, ""0 + uint.MaxValue"");
Helper.AddULong(({0}*)1, uint.MaxValue, ""1 + uint.MaxValue"");
Helper.AddULong(({0}*)uint.MaxValue, 0, ""uint.MaxValue + 0"");
Helper.AddULong(({0}*)uint.MaxValue, 1, ""uint.MaxValue + 1"");
Helper.AddULong(({0}*)0, long.MaxValue, ""0 + long.MaxValue"");
Helper.AddULong(({0}*)1, long.MaxValue, ""1 + long.MaxValue"");
//Helper.AddULong(({0}*)long.MaxValue, 0, ""long.MaxValue + 0"");
//Helper.AddULong(({0}*)long.MaxValue, 1, ""long.MaxValue + 1"");
Helper.AddULong(({0}*)0, ulong.MaxValue, ""0 + ulong.MaxValue"");
Helper.AddULong(({0}*)1, ulong.MaxValue, ""1 + ulong.MaxValue"");
//Helper.AddULong(({0}*)ulong.MaxValue, 0, ""ulong.MaxValue + 0"");
//Helper.AddULong(({0}*)ulong.MaxValue, 1, ""ulong.MaxValue + 1"");
";
// 0 - pointed-at type
private const string NegativeNumericAdditionCasesTemplate = @"
Helper.AddInt(({0}*)0, -1, ""0 + (-1)"");
Helper.AddInt(({0}*)0, int.MinValue, ""0 + int.MinValue"");
//Helper.AddInt(({0}*)0, long.MinValue, ""0 + long.MinValue"");
Console.WriteLine();
Helper.AddLong(({0}*)0, -1, ""0 + (-1)"");
Helper.AddLong(({0}*)0, int.MinValue, ""0 + int.MinValue"");
Helper.AddLong(({0}*)0, long.MinValue, ""0 + long.MinValue"");
";
// 0 - pointed-at type
private const string PositiveNumericSubtractionCasesTemplate = @"
Helper.SubInt(({0}*)0, 1, ""0 - 1"");
Helper.SubInt(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
//Helper.SubInt(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
//Helper.SubInt(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubInt(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubUInt(({0}*)0, 1, ""0 - 1"");
Helper.SubUInt(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubUInt(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
//Helper.SubUInt(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubUInt(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubLong(({0}*)0, 1, ""0 - 1"");
Helper.SubLong(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubLong(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
Helper.SubLong(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
//Helper.SubLong(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
Console.WriteLine();
Helper.SubULong(({0}*)0, 1, ""0 - 1"");
Helper.SubULong(({0}*)0, int.MaxValue, ""0 - int.MaxValue"");
Helper.SubULong(({0}*)0, uint.MaxValue, ""0 - uint.MaxValue"");
Helper.SubULong(({0}*)0, long.MaxValue, ""0 - long.MaxValue"");
Helper.SubULong(({0}*)0, ulong.MaxValue, ""0 - ulong.MaxValue"");
";
// 0 - pointed-at type
private const string NegativeNumericSubtractionCasesTemplate = @"
Helper.SubInt(({0}*)0, -1, ""0 - -1"");
Helper.SubInt(({0}*)0, int.MinValue, ""0 - int.MinValue"");
Helper.SubInt(({0}*)0, -1 * int.MaxValue, ""0 - -int.MaxValue"");
Console.WriteLine();
Helper.SubLong(({0}*)0, -1L, ""0 - -1"");
Helper.SubLong(({0}*)0, int.MinValue, ""0 - int.MinValue"");
Helper.SubLong(({0}*)0, long.MinValue, ""0 - long.MinValue"");
Helper.SubLong(({0}*)0, -1L * int.MaxValue, ""0 - -int.MaxValue"");
Helper.SubLong(({0}*)0, -1L * uint.MaxValue, ""0 - -uint.MaxValue"");
Helper.SubLong(({0}*)0, -1L * long.MaxValue, ""0 - -long.MaxValue"");
Helper.SubLong(({0}*)0, -1L * long.MaxValue, ""0 - -ulong.MaxValue"");
Helper.SubLong(({0}*)0, -1L * int.MinValue, ""0 - -int.MinValue"");
//Helper.SubLong(({0}*)0, -1L * long.MinValue, ""0 - -long.MinValue"");
";
private static string MakeNumericOverflowTest(string casesTemplate, string pointedAtType, string operationName, string @operator, string checkedness)
{
const string mainClassTemplate = @"
using System;
unsafe class C
{{
static void Main()
{{
{0}
{{
{1}
}}
}}
}}
{2}
{3}
";
return string.Format(mainClassTemplate,
checkedness,
string.Format(casesTemplate, pointedAtType),
string.Format(CheckedNumericHelperTemplate, operationName, pointedAtType, @operator, checkedness),
SizedStructs);
}
// Positive numbers, size = 1
[Fact]
public void CheckedNumericAdditionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S00", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: Exception at uint.MaxValue + 1
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: Exception at 1 + uint.MaxValue
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: Exception at 1 + uint.MaxValue
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + long.MaxValue (value = 4294967295)
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: Exception at 1 + uint.MaxValue
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: Exception at uint.MaxValue + 1
AddULong: No exception at 0 + long.MaxValue (value = 4294967295)
AddULong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967295)
AddULong: Exception at 1 + ulong.MaxValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967296)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddLong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddULong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddULong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551615)
AddULong: Exception at 1 + ulong.MaxValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void CheckedNumericAdditionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S02", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: Exception at 0 + int.MaxValue
AddInt: Exception at 1 + int.MaxValue
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: Exception at uint.MaxValue + 1
AddUInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967293)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: Exception at uint.MaxValue + 1
AddLong: No exception at 0 + int.MaxValue (value = 4294967292)
AddLong: No exception at 1 + int.MaxValue (value = 4294967293)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: Exception at uint.MaxValue + 1
AddLong: Exception at 0 + long.MaxValue
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 4294967292)
AddULong: No exception at 1 + int.MaxValue (value = 4294967293)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: Exception at uint.MaxValue + 1
AddULong: Exception at 0 + long.MaxValue
AddULong: Exception at 1 + long.MaxValue
AddULong: Exception at 0 + ulong.MaxValue
AddULong: Exception at 1 + ulong.MaxValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddUInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddUInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 17179869180)
AddUInt: No exception at 1 + uint.MaxValue (value = 17179869181)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + int.MaxValue (value = 8589934588)
AddLong: No exception at 1 + int.MaxValue (value = 8589934589)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddLong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: Exception at 0 + long.MaxValue
AddLong: Exception at 1 + long.MaxValue
AddULong: No exception at 0 + int.MaxValue (value = 8589934588)
AddULong: No exception at 1 + int.MaxValue (value = 8589934589)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddULong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddULong: Exception at 0 + long.MaxValue
AddULong: Exception at 1 + long.MaxValue
AddULong: Exception at 0 + ulong.MaxValue
AddULong: Exception at 1 + ulong.MaxValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void CheckedNumericAdditionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S00", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967295)
AddInt: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + (-1) (value = 4294967295)
AddLong: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551615)
AddInt: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + (-1) (value = 18446744073709551615)
AddLong: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + long.MinValue (value = 9223372036854775808)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: expectedOutput);
}
// Negative numbers, size = 4
[Fact]
public void CheckedNumericAdditionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S02", "Add", "+", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967292)
AddInt: Exception at 0 + int.MinValue
AddLong: No exception at 0 + (-1) (value = 4294967292)
AddLong: No exception at 0 + int.MinValue (value = 0)
AddLong: Exception at 0 + long.MinValue
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551612)
AddInt: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + (-1) (value = 18446744073709551612)
AddLong: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: Exception at 0 + long.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 1
[Fact]
public void CheckedNumericSubtractionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S00", "Sub", "-", "checked");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
SubInt: Exception at 0 - 1
SubInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - 1
SubUInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - 1
SubLong: Exception at 0 - int.MaxValue
SubLong: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - 1
SubULong: Exception at 0 - int.MaxValue
SubULong: Exception at 0 - uint.MaxValue
SubULong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - ulong.MaxValue
");
}
// Positive numbers, size = 4
[Fact]
public void CheckedNumericSubtractionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S02", "Sub", "-", "checked");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
SubInt: Exception at 0 - 1
SubInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - 1
SubUInt: Exception at 0 - int.MaxValue
SubUInt: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - 1
SubLong: Exception at 0 - int.MaxValue
SubLong: Exception at 0 - uint.MaxValue
SubLong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - 1
SubULong: Exception at 0 - int.MaxValue
SubULong: Exception at 0 - uint.MaxValue
SubULong: Exception at 0 - long.MaxValue
SubULong: Exception at 0 - ulong.MaxValue
");
}
// Negative numbers, size = 1
[Fact]
public void CheckedNumericSubtractionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S00", "Sub", "-", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
else
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void CheckedNumericSubtractionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S02", "Sub", "-", "checked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: No exception at 0 - int.MinValue (value = 0)
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: No exception at 0 - -int.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
SubInt: Exception at 0 - -1
SubInt: Exception at 0 - int.MinValue
SubInt: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -1
SubLong: Exception at 0 - int.MinValue
SubLong: Exception at 0 - long.MinValue
SubLong: Exception at 0 - -int.MaxValue
SubLong: Exception at 0 - -uint.MaxValue
SubLong: Exception at 0 - -long.MaxValue
SubLong: Exception at 0 - -ulong.MaxValue
SubLong: Exception at 0 - -int.MinValue
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void CheckedNumericSubtractionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S* p;
p = (S*)0 + (-1);
System.Console.WriteLine(""No exception from addition"");
try
{
p = (S*)0 - 1;
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception from subtraction"");
}
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Passes, expectedOutput: @"
No exception from addition
Exception from subtraction
");
}
[Fact]
public void CheckedNumericAdditionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
checked
{
S* p;
p = (S*)1 + int.MaxValue;
System.Console.WriteLine(""No exception for pointer + int"");
try
{
p = int.MaxValue + (S*)1;
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception for int + pointer"");
}
}
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
No exception for pointer + int
Exception for int + pointer
";
}
else
{
expectedOutput = @"
No exception for pointer + int
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Passes);
}
[Fact]
public void CheckedPointerSubtractionQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)uint.MinValue;
S* q = (S*)uint.MaxValue;
checked
{
Console.Write(p - q);
}
unchecked
{
Console.Write(p - q);
}
}
}
";
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"11";
}
else
{
expectedOutput = @"-4294967295-4294967295";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void CheckedPointerElementAccessQuirk()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
fixed (byte* p = new byte[2])
{
p[0] = 12;
// Take a pointer to the second element of the array.
byte* q = p + 1;
// Compute the offset that will wrap around all the way to the preceding byte of memory.
// We do this so that we can overflow, but still end up in valid memory.
ulong offset = sizeof(IntPtr) == sizeof(int) ? uint.MaxValue : ulong.MaxValue;
checked
{
Console.WriteLine(q[offset]);
System.Console.WriteLine(""No exception for element access"");
try
{
Console.WriteLine(*(q + offset));
}
catch (OverflowException)
{
System.Console.WriteLine(""Exception for add-then-dereference"");
}
}
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
12
No exception for element access
Exception for add-then-dereference
");
}
#endregion Checked pointer arithmetic overflow tests
#region Unchecked pointer arithmetic overflow tests
// Positive numbers, size = 1
[Fact]
public void UncheckedNumericAdditionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S00", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 0)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 0)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 0)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 0)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 0)
AddLong: No exception at 0 + long.MaxValue (value = 4294967295)
AddLong: No exception at 1 + long.MaxValue (value = 0)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 0)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 0)
AddULong: No exception at 0 + long.MaxValue (value = 4294967295)
AddULong: No exception at 1 + long.MaxValue (value = 0)
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967295)
AddULong: No exception at 1 + ulong.MaxValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddUInt: No exception at 0 + int.MaxValue (value = 2147483647)
AddUInt: No exception at 1 + int.MaxValue (value = 2147483648)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483648)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967295)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967296)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + int.MaxValue (value = 2147483647)
AddLong: No exception at 1 + int.MaxValue (value = 2147483648)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483648)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddLong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddLong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + int.MaxValue (value = 2147483647)
AddULong: No exception at 1 + int.MaxValue (value = 2147483648)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483648)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967295)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967296)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967296)
AddULong: No exception at 0 + long.MaxValue (value = 9223372036854775807)
AddULong: No exception at 1 + long.MaxValue (value = 9223372036854775808)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551615)
AddULong: No exception at 1 + ulong.MaxValue (value = 0)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void UncheckedNumericAdditionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericAdditionCasesTemplate, "S02", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 3)
AddUInt: No exception at 0 + int.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + int.MaxValue (value = 4294967293)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 4294967292)
AddUInt: No exception at 1 + uint.MaxValue (value = 4294967293)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 3)
AddLong: No exception at 0 + int.MaxValue (value = 4294967292)
AddLong: No exception at 1 + int.MaxValue (value = 4294967293)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddLong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 3)
AddLong: No exception at 0 + long.MaxValue (value = 4294967292)
AddLong: No exception at 1 + long.MaxValue (value = 4294967293)
AddULong: No exception at 0 + int.MaxValue (value = 4294967292)
AddULong: No exception at 1 + int.MaxValue (value = 4294967293)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 4294967292)
AddULong: No exception at 1 + uint.MaxValue (value = 4294967293)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 3)
AddULong: No exception at 0 + long.MaxValue (value = 4294967292)
AddULong: No exception at 1 + long.MaxValue (value = 4294967293)
AddULong: No exception at 0 + ulong.MaxValue (value = 4294967292)
AddULong: No exception at 1 + ulong.MaxValue (value = 4294967293)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddUInt: No exception at 0 + int.MaxValue (value = 8589934588)
AddUInt: No exception at 1 + int.MaxValue (value = 8589934589)
AddUInt: No exception at int.MaxValue + 0 (value = 2147483647)
AddUInt: No exception at int.MaxValue + 1 (value = 2147483651)
AddUInt: No exception at 0 + uint.MaxValue (value = 17179869180)
AddUInt: No exception at 1 + uint.MaxValue (value = 17179869181)
AddUInt: No exception at uint.MaxValue + 0 (value = 4294967295)
AddUInt: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + int.MaxValue (value = 8589934588)
AddLong: No exception at 1 + int.MaxValue (value = 8589934589)
AddLong: No exception at int.MaxValue + 0 (value = 2147483647)
AddLong: No exception at int.MaxValue + 1 (value = 2147483651)
AddLong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddLong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddLong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddLong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddLong: No exception at 0 + long.MaxValue (value = 18446744073709551612)
AddLong: No exception at 1 + long.MaxValue (value = 18446744073709551613)
AddULong: No exception at 0 + int.MaxValue (value = 8589934588)
AddULong: No exception at 1 + int.MaxValue (value = 8589934589)
AddULong: No exception at int.MaxValue + 0 (value = 2147483647)
AddULong: No exception at int.MaxValue + 1 (value = 2147483651)
AddULong: No exception at 0 + uint.MaxValue (value = 17179869180)
AddULong: No exception at 1 + uint.MaxValue (value = 17179869181)
AddULong: No exception at uint.MaxValue + 0 (value = 4294967295)
AddULong: No exception at uint.MaxValue + 1 (value = 4294967299)
AddULong: No exception at 0 + long.MaxValue (value = 18446744073709551612)
AddULong: No exception at 1 + long.MaxValue (value = 18446744073709551613)
AddULong: No exception at 0 + ulong.MaxValue (value = 18446744073709551612)
AddULong: No exception at 1 + ulong.MaxValue (value = 18446744073709551613)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void UncheckedNumericAdditionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S00", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967295)
AddInt: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + (-1) (value = 4294967295)
AddLong: No exception at 0 + int.MinValue (value = 2147483648)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551615)
AddInt: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + (-1) (value = 18446744073709551615)
AddLong: No exception at 0 + int.MinValue (value = 18446744071562067968)
AddLong: No exception at 0 + long.MinValue (value = 9223372036854775808)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void UncheckedNumericAdditionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericAdditionCasesTemplate, "S02", "Add", "+", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 4294967292)
AddInt: No exception at 0 + int.MinValue (value = 0)
AddLong: No exception at 0 + (-1) (value = 4294967292)
AddLong: No exception at 0 + int.MinValue (value = 0)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
else
{
expectedOutput = @"
AddInt: No exception at 0 + (-1) (value = 18446744073709551612)
AddInt: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + (-1) (value = 18446744073709551612)
AddLong: No exception at 0 + int.MinValue (value = 18446744065119617024)
AddLong: No exception at 0 + long.MinValue (value = 0)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 1
[Fact]
public void UncheckedNumericSubtractionOverflow1()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S00", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 4294967295)
SubInt: No exception at 0 - int.MaxValue (value = 2147483649)
SubUInt: No exception at 0 - 1 (value = 4294967295)
SubUInt: No exception at 0 - int.MaxValue (value = 2147483649)
SubUInt: No exception at 0 - uint.MaxValue (value = 1)
SubLong: No exception at 0 - 1 (value = 4294967295)
SubLong: No exception at 0 - int.MaxValue (value = 2147483649)
SubLong: No exception at 0 - uint.MaxValue (value = 1)
SubLong: No exception at 0 - long.MaxValue (value = 1)
SubULong: No exception at 0 - 1 (value = 4294967295)
SubULong: No exception at 0 - int.MaxValue (value = 2147483649)
SubULong: No exception at 0 - uint.MaxValue (value = 1)
SubULong: No exception at 0 - long.MaxValue (value = 1)
SubULong: No exception at 0 - ulong.MaxValue (value = 1)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 18446744073709551615)
SubInt: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubUInt: No exception at 0 - 1 (value = 18446744073709551615)
SubUInt: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubUInt: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubLong: No exception at 0 - 1 (value = 18446744073709551615)
SubLong: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubLong: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubLong: No exception at 0 - long.MaxValue (value = 9223372036854775809)
SubULong: No exception at 0 - 1 (value = 18446744073709551615)
SubULong: No exception at 0 - int.MaxValue (value = 18446744071562067969)
SubULong: No exception at 0 - uint.MaxValue (value = 18446744069414584321)
SubULong: No exception at 0 - long.MaxValue (value = 9223372036854775809)
SubULong: No exception at 0 - ulong.MaxValue (value = 1)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Positive numbers, size = 4
[Fact]
public void UncheckedNumericSubtractionOverflow2()
{
var text = MakeNumericOverflowTest(PositiveNumericSubtractionCasesTemplate, "S02", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 4294967292)
SubInt: No exception at 0 - int.MaxValue (value = 4)
SubUInt: No exception at 0 - 1 (value = 4294967292)
SubUInt: No exception at 0 - int.MaxValue (value = 4)
SubUInt: No exception at 0 - uint.MaxValue (value = 4)
SubLong: No exception at 0 - 1 (value = 4294967292)
SubLong: No exception at 0 - int.MaxValue (value = 4)
SubLong: No exception at 0 - uint.MaxValue (value = 4)
SubLong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - 1 (value = 4294967292)
SubULong: No exception at 0 - int.MaxValue (value = 4)
SubULong: No exception at 0 - uint.MaxValue (value = 4)
SubULong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - ulong.MaxValue (value = 4)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - 1 (value = 18446744073709551612)
SubInt: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubUInt: No exception at 0 - 1 (value = 18446744073709551612)
SubUInt: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubUInt: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubLong: No exception at 0 - 1 (value = 18446744073709551612)
SubLong: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubLong: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubLong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - 1 (value = 18446744073709551612)
SubULong: No exception at 0 - int.MaxValue (value = 18446744065119617028)
SubULong: No exception at 0 - uint.MaxValue (value = 18446744056529682436)
SubULong: No exception at 0 - long.MaxValue (value = 4)
SubULong: No exception at 0 - ulong.MaxValue (value = 4)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 1
[Fact]
public void UncheckedNumericSubtractionOverflow3()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S00", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 1)
SubInt: No exception at 0 - int.MinValue (value = 2147483648)
SubInt: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -1 (value = 1)
SubLong: No exception at 0 - int.MinValue (value = 2147483648)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -long.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -ulong.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -int.MinValue (value = 2147483648)
";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 1)
SubInt: No exception at 0 - int.MinValue (value = 2147483648)
SubInt: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -1 (value = 1)
SubLong: No exception at 0 - int.MinValue (value = 2147483648)
SubLong: No exception at 0 - long.MinValue (value = 9223372036854775808)
SubLong: No exception at 0 - -int.MaxValue (value = 2147483647)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967295)
SubLong: No exception at 0 - -long.MaxValue (value = 9223372036854775807)
SubLong: No exception at 0 - -ulong.MaxValue (value = 9223372036854775807)
SubLong: No exception at 0 - -int.MinValue (value = 18446744071562067968)
";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
// Negative numbers, size = 4
[Fact]
public void UncheckedNumericSubtractionOverflow4()
{
var text = MakeNumericOverflowTest(NegativeNumericSubtractionCasesTemplate, "S02", "Sub", "-", "unchecked");
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 4)
SubInt: No exception at 0 - int.MinValue (value = 0)
SubInt: No exception at 0 - -int.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -1 (value = 4)
SubLong: No exception at 0 - int.MinValue (value = 0)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -uint.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -long.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -ulong.MaxValue (value = 4294967292)
SubLong: No exception at 0 - -int.MinValue (value = 0)";
}
else
{
expectedOutput = @"
SubInt: No exception at 0 - -1 (value = 4)
SubInt: No exception at 0 - int.MinValue (value = 8589934592)
SubInt: No exception at 0 - -int.MaxValue (value = 8589934588)
SubLong: No exception at 0 - -1 (value = 4)
SubLong: No exception at 0 - int.MinValue (value = 8589934592)
SubLong: No exception at 0 - long.MinValue (value = 0)
SubLong: No exception at 0 - -int.MaxValue (value = 8589934588)
SubLong: No exception at 0 - -uint.MaxValue (value = 17179869180)
SubLong: No exception at 0 - -long.MaxValue (value = 18446744073709551612)
SubLong: No exception at 0 - -ulong.MaxValue (value = 18446744073709551612)
SubLong: No exception at 0 - -int.MinValue (value = 18446744065119617024)";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
#endregion Unchecked pointer arithmetic overflow tests
#region Pointer comparison tests
[Fact]
public void PointerComparisonSameType()
{
var text = @"
using System;
unsafe struct S
{
static void Main()
{
S* p = (S*)0;
S* q = (S*)1;
unchecked
{
Write(p == q);
Write(p != q);
Write(p <= q);
Write(p >= q);
Write(p < q);
Write(p > q);
}
checked
{
Write(p == q);
Write(p != q);
Write(p <= q);
Write(p >= q);
Write(p < q);
Write(p > q);
}
}
static void Write(bool b)
{
Console.Write(b ? 1 : 0);
}
}
";
// NOTE: all comparisons unsigned.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "011010011010", verify: Verification.Fails).VerifyIL("S.Main", @"
{
// Code size 133 (0x85)
.maxstack 2
.locals init (S* V_0, //p
S* V_1) //q
IL_0000: ldc.i4.0
IL_0001: conv.i
IL_0002: stloc.0
IL_0003: ldc.i4.1
IL_0004: conv.i
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: ceq
IL_000a: call ""void S.Write(bool)""
IL_000f: ldloc.0
IL_0010: ldloc.1
IL_0011: ceq
IL_0013: ldc.i4.0
IL_0014: ceq
IL_0016: call ""void S.Write(bool)""
IL_001b: ldloc.0
IL_001c: ldloc.1
IL_001d: cgt.un
IL_001f: ldc.i4.0
IL_0020: ceq
IL_0022: call ""void S.Write(bool)""
IL_0027: ldloc.0
IL_0028: ldloc.1
IL_0029: clt.un
IL_002b: ldc.i4.0
IL_002c: ceq
IL_002e: call ""void S.Write(bool)""
IL_0033: ldloc.0
IL_0034: ldloc.1
IL_0035: clt.un
IL_0037: call ""void S.Write(bool)""
IL_003c: ldloc.0
IL_003d: ldloc.1
IL_003e: cgt.un
IL_0040: call ""void S.Write(bool)""
IL_0045: ldloc.0
IL_0046: ldloc.1
IL_0047: ceq
IL_0049: call ""void S.Write(bool)""
IL_004e: ldloc.0
IL_004f: ldloc.1
IL_0050: ceq
IL_0052: ldc.i4.0
IL_0053: ceq
IL_0055: call ""void S.Write(bool)""
IL_005a: ldloc.0
IL_005b: ldloc.1
IL_005c: cgt.un
IL_005e: ldc.i4.0
IL_005f: ceq
IL_0061: call ""void S.Write(bool)""
IL_0066: ldloc.0
IL_0067: ldloc.1
IL_0068: clt.un
IL_006a: ldc.i4.0
IL_006b: ceq
IL_006d: call ""void S.Write(bool)""
IL_0072: ldloc.0
IL_0073: ldloc.1
IL_0074: clt.un
IL_0076: call ""void S.Write(bool)""
IL_007b: ldloc.0
IL_007c: ldloc.1
IL_007d: cgt.un
IL_007f: call ""void S.Write(bool)""
IL_0084: ret
}
");
}
[Fact, WorkItem(49639, "https://github.com/dotnet/roslyn/issues/49639")]
public void CompareToNullWithNestedUnconstrainedTypeParameter()
{
var verifier = CompileAndVerify(@"
using System;
unsafe
{
test<int>(null);
S<int> s = default;
test<int>(&s);
static void test<T>(S<T>* s)
{
Console.WriteLine(s == null);
Console.WriteLine(s is null);
}
}
struct S<T> {}
", options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
True
True
False
False", verify: Verification.Skipped);
verifier.VerifyIL("Program.<<Main>$>g__test|0_0<T>(S<T>*)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: conv.u
IL_000d: ceq
IL_000f: call ""void System.Console.WriteLine(bool)""
IL_0014: ret
}
");
}
[Fact, WorkItem(49639, "https://github.com/dotnet/roslyn/issues/49639")]
public void CompareToNullWithPointerToUnmanagedTypeParameter()
{
var verifier = CompileAndVerify(@"
using System;
unsafe
{
test<int>(null);
int i = 0;
test<int>(&i);
static void test<T>(T* t) where T : unmanaged
{
Console.WriteLine(t == null);
Console.WriteLine(t is null);
}
}
", options: TestOptions.UnsafeReleaseExe, expectedOutput: @"
True
True
False
False", verify: Verification.Skipped);
verifier.VerifyIL("Program.<<Main>$>g__test|0_0<T>(T*)", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.u
IL_0003: ceq
IL_0005: call ""void System.Console.WriteLine(bool)""
IL_000a: ldarg.0
IL_000b: ldc.i4.0
IL_000c: conv.u
IL_000d: ceq
IL_000f: call ""void System.Console.WriteLine(bool)""
IL_0014: ret
}
");
}
[Theory]
[InlineData("int*")]
[InlineData("delegate*<void>")]
[InlineData("T*")]
[InlineData("delegate*<T>")]
public void CompareToNullInPatternOutsideUnsafe(string pointerType)
{
var comp = CreateCompilation($@"
var c = default(S<int>);
_ = c.Field is null;
unsafe struct S<T> where T : unmanaged
{{
#pragma warning disable CS0649 // Field is unassigned
public {pointerType} Field;
}}
", options: TestOptions.UnsafeReleaseExe);
comp.VerifyDiagnostics(
// (3,5): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
// _ = c.Field is null;
Diagnostic(ErrorCode.ERR_UnsafeNeeded, "c.Field").WithLocation(3, 5)
);
}
#endregion Pointer comparison tests
#region stackalloc tests
[Fact]
public void SimpleStackAlloc()
{
var text = @"
unsafe class C
{
void M()
{
int count = 1;
checked
{
int* p = stackalloc int[2];
char* q = stackalloc char[count];
Use(p);
Use(q);
}
unchecked
{
int* p = stackalloc int[2];
char* q = stackalloc char[count];
Use(p);
Use(q);
}
}
static void Use(int * ptr)
{
}
static void Use(char * ptr)
{
}
}
";
// NOTE: conversion is always unchecked, multiplication is always checked.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (int V_0, //count
int* V_1, //p
int* V_2) //p
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.8
IL_0003: conv.u
IL_0004: localloc
IL_0006: stloc.1
IL_0007: ldloc.0
IL_0008: conv.u
IL_0009: ldc.i4.2
IL_000a: mul.ovf.un
IL_000b: localloc
IL_000d: ldloc.1
IL_000e: call ""void C.Use(int*)""
IL_0013: call ""void C.Use(char*)""
IL_0018: ldc.i4.8
IL_0019: conv.u
IL_001a: localloc
IL_001c: stloc.2
IL_001d: ldloc.0
IL_001e: conv.u
IL_001f: ldc.i4.2
IL_0020: mul.ovf.un
IL_0021: localloc
IL_0023: ldloc.2
IL_0024: call ""void C.Use(int*)""
IL_0029: call ""void C.Use(char*)""
IL_002e: ret
}
");
}
[Fact]
public void StackAllocConversion()
{
var text = @"
unsafe class C
{
void M()
{
void* p = stackalloc int[2];
C q = stackalloc int[2];
}
public static implicit operator C(int* p)
{
return null;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 16 (0x10)
.maxstack 1
.locals init (void* V_0) //p
IL_0000: ldc.i4.8
IL_0001: conv.u
IL_0002: localloc
IL_0004: stloc.0
IL_0005: ldc.i4.8
IL_0006: conv.u
IL_0007: localloc
IL_0009: call ""C C.op_Implicit(int*)""
IL_000e: pop
IL_000f: ret
}
");
}
[Fact]
public void StackAllocConversionZero()
{
var text = @"
unsafe class C
{
void M()
{
void* p = stackalloc int[0];
C q = stackalloc int[0];
}
public static implicit operator C(int* p)
{
return null;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.M", @"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (void* V_0) //p
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldc.i4.0
IL_0004: conv.u
IL_0005: call ""C C.op_Implicit(int*)""
IL_000a: pop
IL_000b: ret
}
");
}
[Fact]
public void StackAllocSpecExample() //Section 18.8
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
Console.WriteLine(IntToString(123));
Console.WriteLine(IntToString(-456));
}
static string IntToString(int value) {
int n = value >= 0? value: -value;
unsafe {
char* buffer = stackalloc char[16];
char* p = buffer + 16;
do {
*--p = (char)(n % 10 + '0');
n /= 10;
} while (n != 0);
if (value < 0) *--p = '-';
return new string(p, 0, (int)(buffer + 16 - p));
}
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"123
-456
");
}
// See MethodToClassRewriter.VisitAssignmentOperator for an explanation.
[Fact]
public void StackAllocIntoHoistedLocal1()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
var p = stackalloc int[2];
var q = stackalloc int[2];
Action a = () =>
{
var r = stackalloc int[2];
var s = stackalloc int[2];
Action b = () =>
{
p = null; //capture p
r = null; //capture r
};
Use(s);
};
Use(q);
}
static void Use(int * ptr)
{
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails);
// Note that the stackalloc for p is written into a temp *before* the receiver (i.e. "this")
// for C.<>c__DisplayClass0.p is pushed onto the stack.
verifier.VerifyIL("C.Main", @"
{
// Code size 28 (0x1c)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.8
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* C.<>c__DisplayClass0_0.p""
IL_0012: ldc.i4.8
IL_0013: conv.u
IL_0014: localloc
IL_0016: call ""void C.Use(int*)""
IL_001b: ret
}
");
// Check that the same thing works inside a lambda.
verifier.VerifyIL("C.<>c__DisplayClass0_0.<Main>b__0", @"
{
// Code size 35 (0x23)
.maxstack 2
.locals init (C.<>c__DisplayClass0_1 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""C.<>c__DisplayClass0_1..ctor()""
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldarg.0
IL_0008: stfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_000d: ldc.i4.8
IL_000e: conv.u
IL_000f: localloc
IL_0011: stloc.1
IL_0012: ldloc.0
IL_0013: ldloc.1
IL_0014: stfld ""int* C.<>c__DisplayClass0_1.r""
IL_0019: ldc.i4.8
IL_001a: conv.u
IL_001b: localloc
IL_001d: call ""void C.Use(int*)""
IL_0022: ret
}
");
}
// See MethodToClassRewriter.VisitAssignmentOperator for an explanation.
[Fact]
public void StackAllocIntoHoistedLocal2()
{
// From native bug #59454 (in DevDiv collection)
var text = @"
unsafe class T
{
delegate int D();
static void Main()
{
int* v = stackalloc int[1];
D d = delegate { return *v; };
System.Console.WriteLine(d());
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails).VerifyIL("T.Main", @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (T.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""T.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.4
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* T.<>c__DisplayClass1_0.v""
IL_0012: ldloc.0
IL_0013: ldftn ""int T.<>c__DisplayClass1_0.<Main>b__0()""
IL_0019: newobj ""T.D..ctor(object, System.IntPtr)""
IL_001e: callvirt ""int T.D.Invoke()""
IL_0023: call ""void System.Console.WriteLine(int)""
IL_0028: ret
}
");
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails).VerifyIL("T.Main", @"
{
// Code size 41 (0x29)
.maxstack 2
.locals init (T.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0
int* V_1)
IL_0000: newobj ""T.<>c__DisplayClass1_0..ctor()""
IL_0005: stloc.0
IL_0006: ldc.i4.4
IL_0007: conv.u
IL_0008: localloc
IL_000a: stloc.1
IL_000b: ldloc.0
IL_000c: ldloc.1
IL_000d: stfld ""int* T.<>c__DisplayClass1_0.v""
IL_0012: ldloc.0
IL_0013: ldftn ""int T.<>c__DisplayClass1_0.<Main>b__0()""
IL_0019: newobj ""T.D..ctor(object, System.IntPtr)""
IL_001e: callvirt ""int T.D.Invoke()""
IL_0023: call ""void System.Console.WriteLine(int)""
IL_0028: ret
}
");
}
[Fact]
public void CSLegacyStackallocUse32bitChecked()
{
// This is from C# Legacy test where it uses Perl script to call ildasm and check 'mul.ovf' emitted
// $Roslyn\Main\LegacyTest\CSharp\Source\csharp\Source\Conformance\unsafecode\stackalloc\regr001.cs
var text = @"// <Title>Should checked affect stackalloc?</Title>
// <Description>
// The lower level localloc MSIL instruction takes an unsigned native int as input; however the higher level
// stackalloc uses only 32-bits. The example shows the operation overflowing the 32-bit multiply which leads to
// a curious edge condition.
// If compile with /checked we insert a mul.ovf instruction, and this causes a system overflow exception at runtime.
// </Description>
// <RelatedBugs>VSW:489857</RelatedBugs>
using System;
public class C
{
private static unsafe int Main()
{
Int64* intArray = stackalloc Int64[0x7fffffff];
return (int)intArray[0];
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldc.i4 0x7fffffff
IL_0005: conv.u
IL_0006: ldc.i4.8
IL_0007: mul.ovf.un
IL_0008: localloc
IL_000a: ldind.i8
IL_000b: conv.i4
IL_000c: ret
}
");
}
#endregion stackalloc tests
#region Functional tests
[Fact]
public void BubbleSort()
{
var text = @"
using System;
unsafe class C
{
static void Main()
{
BubbleSort();
BubbleSort(1);
BubbleSort(2, 1);
BubbleSort(3, 1, 2);
BubbleSort(3, 1, 4, 2);
}
static void BubbleSort(params int[] array)
{
if (array == null)
{
return;
}
fixed (int* begin = array)
{
BubbleSort(begin, end: begin + array.Length);
}
Console.WriteLine(string.Join("", "", array));
}
private static void BubbleSort(int* begin, int* end)
{
for (int* firstUnsorted = begin; firstUnsorted < end; firstUnsorted++)
{
for (int* current = firstUnsorted; current + 1 < end; current++)
{
if (current[0] > current[1])
{
SwapWithNext(current);
}
}
}
}
static void SwapWithNext(int* p)
{
int temp = *p;
p[0] = p[1];
p[1] = temp;
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
1
1, 2
1, 2, 3
1, 2, 3, 4");
}
[Fact]
public void BigStructs()
{
var text = @"
unsafe class C
{
static void Main()
{
void* v;
CheckOverflow(""(S15*)0 + sizeof(S15)"", () => v = checked((S15*)0 + sizeof(S15)));
CheckOverflow(""(S15*)0 + sizeof(S16)"", () => v = checked((S15*)0 + sizeof(S16)));
CheckOverflow(""(S16*)0 + sizeof(S15)"", () => v = checked((S16*)0 + sizeof(S15)));
}
static void CheckOverflow(string description, System.Action operation)
{
try
{
operation();
System.Console.WriteLine(""No overflow from {0}"", description);
}
catch (System.OverflowException)
{
System.Console.WriteLine(""Overflow from {0}"", description);
}
}
}
" + SizedStructs;
bool isx86 = (IntPtr.Size == 4);
string expectedOutput;
if (isx86)
{
expectedOutput = @"
No overflow from (S15*)0 + sizeof(S15)
Overflow from (S15*)0 + sizeof(S16)
Overflow from (S16*)0 + sizeof(S15)";
}
else
{
expectedOutput = @"
No overflow from (S15*)0 + sizeof(S15)
No overflow from (S15*)0 + sizeof(S16)
No overflow from (S16*)0 + sizeof(S15)";
}
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: expectedOutput, verify: Verification.Fails);
}
[Fact]
public void LambdaConversion()
{
var text = @"
using System;
class Program
{
static void Main()
{
Goo(x => { });
}
static void Goo(F1 f) { Console.WriteLine(1); }
static void Goo(F2 f) { Console.WriteLine(2); }
}
unsafe delegate void F1(int* x);
delegate void F2(int x);
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: @"2", verify: Verification.Passes);
}
[Fact]
public void LocalVariableReuse()
{
var text = @"
unsafe class C
{
int this[string s] { get { return 0; } set { } }
void Test()
{
{
this[""not pinned"".ToString()] += 2; //creates an unpinned string local (for the argument)
}
fixed (char* p = ""pinned"") //creates a pinned string local
{
}
{
this[""not pinned"".ToString()] += 2; //reuses the unpinned string local
}
fixed (char* p = ""pinned"") //reuses the pinned string local
{
}
}
}
";
// NOTE: one pinned string temp and one unpinned string temp.
// That is, pinned temps are reused in by other pinned temps
// but not by unpinned temps and vice versa.
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("C.Test", @"
{
// Code size 99 (0x63)
.maxstack 4
.locals init (string V_0,
char* V_1, //p
pinned string V_2,
char* V_3) //p
IL_0000: ldstr ""not pinned""
IL_0005: callvirt ""string object.ToString()""
IL_000a: stloc.0
IL_000b: ldarg.0
IL_000c: ldloc.0
IL_000d: ldarg.0
IL_000e: ldloc.0
IL_000f: call ""int C.this[string].get""
IL_0014: ldc.i4.2
IL_0015: add
IL_0016: call ""void C.this[string].set""
IL_001b: ldstr ""pinned""
IL_0020: stloc.2
IL_0021: ldloc.2
IL_0022: conv.u
IL_0023: stloc.1
IL_0024: ldloc.1
IL_0025: brfalse.s IL_002f
IL_0027: ldloc.1
IL_0028: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_002d: add
IL_002e: stloc.1
IL_002f: ldnull
IL_0030: stloc.2
IL_0031: ldstr ""not pinned""
IL_0036: callvirt ""string object.ToString()""
IL_003b: stloc.0
IL_003c: ldarg.0
IL_003d: ldloc.0
IL_003e: ldarg.0
IL_003f: ldloc.0
IL_0040: call ""int C.this[string].get""
IL_0045: ldc.i4.2
IL_0046: add
IL_0047: call ""void C.this[string].set""
IL_004c: ldstr ""pinned""
IL_0051: stloc.2
IL_0052: ldloc.2
IL_0053: conv.u
IL_0054: stloc.3
IL_0055: ldloc.3
IL_0056: brfalse.s IL_0060
IL_0058: ldloc.3
IL_0059: call ""int System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData.get""
IL_005e: add
IL_005f: stloc.3
IL_0060: ldnull
IL_0061: stloc.2
IL_0062: ret
}");
}
[WorkItem(544229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544229")]
[Fact]
public void UnsafeTypeAsAttributeArgument()
{
var template = @"
using System;
namespace System
{{
class Int32 {{ }}
}}
[A(Type = typeof({0}))]
class A : Attribute
{{
public Type Type;
static void Main()
{{
var a = (A)typeof(A).GetCustomAttributes(false)[0];
Console.WriteLine(a.Type == typeof({0}));
}}
}}
";
CompileAndVerify(string.Format(template, "int"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int*"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int**"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int[]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int[][]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
CompileAndVerify(string.Format(template, "int*[]"), options: TestOptions.UnsafeReleaseExe, expectedOutput: @"True", verify: Verification.Passes);
}
#endregion Functional tests
#region Regression tests
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void MixedSafeAndUnsafeFields()
{
var text =
@"struct Perf_Contexts
{
int data;
private int SuppressUnused(int x) { data = x; return data; }
}
public sealed class ChannelServices
{
static unsafe Perf_Contexts* GetPrivateContextsPerfCounters() { return null; }
private static int I1 = 12;
unsafe private static Perf_Contexts* perf_Contexts = GetPrivateContextsPerfCounters();
private static int I2 = 13;
private static int SuppressUnused(int x) { return I1 + I2; }
}
public class Test
{
public static void Main()
{
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails).VerifyDiagnostics();
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void SafeFieldBeforeUnsafeField()
{
var text = @"
class C
{
int x = 1;
unsafe int* p = (int*)2;
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics(
// (4,9): warning CS0414: The field 'C.x' is assigned but its value is never used
// int x = 1;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x"));
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026")]
[Fact]
public void SafeFieldAfterUnsafeField()
{
var text = @"
class C
{
unsafe int* p = (int*)2;
int x = 1;
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics(
// (5,9): warning CS0414: The field 'C.x' is assigned but its value is never used
// int x = 1;
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x"));
}
[WorkItem(545026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545026"), WorkItem(598170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598170")]
[Fact]
public void FixedPassByRef()
{
var text = @"
class Test
{
unsafe static int printAddress(out int* pI)
{
pI = null;
System.Console.WriteLine((ulong)pI);
return 1;
}
unsafe static int printAddress1(ref int* pI)
{
pI = null;
System.Console.WriteLine((ulong)pI);
return 1;
}
static int Main()
{
int retval = 0;
S s = new S();
unsafe
{
retval = Test.printAddress(out s.i);
retval = Test.printAddress1(ref s.i);
}
if (retval == 0)
System.Console.WriteLine(""Failed."");
return retval;
}
}
unsafe struct S
{
public fixed int i[1];
}
";
var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics(
// (24,44): error CS1510: A ref or out argument must be an assignable variable
// retval = Test.printAddress(out s.i);
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "s.i"),
// (25,45): error CS1510: A ref or out argument must be an assignable variable
// retval = Test.printAddress1(ref s.i);
Diagnostic(ErrorCode.ERR_RefLvalueExpected, "s.i"));
}
[Fact, WorkItem(545293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545293"), WorkItem(881188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/881188")]
public void EmptyAndFixedBufferStructIsInitialized()
{
var text = @"
public struct EmptyStruct { }
unsafe public struct FixedStruct { fixed char c[10]; }
public struct OuterStruct
{
EmptyStruct ES;
FixedStruct FS;
override public string ToString() { return (ES.ToString() + FS.ToString()); }
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Passes).VerifyDiagnostics(
// (8,17): warning CS0649: Field 'OuterStruct.FS' is never assigned to, and will always have its default value
// FixedStruct FS;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "FS").WithArguments("OuterStruct.FS", "").WithLocation(8, 17),
// (7,17): warning CS0649: Field 'OuterStruct.ES' is never assigned to, and will always have its default value
// EmptyStruct ES;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ES").WithArguments("OuterStruct.ES", "").WithLocation(7, 17)
);
}
[Fact, WorkItem(545296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545296"), WorkItem(545999, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545999")]
public void FixedBufferAndStatementWithFixedArrayElementAsInitializer()
{
var text = @"
unsafe public struct FixedStruct
{
fixed int i[1];
fixed char c[10];
override public string ToString() {
fixed (char* pc = this.c) { return pc[0].ToString(); }
}
}
";
var comp = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyDiagnostics();
comp.VerifyIL("FixedStruct.ToString", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: ldflda ""char* FixedStruct.c""
IL_0006: ldflda ""char FixedStruct.<c>e__FixedBuffer.FixedElementField""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: call ""string char.ToString()""
IL_0013: ret
}
");
}
[Fact]
public void FixedBufferAndStatementWithFixedArrayElementAsInitializerExe()
{
var text = @"
class Program
{
unsafe static void Main(string[] args)
{
FixedStruct s = new FixedStruct();
s.c[0] = 'A';
s.c[1] = 'B';
s.c[2] = 'C';
FixedStruct[] arr = { s };
System.Console.Write(arr[0].ToString());
}
}
unsafe public struct FixedStruct
{
public fixed char c[10];
override public string ToString()
{
fixed (char* pc = this.c)
{
System.Console.Write(pc[0]);
System.Console.Write(pc[1].ToString());
return pc[2].ToString();
}
}
}";
var comp = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "ABC", verify: Verification.Fails).VerifyDiagnostics();
comp.VerifyIL("FixedStruct.ToString", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (pinned char& V_0)
IL_0000: ldarg.0
IL_0001: ldflda ""char* FixedStruct.c""
IL_0006: ldflda ""char FixedStruct.<c>e__FixedBuffer.FixedElementField""
IL_000b: stloc.0
IL_000c: ldloc.0
IL_000d: conv.u
IL_000e: dup
IL_000f: ldind.u2
IL_0010: call ""void System.Console.Write(char)""
IL_0015: dup
IL_0016: ldc.i4.2
IL_0017: add
IL_0018: call ""string char.ToString()""
IL_001d: call ""void System.Console.Write(string)""
IL_0022: ldc.i4.2
IL_0023: conv.i
IL_0024: ldc.i4.2
IL_0025: mul
IL_0026: add
IL_0027: call ""string char.ToString()""
IL_002c: ret
}
");
}
[Fact, WorkItem(545299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545299")]
public void FixedStatementInlambda()
{
var text = @"
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
unsafe class C<T> where T : struct
{
public void Goo()
{
Func<T, char> d = delegate
{
fixed (char* p = ""blah"")
{
for (char* pp = p; pp != null; pp++)
return *pp;
}
return 'c';
};
Console.WriteLine(d(default(T)));
}
}
class A
{
static void Main()
{
new C<int>().Goo();
}
}
";
CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "b", verify: Verification.Fails);
}
[Fact, WorkItem(546865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546865")]
public void DontStackScheduleLocalPerformingPointerConversion()
{
var text = @"
using System;
unsafe struct S1
{
public char* charPointer;
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1();
fixed (char* p = ""hello"")
{
s1.charPointer = p;
ulong UserData = (ulong)&s1;
Test1(UserData);
}
}
static void Test1(ulong number)
{
S1* structPointer = (S1*)number;
Console.WriteLine(new string(structPointer->charPointer));
}
static ulong Test2()
{
S1* structPointer = (S1*)null; // null to pointer
int* intPointer = (int*)structPointer; // pointer to pointer
void* voidPointer = (void*)intPointer; // pointer to void
ulong number = (ulong)voidPointer; // pointer to integer
return number;
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "hello", verify: Verification.Fails);
// Note that the pointer local is not scheduled on the stack.
verifier.VerifyIL("Test.Test1", @"
{
// Code size 20 (0x14)
.maxstack 1
.locals init (S1* V_0) //structPointer
IL_0000: ldarg.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: ldfld ""char* S1.charPointer""
IL_0009: newobj ""string..ctor(char*)""
IL_000e: call ""void System.Console.WriteLine(string)""
IL_0013: ret
}");
// All locals retained.
verifier.VerifyIL("Test.Test2", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (S1* V_0, //structPointer
int* V_1, //intPointer
void* V_2) //voidPointer
IL_0000: ldc.i4.0
IL_0001: conv.u
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: stloc.1
IL_0005: ldloc.1
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: conv.u8
IL_0009: ret
}");
}
[Fact, WorkItem(546807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546807")]
public void PointerMemberAccessReadonlyField()
{
var text = @"
using System;
unsafe class C
{
public S1* S1;
}
unsafe struct S1
{
public readonly int* X;
public int* Y;
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1();
C c = new C();
c.S1 = &s1;
Console.WriteLine(null == c.S1->X);
Console.WriteLine(null == c.S1->Y);
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
True
True");
// NOTE: ldobj before ldfld S1.X, but not before ldfld S1.Y.
verifier.VerifyIL("Test.Main", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (S1 V_0, //s1
C V_1) //c
IL_0000: ldloca.s V_0
IL_0002: initobj ""S1""
IL_0008: newobj ""C..ctor()""
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: ldloca.s V_0
IL_0011: conv.u
IL_0012: stfld ""S1* C.S1""
IL_0017: ldc.i4.0
IL_0018: conv.u
IL_0019: ldloc.1
IL_001a: ldfld ""S1* C.S1""
IL_001f: ldfld ""int* S1.X""
IL_0024: ceq
IL_0026: call ""void System.Console.WriteLine(bool)""
IL_002b: ldc.i4.0
IL_002c: conv.u
IL_002d: ldloc.1
IL_002e: ldfld ""S1* C.S1""
IL_0033: ldfld ""int* S1.Y""
IL_0038: ceq
IL_003a: call ""void System.Console.WriteLine(bool)""
IL_003f: ret
}
");
}
[Fact, WorkItem(546807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546807")]
public void PointerMemberAccessCall()
{
var text = @"
using System;
unsafe class C
{
public S1* S1;
}
unsafe struct S1
{
public int X;
public void Instance()
{
Console.WriteLine(this.X);
}
}
static class Extensions
{
public static void Extension(this S1 s1)
{
Console.WriteLine(s1.X);
}
}
unsafe class Test
{
static void Main()
{
S1 s1 = new S1 { X = 2 };
C c = new C();
c.S1 = &s1;
c.S1->Instance();
c.S1->Extension();
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"
2
2");
// NOTE: ldobj before extension call, but not before instance call.
verifier.VerifyIL("Test.Main", @"
{
// Code size 59 (0x3b)
.maxstack 3
.locals init (S1 V_0, //s1
S1 V_1)
IL_0000: ldloca.s V_1
IL_0002: initobj ""S1""
IL_0008: ldloca.s V_1
IL_000a: ldc.i4.2
IL_000b: stfld ""int S1.X""
IL_0010: ldloc.1
IL_0011: stloc.0
IL_0012: newobj ""C..ctor()""
IL_0017: dup
IL_0018: ldloca.s V_0
IL_001a: conv.u
IL_001b: stfld ""S1* C.S1""
IL_0020: dup
IL_0021: ldfld ""S1* C.S1""
IL_0026: call ""void S1.Instance()""
IL_002b: ldfld ""S1* C.S1""
IL_0030: ldobj ""S1""
IL_0035: call ""void Extensions.Extension(S1)""
IL_003a: ret
}");
}
[Fact, WorkItem(531327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531327")]
public void PointerParameter()
{
var text = @"
using System;
unsafe struct S1
{
static void M(N.S2* ps2){}
}
namespace N
{
public struct S2
{
public int F;
}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll.WithConcurrentBuild(false), verify: Verification.Passes);
}
[Fact, WorkItem(531327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531327")]
public void PointerReturn()
{
var text = @"
using System;
namespace N
{
public struct S2
{
public int F;
}
}
unsafe struct S1
{
static N.S2* M(int ps2){return null;}
}
";
var verifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseDll.WithConcurrentBuild(false), verify: Verification.Fails);
}
[Fact, WorkItem(748530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/748530")]
public void Repro748530()
{
var text = @"
unsafe class A
{
public unsafe struct ListNode
{
internal ListNode(int data, ListNode* pNext)
{
}
}
}
";
var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll);
comp.VerifyDiagnostics();
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
uint offset = 0x80000000;
byte* wrong = data + offset;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 36 (0x24)
.maxstack 2
.locals init (byte* V_0, //data
uint V_1, //offset
byte* V_2) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldc.i4 0x80000000
IL_000c: stloc.1
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: conv.u
IL_0010: add
IL_0011: stloc.2
IL_0012: ldstr ""{0:X}""
IL_0017: ldloc.2
IL_0018: conv.u8
IL_0019: box ""ulong""
IL_001e: call ""void System.Console.WriteLine(string, object)""
IL_0023: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv001()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
short* data = (short*)0x76543210;
uint offset = 0x40000000;
short* wrong = data + offset;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 40 (0x28)
.maxstack 3
.locals init (short* V_0, //data
uint V_1, //offset
short* V_2) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldc.i4 0x40000000
IL_000c: stloc.1
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: conv.u8
IL_0010: ldc.i4.2
IL_0011: conv.i8
IL_0012: mul
IL_0013: conv.i
IL_0014: add
IL_0015: stloc.2
IL_0016: ldstr ""{0:X}""
IL_001b: ldloc.2
IL_001c: conv.u8
IL_001d: box ""ulong""
IL_0022: call ""void System.Console.WriteLine(string, object)""
IL_0027: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv002()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
byte* wrong = data + 0x80000000u;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F6543210", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 34 (0x22)
.maxstack 2
.locals init (byte* V_0, //data
byte* V_1) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4 0x80000000
IL_000d: conv.u
IL_000e: add
IL_000f: stloc.1
IL_0010: ldstr ""{0:X}""
IL_0015: ldloc.1
IL_0016: conv.u8
IL_0017: box ""ulong""
IL_001c: call ""void System.Console.WriteLine(string, object)""
IL_0021: ret
}
");
}
[WorkItem(682584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/682584")]
[Fact]
public void UnsafeMathConv002a()
{
var text = @"
using System;
unsafe class C
{
static void Main(string[] args)
{
byte* data = (byte*)0x76543210;
byte* wrong = data + 0x7FFFFFFFu;
Console.WriteLine(""{0:X}"", (ulong)wrong);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "F654320F", verify: Verification.Fails);
compVerifier.VerifyIL("C.Main", @"
{
// Code size 33 (0x21)
.maxstack 2
.locals init (byte* V_0, //data
byte* V_1) //wrong
IL_0000: ldc.i4 0x76543210
IL_0005: conv.i
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4 0x7fffffff
IL_000d: add
IL_000e: stloc.1
IL_000f: ldstr ""{0:X}""
IL_0014: ldloc.1
IL_0015: conv.u8
IL_0016: box ""ulong""
IL_001b: call ""void System.Console.WriteLine(string, object)""
IL_0020: ret
}
");
}
[WorkItem(857598, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/857598")]
[Fact]
public void VoidToNullable()
{
var text = @"
unsafe class C
{
public int? x = (int?)(void*)0;
}
class c1
{
public static void Main()
{
var x = new C();
System.Console.WriteLine(x.x);
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Passes);
compVerifier.VerifyIL("C..ctor", @"
{
// Code size 21 (0x15)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.0
IL_0002: conv.i
IL_0003: conv.i4
IL_0004: newobj ""int?..ctor(int)""
IL_0009: stfld ""int? C.x""
IL_000e: ldarg.0
IL_000f: call ""object..ctor()""
IL_0014: ret
}
");
}
[WorkItem(907771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907771")]
[Fact]
public void UnsafeBeforeReturn001()
{
var text = @"
using System;
public unsafe class C
{
private static readonly byte[] _emptyArray = new byte[0];
public static void Main()
{
System.Console.WriteLine(ToManagedByteArray(2));
}
public static byte[] ToManagedByteArray(uint byteCount)
{
if (byteCount == 0)
{
return _emptyArray; // degenerate case
}
else
{
byte[] bytes = new byte[byteCount];
fixed (byte* pBytes = bytes)
{
}
return bytes;
}
}
}
";
var compVerifier = CompileAndVerify(text, options: TestOptions.UnsafeReleaseExe, expectedOutput: "System.Byte[]", verify: Verification.Fails);
compVerifier.VerifyIL("C.ToManagedByteArray", @"
{
// Code size 42 (0x2a)
.maxstack 3
.locals init (byte* V_0, //pBytes
pinned byte[] V_1)
IL_0000: ldarg.0
IL_0001: brtrue.s IL_0009
IL_0003: ldsfld ""byte[] C._emptyArray""
IL_0008: ret
IL_0009: ldarg.0
IL_000a: newarr ""byte""
IL_000f: dup
IL_0010: dup
IL_0011: stloc.1
IL_0012: brfalse.s IL_0019
IL_0014: ldloc.1
IL_0015: ldlen
IL_0016: conv.i4
IL_0017: brtrue.s IL_001e
IL_0019: ldc.i4.0
IL_001a: conv.u
IL_001b: stloc.0
IL_001c: br.s IL_0027
IL_001e: ldloc.1
IL_001f: ldc.i4.0
IL_0020: ldelema ""byte""
IL_0025: conv.u
IL_0026: stloc.0
IL_0027: ldnull
IL_0028: stloc.1
IL_0029: ret
}
");
}
[WorkItem(907771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907771")]
[Fact]
public void UnsafeBeforeReturn002()
{
var text = @"
using System;
public unsafe class C
{
private static readonly byte[] _emptyArray = new byte[0];
public static void Main()
{
System.Console.WriteLine(ToManagedByteArray(2));
}
public static byte[] ToManagedByteArray(uint byteCount)
{
if (byteCount == 0)
{
return _emptyArray; // degenerate case
}
else
{
byte[] bytes = new byte[byteCount];
fixed (byte* pBytes = bytes)
{
}
return bytes;
}
}
}
";
var v = CompileAndVerify(text, options: TestOptions.UnsafeDebugExe, expectedOutput: "System.Byte[]", verify: Verification.Fails);
v.VerifyIL("C.ToManagedByteArray", @"
{
// Code size 64 (0x40)
.maxstack 2
.locals init (bool V_0,
byte[] V_1,
byte[] V_2, //bytes
byte* V_3, //pBytes
pinned byte[] V_4)
-IL_0000: nop
-IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: ceq
IL_0005: stloc.0
~IL_0006: ldloc.0
IL_0007: brfalse.s IL_0012
-IL_0009: nop
-IL_000a: ldsfld ""byte[] C._emptyArray""
IL_000f: stloc.1
IL_0010: br.s IL_003e
-IL_0012: nop
-IL_0013: ldarg.0
IL_0014: newarr ""byte""
IL_0019: stloc.2
-IL_001a: ldloc.2
IL_001b: dup
IL_001c: stloc.s V_4
IL_001e: brfalse.s IL_0026
IL_0020: ldloc.s V_4
IL_0022: ldlen
IL_0023: conv.i4
IL_0024: brtrue.s IL_002b
IL_0026: ldc.i4.0
IL_0027: conv.u
IL_0028: stloc.3
IL_0029: br.s IL_0035
IL_002b: ldloc.s V_4
IL_002d: ldc.i4.0
IL_002e: ldelema ""byte""
IL_0033: conv.u
IL_0034: stloc.3
-IL_0035: nop
-IL_0036: nop
~IL_0037: ldnull
IL_0038: stloc.s V_4
-IL_003a: ldloc.2
IL_003b: stloc.1
IL_003c: br.s IL_003e
-IL_003e: ldloc.1
IL_003f: ret
}
", sequencePoints: "C.ToManagedByteArray");
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void SystemIntPtrInSignature_BreakingChange()
{
// NOTE: the IL is intentionally not compliant with ECMA spec
// in particular Metadata spec II.23.2.16 (Short form signatures) says that
// [mscorlib]System.IntPtr is not supposed to be used in metadata
// and short-version 'native int' is supposed to be used instead.
var ilSource =
@"
.class public AddressHelper{
.method public hidebysig static valuetype [mscorlib]System.IntPtr AddressOf<T>(!!0& t){
ldarg 0
ldind.i
ret
}
}
";
var csharpSource =
@"
class Program
{
static void Main(string[] args)
{
var s = string.Empty;
var i = AddressHelper.AddressOf(ref s);
System.Console.WriteLine(i);
}
}
";
var cscomp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource);
var expected = new[] {
// (7,35): error CS0570: 'AddressHelper.AddressOf<T>(?)' is not supported by the language
// var i = AddressHelper.AddressOf(ref s);
Diagnostic(ErrorCode.ERR_BindToBogus, "AddressOf").WithArguments("AddressHelper.AddressOf<T>(?)").WithLocation(7, 35)
};
cscomp.VerifyDiagnostics(expected);
}
[ClrOnlyFact(ClrOnlyReason.Ilasm)]
public void SystemIntPtrInSignature_BreakingChange_001()
{
var ilSource =
@"
.class public AddressHelper{
.method public hidebysig static native int AddressOf<T>(!!0& t){
ldc.i4.5
conv.u
ret
}
}
";
var csharpSource =
@"
class Program
{
static void Main(string[] args)
{
var s = string.Empty;
var i = AddressHelper.AddressOf(ref s);
System.Console.WriteLine(i);
}
}
";
var compilation = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource, targetFramework: TargetFramework.Mscorlib40, options: TestOptions.ReleaseExe);
compilation.VerifyDiagnostics();
var result = CompileAndVerify(compilation, expectedOutput: "5");
}
[Fact, WorkItem(7550, "https://github.com/dotnet/roslyn/issues/7550")]
public void EnsureNullPointerIsPoppedIfUnused()
{
string source = @"
public class A
{
public unsafe byte* Ptr;
static void Main()
{
unsafe
{
var x = new A();
byte* ptr = (x == null) ? null : x.Ptr;
}
System.Console.WriteLine(""OK"");
}
}
";
CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "OK", verify: Verification.Passes);
}
[Fact, WorkItem(40768, "https://github.com/dotnet/roslyn/issues/40768")]
public void DoesNotEmitArrayDotEmptyForEmptyPointerArrayParams()
{
var source = @"
using System;
public static class Program
{
public static unsafe void Main()
{
Console.WriteLine(Test());
}
public static unsafe int Test(params int*[] types)
{
return types.Length;
}
}";
var comp = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0", verify: Verification.Fails);
comp.VerifyIL("Program.Main", @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: newarr ""int*""
IL_0006: call ""int Program.Test(params int*[])""
IL_000b: call ""void System.Console.WriteLine(int)""
IL_0010: ret
}");
}
[Fact]
public void DoesEmitArrayDotEmptyForEmptyPointerArrayArrayParams()
{
var source = @"
using System;
public static class Program
{
public static unsafe void Main()
{
Console.WriteLine(Test());
}
public static unsafe int Test(params int*[][] types)
{
return types.Length;
}
}";
var comp = CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, expectedOutput: "0");
comp.VerifyIL("Program.Main", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: call ""int*[][] System.Array.Empty<int*[]>()""
IL_0005: call ""int Program.Test(params int*[][])""
IL_000a: call ""void System.Console.WriteLine(int)""
IL_000f: ret
}");
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/Core/GoToDefinition/GoToSymbolContext.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.GoToDefinition
{
internal class GoToSymbolContext
{
private readonly object _gate = new();
private readonly MultiDictionary<string, DefinitionItem> _items = new();
public GoToSymbolContext(Document document, int position, CancellationToken cancellationToken)
{
Document = document;
Position = position;
CancellationToken = cancellationToken;
}
public Document Document { get; }
public int Position { get; }
public CancellationToken CancellationToken { get; }
public TextSpan Span { get; set; }
internal bool TryGetItems(string key, out IEnumerable<DefinitionItem> items)
{
if (_items.ContainsKey(key))
{
// Multidictionary valuesets are structs so we can't
// just check for null
items = _items[key];
return true;
}
else
{
items = null;
return false;
}
}
public void AddItem(string key, DefinitionItem item)
{
lock (_gate)
{
_items.Add(key, item);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.GoToDefinition
{
internal class GoToSymbolContext
{
private readonly object _gate = new();
private readonly MultiDictionary<string, DefinitionItem> _items = new();
public GoToSymbolContext(Document document, int position, CancellationToken cancellationToken)
{
Document = document;
Position = position;
CancellationToken = cancellationToken;
}
public Document Document { get; }
public int Position { get; }
public CancellationToken CancellationToken { get; }
public TextSpan Span { get; set; }
internal bool TryGetItems(string key, out IEnumerable<DefinitionItem> items)
{
if (_items.ContainsKey(key))
{
// Multidictionary valuesets are structs so we can't
// just check for null
items = _items[key];
return true;
}
else
{
items = null;
return false;
}
}
public void AddItem(string key, DefinitionItem item)
{
lock (_gate)
{
_items.Add(key, item);
}
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Features/Core/Portable/Organizing/Organizers/ISyntaxOrganizer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading;
namespace Microsoft.CodeAnalysis.Organizing.Organizers
{
internal interface ISyntaxOrganizer
{
/// <summary>
/// syntax node types this organizer is applicable to
/// </summary>
IEnumerable<Type> SyntaxNodeTypes { get; }
/// <summary>
/// organize given node
/// </summary>
SyntaxNode OrganizeNode(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken = default);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading;
namespace Microsoft.CodeAnalysis.Organizing.Organizers
{
internal interface ISyntaxOrganizer
{
/// <summary>
/// syntax node types this organizer is applicable to
/// </summary>
IEnumerable<Type> SyntaxNodeTypes { get; }
/// <summary>
/// organize given node
/// </summary>
SyntaxNode OrganizeNode(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken = default);
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/VisualStudio/CSharp/Test/CodeModel/FileCodeClassTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeClassTests : AbstractFileCodeElementTests
{
public FileCodeClassTests()
: base(@"using System;
public abstract class Goo : IDisposable, ICloneable
{
}
[Serializable]
public class Bar
{
int a;
public int A
{
get
{
return a;
}
}
public string WindowsUserID => ""Domain"";
}")
{
}
private CodeClass GetCodeClass(params object[] path)
{
return (CodeClass)GetCodeElement(path);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsAbstract()
{
var cc = GetCodeClass("Goo");
Assert.True(cc.IsAbstract);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Bases()
{
var cc = GetCodeClass("Goo");
var bases = cc.Bases;
Assert.Equal(1, bases.Count);
Assert.Equal(1, bases.Cast<CodeElement>().Count());
Assert.NotNull(bases.Parent);
var parentClass = bases.Parent as CodeClass;
Assert.NotNull(parentClass);
Assert.Equal("Goo", parentClass.FullName);
Assert.True(bases.Item("object") is CodeClass);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void ImplementedInterfaces()
{
var cc = GetCodeClass("Goo");
var interfaces = cc.ImplementedInterfaces;
Assert.Equal(2, interfaces.Count);
Assert.Equal(2, interfaces.Cast<CodeElement>().Count());
Assert.NotNull(interfaces.Parent);
var parentClass = interfaces.Parent as CodeClass;
Assert.NotNull(parentClass);
Assert.Equal("Goo", parentClass.FullName);
Assert.True(interfaces.Item("System.IDisposable") is CodeInterface);
Assert.True(interfaces.Item("ICloneable") is CodeInterface);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void KindTest()
{
var cc = GetCodeClass("Goo");
Assert.Equal(vsCMElement.vsCMElementClass, cc.Kind);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody);
Assert.Equal(10, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartHeader);
Assert.Equal(8, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(8, startPoint.Line);
Assert.Equal(14, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(7, endPoint.Line);
Assert.Equal(15, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody);
Assert.Equal(21, endPoint.Line);
Assert.Equal(1, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(8, endPoint.Line);
Assert.Equal(17, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(21, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.StartPoint;
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.EndPoint;
Assert.Equal(21, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Accessor()
{
var testObject = GetCodeClass("Bar");
var l = from p in testObject.Members.OfType<CodeProperty>() where vsCMAccess.vsCMAccessPublic == p.Access && p.Getter != null && !p.Getter.IsShared && vsCMAccess.vsCMAccessPublic == p.Getter.Access select p;
var z = l.ToList<CodeProperty>();
Assert.Equal(2, z.Count);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using EnvDTE;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeClassTests : AbstractFileCodeElementTests
{
public FileCodeClassTests()
: base(@"using System;
public abstract class Goo : IDisposable, ICloneable
{
}
[Serializable]
public class Bar
{
int a;
public int A
{
get
{
return a;
}
}
public string WindowsUserID => ""Domain"";
}")
{
}
private CodeClass GetCodeClass(params object[] path)
{
return (CodeClass)GetCodeElement(path);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsAbstract()
{
var cc = GetCodeClass("Goo");
Assert.True(cc.IsAbstract);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Bases()
{
var cc = GetCodeClass("Goo");
var bases = cc.Bases;
Assert.Equal(1, bases.Count);
Assert.Equal(1, bases.Cast<CodeElement>().Count());
Assert.NotNull(bases.Parent);
var parentClass = bases.Parent as CodeClass;
Assert.NotNull(parentClass);
Assert.Equal("Goo", parentClass.FullName);
Assert.True(bases.Item("object") is CodeClass);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void ImplementedInterfaces()
{
var cc = GetCodeClass("Goo");
var interfaces = cc.ImplementedInterfaces;
Assert.Equal(2, interfaces.Count);
Assert.Equal(2, interfaces.Cast<CodeElement>().Count());
Assert.NotNull(interfaces.Parent);
var parentClass = interfaces.Parent as CodeClass;
Assert.NotNull(parentClass);
Assert.Equal("Goo", parentClass.FullName);
Assert.True(interfaces.Item("System.IDisposable") is CodeInterface);
Assert.True(interfaces.Item("ICloneable") is CodeInterface);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void KindTest()
{
var cc = GetCodeClass("Goo");
Assert.Equal(vsCMElement.vsCMElementClass, cc.Kind);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartBody);
Assert.Equal(10, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartHeader);
Assert.Equal(8, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(8, startPoint.Line);
Assert.Equal(14, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(7, endPoint.Line);
Assert.Equal(15, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartBody);
Assert.Equal(21, endPoint.Line);
Assert.Equal(1, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(8, endPoint.Line);
Assert.Equal(17, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
var testObject = GetCodeClass("Bar");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(21, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
var testObject = GetCodeClass("Bar");
var startPoint = testObject.StartPoint;
Assert.Equal(7, startPoint.Line);
Assert.Equal(1, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
var testObject = GetCodeClass("Bar");
var endPoint = testObject.EndPoint;
Assert.Equal(21, endPoint.Line);
Assert.Equal(2, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Accessor()
{
var testObject = GetCodeClass("Bar");
var l = from p in testObject.Members.OfType<CodeProperty>() where vsCMAccess.vsCMAccessPublic == p.Access && p.Getter != null && !p.Getter.IsShared && vsCMAccess.vsCMAccessPublic == p.Getter.Access select p;
var z = l.ToList<CodeProperty>();
Assert.Equal(2, z.Count);
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.TypeParameterSymbolKey.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Shared.Extensions;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private static class TypeParameterSymbolKey
{
public static void Create(ITypeParameterSymbol symbol, SymbolKeyWriter visitor)
{
if (symbol.TypeParameterKind == TypeParameterKind.Cref)
{
visitor.WriteBoolean(true);
visitor.WriteLocation(symbol.Locations[0]);
}
else
{
visitor.WriteBoolean(false);
visitor.WriteString(symbol.MetadataName);
visitor.WriteSymbolKey(symbol.ContainingSymbol);
}
}
public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason)
{
var isCref = reader.ReadBoolean();
if (isCref)
{
var location = reader.ReadLocation(out var locationFailureReason)!;
if (locationFailureReason != null)
{
failureReason = $"({nameof(TypeParameterSymbolKey)} {nameof(location)} failed -> {locationFailureReason})";
return default;
}
var resolution = reader.ResolveLocation(location);
failureReason = null;
return resolution.GetValueOrDefault();
}
else
{
var metadataName = reader.ReadString();
var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason);
if (containingSymbolFailureReason != null)
{
failureReason = $"({nameof(TypeParameterSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})";
return default;
}
using var result = PooledArrayBuilder<ITypeParameterSymbol>.GetInstance();
foreach (var containingSymbol in containingSymbolResolution)
{
foreach (var typeParam in containingSymbol.GetTypeParameters())
{
if (typeParam.MetadataName == metadataName)
{
result.AddIfNotNull(typeParam);
}
}
}
return CreateResolution(result, $"({nameof(TypeParameterSymbolKey)} '{metadataName}' not found)", out failureReason);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Shared.Extensions;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private static class TypeParameterSymbolKey
{
public static void Create(ITypeParameterSymbol symbol, SymbolKeyWriter visitor)
{
if (symbol.TypeParameterKind == TypeParameterKind.Cref)
{
visitor.WriteBoolean(true);
visitor.WriteLocation(symbol.Locations[0]);
}
else
{
visitor.WriteBoolean(false);
visitor.WriteString(symbol.MetadataName);
visitor.WriteSymbolKey(symbol.ContainingSymbol);
}
}
public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason)
{
var isCref = reader.ReadBoolean();
if (isCref)
{
var location = reader.ReadLocation(out var locationFailureReason)!;
if (locationFailureReason != null)
{
failureReason = $"({nameof(TypeParameterSymbolKey)} {nameof(location)} failed -> {locationFailureReason})";
return default;
}
var resolution = reader.ResolveLocation(location);
failureReason = null;
return resolution.GetValueOrDefault();
}
else
{
var metadataName = reader.ReadString();
var containingSymbolResolution = reader.ReadSymbolKey(out var containingSymbolFailureReason);
if (containingSymbolFailureReason != null)
{
failureReason = $"({nameof(TypeParameterSymbolKey)} {nameof(containingSymbolResolution)} failed -> {containingSymbolFailureReason})";
return default;
}
using var result = PooledArrayBuilder<ITypeParameterSymbol>.GetInstance();
foreach (var containingSymbol in containingSymbolResolution)
{
foreach (var typeParam in containingSymbol.GetTypeParameters())
{
if (typeParam.MetadataName == metadataName)
{
result.AddIfNotNull(typeParam);
}
}
}
return CreateResolution(result, $"({nameof(TypeParameterSymbolKey)} '{metadataName}' not found)", out failureReason);
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/VisualBasicTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests.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.
Option Strict On
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
Imports Microsoft.CodeAnalysis.PreferFrameworkType
Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.PreferFrameworkTypeTests
Partial Public Class PreferFrameworkTypeTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Private ReadOnly onWithInfo As New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion)
Private ReadOnly offWithInfo As New CodeStyleOption2(Of Boolean)(False, NotificationOption2.Suggestion)
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (New VisualBasicPreferFrameworkTypeDiagnosticAnalyzer(),
New PreferFrameworkTypeCodeFixProvider())
End Function
Private ReadOnly Property NoFrameworkType As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeEverywhere As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.offWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeInDeclaration As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeInMemberAccess As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, Me.onWithInfo}
}
End Get
End Property
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotWhenOptionsAreNotSet() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|Integer|]
End Class
", New TestParameters(options:=NoFrameworkType))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnUserdefinedType() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|C|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnFrameworkType() As Task
Await TestMissingInRegularAndScriptAsync("
Imports System
Class C
Protected i As [|Int32|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnQualifiedTypeSyntax() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|System.Int32|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|List|](Of Integer)
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnIdentifierThatIsNotTypeSyntax() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected [|i|] As Integer
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnBoolean_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Boolean|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnByte_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Byte|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnChar_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Char|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnObject_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Object|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnSByte_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|SByte|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnString_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|String|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnSingle_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Single|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnDecimal_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Decimal|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnDouble_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Double|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FieldDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Protected i As [|Integer|]
End Class
",
"Imports System
Class C
Protected i As Int32
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FieldDeclarationWithInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Protected i As [|Integer|] = 5
End Class
",
"Imports System
Class C
Protected i As Int32 = 5
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function DelegateDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Delegate Function PerformCalculation(x As Integer, y As Integer) As [|Integer|]
End Class
",
"Imports System
Class C
Public Delegate Function PerformCalculation(x As Integer, y As Integer) As Int32
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function PropertyDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Property X As [|Long|]
End Class
",
"Imports System
Class C
Public Property X As Int64
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GenericPropertyDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Class C
Public Property X As List(Of [|Long|])
End Class
",
"Imports System
Imports System.Collections.Generic
Class C
Public Property X As List(Of Int64)
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FunctionDeclarationReturnType() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Function F() As [|Integer|]
End Function
End Class
",
"Imports System
Class C
Public Function F() As Int32
End Function
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MethodDeclarationParameters() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub F(x As [|Integer|])
End Sub
End Class
",
"Imports System
Class C
Public Sub F(x As Int32)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GenericMethodInvocation() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Method(Of T)()
End Sub
Public Sub Test()
Method(Of [|Integer|])()
End Sub
End Class
",
"Imports System
Class C
Public Sub Method(Of T)()
End Sub
Public Sub Test()
Method(Of Int32)()
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function LocalDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x As [|Integer|] = 5
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x As Int32 = 5
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MemberAccess() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = [|Integer|].MaxValue
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = Int32.MaxValue
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MemberAccess2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = [|Integer|].Parse(""1"")
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = Int32.Parse(""1"")
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function DocCommentTriviaCrefExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
''' <see cref=""[|Integer|].MaxValue""/>
Public Sub Test()
End Sub
End Class
",
"Imports System
Class C
''' <see cref=""Integer.MaxValue""/>
Public Sub Test()
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GetTypeExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = GetType([|Integer|])
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = GetType(Int32)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FormalParametersWithinLambdaExression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim func3 As Func(Of Integer, Integer) = Function(z As [|Integer|]) z + 1
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim func3 As Func(Of Integer, Integer) = Function(z As Int32) z + 1
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ObjectCreationExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim z = New [|Date|](2016, 8, 23)
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim z = New DateTime(2016, 8, 23)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ArrayDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim k As [|Integer|]() = New Integer(3) {}
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim k As Int32() = New Integer(3) {}
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ArrayInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim k As Integer() = New [|Integer|](3) {0, 1, 2, 3}
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim k As Integer() = New Int32(3) {0, 1, 2, 3}
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MultiDimentionalArrayAsGenericTypeParameter() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Class C
Public Sub Test()
Dim a As List(Of [|Integer|]()(,)(,,,))
End Sub
End Class
",
"Imports System
Imports System.Collections.Generic
Class C
Public Sub Test()
Dim a As List(Of Int32()(,)(,,,))
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ForStatement() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
For j As [|Integer|] = 0 To 3
Next
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
For j As Int32 = 0 To 3
Next
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ForeachStatement() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
For Each item As [|Integer|] In New Integer() {1, 2, 3}
Next
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
For Each item As Int32 In New Integer() {1, 2, 3}
Next
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function LeadingTrivia() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
' This is a comment
Dim x As [|Integer|]
End Sub
End Class",
"Imports System
Class C
Public Sub Test()
' This is a comment
Dim x As Int32
End Sub
End Class", options:=FrameworkTypeInDeclaration)
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.
Option Strict On
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
Imports Microsoft.CodeAnalysis.PreferFrameworkType
Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics.Analyzers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.PreferFrameworkTypeTests
Partial Public Class PreferFrameworkTypeTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Private ReadOnly onWithInfo As New CodeStyleOption2(Of Boolean)(True, NotificationOption2.Suggestion)
Private ReadOnly offWithInfo As New CodeStyleOption2(Of Boolean)(False, NotificationOption2.Suggestion)
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (New VisualBasicPreferFrameworkTypeDiagnosticAnalyzer(),
New PreferFrameworkTypeCodeFixProvider())
End Function
Private ReadOnly Property NoFrameworkType As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, True, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeEverywhere As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.offWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeInDeclaration As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, Me.onWithInfo}
}
End Get
End Property
Private ReadOnly Property FrameworkTypeInMemberAccess As OptionsCollection
Get
Return New OptionsCollection(GetLanguage()) From {
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, False, NotificationOption2.Suggestion},
{CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, Me.onWithInfo}
}
End Get
End Property
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotWhenOptionsAreNotSet() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|Integer|]
End Class
", New TestParameters(options:=NoFrameworkType))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnUserdefinedType() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|C|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnFrameworkType() As Task
Await TestMissingInRegularAndScriptAsync("
Imports System
Class C
Protected i As [|Int32|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnQualifiedTypeSyntax() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|System.Int32|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnFrameworkTypeWithNoPredefinedKeywordEquivalent() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected i As [|List|](Of Integer)
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnIdentifierThatIsNotTypeSyntax() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected [|i|] As Integer
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnBoolean_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Boolean|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnByte_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Byte|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnChar_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Char|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnObject_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Object|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnSByte_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|SByte|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnString_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|String|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnSingle_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Single|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnDecimal_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Decimal|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function NotOnDouble_KeywordMatchesTypeName() As Task
Await TestMissingInRegularAndScriptAsync("
Class C
Protected x As [|Double|]
End Class
", New TestParameters(options:=FrameworkTypeEverywhere))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FieldDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Protected i As [|Integer|]
End Class
",
"Imports System
Class C
Protected i As Int32
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FieldDeclarationWithInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Protected i As [|Integer|] = 5
End Class
",
"Imports System
Class C
Protected i As Int32 = 5
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function DelegateDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Delegate Function PerformCalculation(x As Integer, y As Integer) As [|Integer|]
End Class
",
"Imports System
Class C
Public Delegate Function PerformCalculation(x As Integer, y As Integer) As Int32
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function PropertyDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Property X As [|Long|]
End Class
",
"Imports System
Class C
Public Property X As Int64
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GenericPropertyDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Class C
Public Property X As List(Of [|Long|])
End Class
",
"Imports System
Imports System.Collections.Generic
Class C
Public Property X As List(Of Int64)
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FunctionDeclarationReturnType() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Function F() As [|Integer|]
End Function
End Class
",
"Imports System
Class C
Public Function F() As Int32
End Function
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MethodDeclarationParameters() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub F(x As [|Integer|])
End Sub
End Class
",
"Imports System
Class C
Public Sub F(x As Int32)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GenericMethodInvocation() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Method(Of T)()
End Sub
Public Sub Test()
Method(Of [|Integer|])()
End Sub
End Class
",
"Imports System
Class C
Public Sub Method(Of T)()
End Sub
Public Sub Test()
Method(Of Int32)()
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function LocalDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x As [|Integer|] = 5
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x As Int32 = 5
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MemberAccess() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = [|Integer|].MaxValue
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = Int32.MaxValue
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MemberAccess2() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = [|Integer|].Parse(""1"")
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = Int32.Parse(""1"")
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function DocCommentTriviaCrefExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
''' <see cref=""[|Integer|].MaxValue""/>
Public Sub Test()
End Sub
End Class
",
"Imports System
Class C
''' <see cref=""Integer.MaxValue""/>
Public Sub Test()
End Sub
End Class
", options:=FrameworkTypeInMemberAccess)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function GetTypeExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim x = GetType([|Integer|])
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim x = GetType(Int32)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function FormalParametersWithinLambdaExression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim func3 As Func(Of Integer, Integer) = Function(z As [|Integer|]) z + 1
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim func3 As Func(Of Integer, Integer) = Function(z As Int32) z + 1
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ObjectCreationExpression() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim z = New [|Date|](2016, 8, 23)
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim z = New DateTime(2016, 8, 23)
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ArrayDeclaration() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim k As [|Integer|]() = New Integer(3) {}
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim k As Int32() = New Integer(3) {}
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ArrayInitializer() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
Dim k As Integer() = New [|Integer|](3) {0, 1, 2, 3}
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
Dim k As Integer() = New Int32(3) {0, 1, 2, 3}
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function MultiDimentionalArrayAsGenericTypeParameter() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Imports System.Collections.Generic
Class C
Public Sub Test()
Dim a As List(Of [|Integer|]()(,)(,,,))
End Sub
End Class
",
"Imports System
Imports System.Collections.Generic
Class C
Public Sub Test()
Dim a As List(Of Int32()(,)(,,,))
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ForStatement() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
For j As [|Integer|] = 0 To 3
Next
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
For j As Int32 = 0 To 3
Next
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function ForeachStatement() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
For Each item As [|Integer|] In New Integer() {1, 2, 3}
Next
End Sub
End Class
",
"Imports System
Class C
Public Sub Test()
For Each item As Int32 In New Integer() {1, 2, 3}
Next
End Sub
End Class
", options:=FrameworkTypeInDeclaration)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)>
Public Async Function LeadingTrivia() As Task
Await TestInRegularAndScriptAsync(
"Imports System
Class C
Public Sub Test()
' This is a comment
Dim x As [|Integer|]
End Sub
End Class",
"Imports System
Class C
Public Sub Test()
' This is a comment
Dim x As Int32
End Sub
End Class", options:=FrameworkTypeInDeclaration)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/AssemblyReferencesTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.MetadataUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
public class AssemblyReferencesTests : EditAndContinueTestBase
{
private static readonly CSharpCompilationOptions s_signedDll =
TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2);
/// <summary>
/// The baseline metadata might have less (or even different) references than
/// the current compilation. We shouldn't assume that the reference sets are the same.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void CompilationReferences_Less()
{
// Add some references that are actually not used in the source.
// The only actual reference stored in the metadata image would be: mscorlib (rowid 1).
// If we incorrectly assume the references are the same we will map TypeRefs of
// Mscorlib to System.Windows.Forms.
var references = new[] { SystemWindowsFormsRef, MscorlibRef, SystemCoreRef };
string src1 = @"
using System;
using System.Threading.Tasks;
class C
{
public Task<int> F() { Console.WriteLine(123); return null; }
public static void Main() { Console.WriteLine(1); }
}
";
string src2 = @"
using System;
using System.Threading.Tasks;
class C
{
public Task<int> F() { Console.WriteLine(123); return null; }
public static void Main() { Console.WriteLine(2); }
}
";
var c1 = CreateEmptyCompilation(src1, references);
var c2 = c1.WithSource(src2);
var md1 = AssemblyMetadata.CreateFromStream(c1.EmitToStream());
var baseline = EmitBaseline.CreateInitialBaseline(md1.GetModules()[0], handle => default(EditAndContinueMethodDebugInformation));
var mdStream = new MemoryStream();
var ilStream = new MemoryStream();
var pdbStream = new MemoryStream();
var updatedMethods = new List<MethodDefinitionHandle>();
var edits = new[]
{
SemanticEdit.Create(
SemanticEditKind.Update,
c1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"),
c2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"))
};
c2.EmitDifference(baseline, edits, s => false, mdStream, ilStream, pdbStream);
var actualIL = ImmutableArray.Create(ilStream.ToArray()).GetMethodIL();
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldc.i4.2
IL_0001: call 0x0A000006
IL_0006: ret
}";
// If the references are mismatched then the symbol matcher won't be able to find Task<T>
// and will recompile the method body of F (even though the method hasn't changed).
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL);
}
/// <summary>
/// The baseline metadata might have more references than the current compilation.
/// References that aren't found in the compilation are treated as missing.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void CompilationReferences_More()
{
string src1 = @"
using System;
class C
{
public static int F(object a) { return 1; }
public static void Main() { Console.WriteLine(F(null)); }
}
";
string src2 = @"
using System;
class C
{
public static int F(object a) { return 1; }
public static void Main() { F(null); }
}
";
// Let's say an IL rewriter inserts a new overload of F that references
// a type in a new AssemblyRef.
string srcPE = @"
using System;
class C
{
public static int F(System.Diagnostics.Process a) { return 2; }
public static int F(object a) { return 1; }
public static void Main() { F(null); }
}
";
var md1 = AssemblyMetadata.CreateFromStream(CreateEmptyCompilation(srcPE, new[] { MscorlibRef, SystemRef }).EmitToStream());
var c1 = CreateEmptyCompilation(src1, new[] { MscorlibRef });
var c2 = c1.WithSource(src2);
var baseline = EmitBaseline.CreateInitialBaseline(md1.GetModules()[0], handle => default(EditAndContinueMethodDebugInformation));
var mdStream = new MemoryStream();
var ilStream = new MemoryStream();
var pdbStream = new MemoryStream();
var updatedMethods = new List<MethodDefinitionHandle>();
var edits = new[]
{
SemanticEdit.Create(
SemanticEditKind.Update,
c1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"),
c2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"))
};
c2.EmitDifference(baseline, edits, s => false, mdStream, ilStream, pdbStream);
var actualIL = ImmutableArray.Create(ilStream.ToArray()).GetMethodIL();
// Symbol matcher should ignore overloads with missing type symbols and match
// F(object).
var expectedIL = @"
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldnull
IL_0001: call 0x06000002
IL_0006: pop
IL_0007: ret
}";
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL);
}
/// <summary>
/// Symbol matcher considers two source types that only differ in the declaring compilations different.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void ChangingCompilationDependencies()
{
string srcLib = @"
public class D { }
";
string src0 = @"
class C
{
public static int F(D a) { return 1; }
}
";
string src1 = @"
class C
{
public static int F(D a) { return 2; }
}
";
string src2 = @"
class C
{
public static int F(D a) { return 3; }
}
";
var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
lib0.VerifyDiagnostics();
var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
lib1.VerifyDiagnostics();
var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
lib2.VerifyDiagnostics();
var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.ToMetadataReference() }, assemblyName: "C", options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.ToMetadataReference() });
var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.ToMetadataReference() });
var v0 = CompileAndVerify(compilation0);
var v1 = CompileAndVerify(compilation1);
var v2 = CompileAndVerify(compilation2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
diff1.EmitResult.Diagnostics.Verify();
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2)));
diff2.EmitResult.Diagnostics.Verify();
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void DependencyVersionWildcards_Compilation()
{
TestDependencyVersionWildcards(
"1.0.0.*",
new Version(1, 0, 2000, 1001),
new Version(1, 0, 2000, 1001),
new Version(1, 0, 2000, 1002));
TestDependencyVersionWildcards(
"1.0.0.*",
new Version(1, 0, 2000, 1001),
new Version(1, 0, 2000, 1002),
new Version(1, 0, 2000, 1002));
TestDependencyVersionWildcards(
"1.0.0.*",
new Version(1, 0, 2000, 1003),
new Version(1, 0, 2000, 1002),
new Version(1, 0, 2000, 1001));
TestDependencyVersionWildcards(
"1.0.*",
new Version(1, 0, 2000, 1001),
new Version(1, 0, 2000, 1002),
new Version(1, 0, 2000, 1003));
TestDependencyVersionWildcards(
"1.0.*",
new Version(1, 0, 2000, 1001),
new Version(1, 0, 2000, 1005),
new Version(1, 0, 2000, 1002));
}
private void TestDependencyVersionWildcards(string sourceVersion, Version version0, Version version1, Version version2)
{
string srcLib = $@"
[assembly: System.Reflection.AssemblyVersion(""{sourceVersion}"")]
public class D {{ }}
";
string src0 = @"
class C
{
public static int F(D a) { return 1; }
}
";
string src1 = @"
class C
{
public static int F(D a) { return 2; }
}
";
string src2 = @"
class C
{
public static int F(D a) { return 3; }
public static int G(D a) { return 4; }
}
";
var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version0);
lib0.VerifyDiagnostics();
var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version1);
lib1.VerifyDiagnostics();
var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version2);
lib2.VerifyDiagnostics();
var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.ToMetadataReference() }, assemblyName: "C", options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.ToMetadataReference() });
var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.ToMetadataReference() });
var v0 = CompileAndVerify(compilation0);
var v1 = CompileAndVerify(compilation1);
var v2 = CompileAndVerify(compilation2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2),
SemanticEdit.Create(SemanticEditKind.Insert, null, g2)));
var md1 = diff1.GetMetadata();
var md2 = diff2.GetMetadata();
var aggReader = new AggregatedMetadataReader(md0.MetadataReader, md1.Reader, md2.Reader);
// all references to Lib should be to the baseline version:
VerifyAssemblyReferences(aggReader, new[]
{
"mscorlib, 4.0.0.0",
"Lib, " + lib0.Assembly.Identity.Version,
"mscorlib, 4.0.0.0",
"Lib, " + lib0.Assembly.Identity.Version,
"mscorlib, 4.0.0.0",
"Lib, " + lib0.Assembly.Identity.Version,
});
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void DependencyVersionWildcards_Metadata()
{
string srcLib = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.*"")]
public class D { }
";
string src0 = @"
class C
{
public static int F(D a) { return 1; }
}
";
string src1 = @"
class C
{
public static int F(D a) { return 2; }
}
";
string src2 = @"
class C
{
public static int F(D a) { return 3; }
public static int G(D a) { return 4; }
}
";
var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1001));
lib0.VerifyDiagnostics();
var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1002));
lib1.VerifyDiagnostics();
var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1003));
lib2.VerifyDiagnostics();
var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.EmitToImageReference() }, assemblyName: "C", options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.EmitToImageReference() });
var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.EmitToImageReference() });
var v0 = CompileAndVerify(compilation0);
var v1 = CompileAndVerify(compilation1);
var v2 = CompileAndVerify(compilation2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7038: Failed to emit module 'C': Changing the version of an assembly reference is not allowed during debugging:
// 'Lib, Version=1.0.2000.1001, Culture=neutral, PublicKeyToken=null' changed version to '1.0.2000.1002'.
Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C",
string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging,
"Lib, Version=1.0.2000.1001, Culture=neutral, PublicKeyToken=null", "1.0.2000.1002")));
}
[WorkItem(9004, "https://github.com/dotnet/roslyn/issues/9004")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void DependencyVersionWildcardsCollisions()
{
string srcLib01 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.1"")]
public class D { }
";
string srcLib02 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.2"")]
public class D { }
";
string srcLib11 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.1.1"")]
public class D { }
";
string srcLib12 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.1.2"")]
public class D { }
";
string src0 = @"
extern alias L0;
extern alias L1;
class C
{
public static int F(L0::D a, L1::D b) => 1;
}
";
string src1 = @"
extern alias L0;
extern alias L1;
class C
{
public static int F(L0::D a, L1::D b) => 2;
}
";
var lib01 = CreateCompilation(srcLib01, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
var ref01 = lib01.ToMetadataReference(ImmutableArray.Create("L0"));
var lib02 = CreateCompilation(srcLib02, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
var ref02 = lib02.ToMetadataReference(ImmutableArray.Create("L0"));
var lib11 = CreateCompilation(srcLib11, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
var ref11 = lib11.ToMetadataReference(ImmutableArray.Create("L1"));
var lib12 = CreateCompilation(srcLib12, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
var ref12 = lib12.ToMetadataReference(ImmutableArray.Create("L1"));
var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, ref01, ref11 }, assemblyName: "C", options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, ref02, ref12 });
var v0 = CompileAndVerify(compilation0);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7038: Failed to emit module 'C': Changing the version of an assembly reference is not allowed during debugging:
// 'Lib, Version=1.0.0.1, Culture=neutral, PublicKeyToken=null' changed version to '1.0.0.2'.
Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C",
string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging,
"Lib, Version=1.0.0.1, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "1.0.0.2")));
}
private void VerifyAssemblyReferences(AggregatedMetadataReader reader, string[] expected)
{
AssertEx.Equal(expected, reader.GetAssemblyReferences().Select(aref => $"{reader.GetString(aref.Name)}, {aref.Version}"));
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
[WorkItem(202017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/202017")]
public void CurrentCompilationVersionWildcards()
{
var source0 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]
class C
{
static void M()
{
new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
}
static void F()
{
}
}");
var source1 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]
class C
{
static void M()
{
new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke();
}
static void F()
{
}
}");
var source2 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]
class C
{
static void M()
{
new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke();
}
static void F()
{
Console.WriteLine(1);
}
}");
var source3 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]
class C
{
static void M()
{
new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke();
new Action(<N:2>() => { Console.WriteLine(3); }</N:2>).Invoke();
new Action(<N:3>() => { Console.WriteLine(4); }</N:3>).Invoke();
}
static void F()
{
Console.WriteLine(1);
}
}");
var options = ComSafeDebugDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2);
var compilation0 = CreateCompilation(source0.Tree, options: options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 0)));
var compilation1 = compilation0.WithSource(source1.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 10)));
var compilation2 = compilation1.WithSource(source2.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 20)));
var compilation3 = compilation2.WithSource(source3.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 30)));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var m0 = compilation0.GetMember<MethodSymbol>("C.M");
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var m3 = compilation3.GetMember<MethodSymbol>("C.M");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// First update adds some new synthesized members (lambda related)
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <M>b__0_0, <M>b__0_1#1}");
// Second update is to a method that doesn't produce any synthesized members
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <M>b__0_0, <M>b__0_1#1}");
// Last update again adds some new synthesized members (lambdas).
// Synthesized members added in the first update need to be mapped to the current compilation.
// Their containing assembly version is different than the version of the previous assembly and
// hence we need to account for wildcards when comparing the versions.
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m2, m3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <>9__0_2#3, <>9__0_3#3, <M>b__0_0, <M>b__0_1#1, <M>b__0_2#3, <M>b__0_3#3}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.MetadataUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
public class AssemblyReferencesTests : EditAndContinueTestBase
{
private static readonly CSharpCompilationOptions s_signedDll =
TestOptions.ReleaseDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2);
/// <summary>
/// The baseline metadata might have less (or even different) references than
/// the current compilation. We shouldn't assume that the reference sets are the same.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void CompilationReferences_Less()
{
// Add some references that are actually not used in the source.
// The only actual reference stored in the metadata image would be: mscorlib (rowid 1).
// If we incorrectly assume the references are the same we will map TypeRefs of
// Mscorlib to System.Windows.Forms.
var references = new[] { SystemWindowsFormsRef, MscorlibRef, SystemCoreRef };
string src1 = @"
using System;
using System.Threading.Tasks;
class C
{
public Task<int> F() { Console.WriteLine(123); return null; }
public static void Main() { Console.WriteLine(1); }
}
";
string src2 = @"
using System;
using System.Threading.Tasks;
class C
{
public Task<int> F() { Console.WriteLine(123); return null; }
public static void Main() { Console.WriteLine(2); }
}
";
var c1 = CreateEmptyCompilation(src1, references);
var c2 = c1.WithSource(src2);
var md1 = AssemblyMetadata.CreateFromStream(c1.EmitToStream());
var baseline = EmitBaseline.CreateInitialBaseline(md1.GetModules()[0], handle => default(EditAndContinueMethodDebugInformation));
var mdStream = new MemoryStream();
var ilStream = new MemoryStream();
var pdbStream = new MemoryStream();
var updatedMethods = new List<MethodDefinitionHandle>();
var edits = new[]
{
SemanticEdit.Create(
SemanticEditKind.Update,
c1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"),
c2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"))
};
c2.EmitDifference(baseline, edits, s => false, mdStream, ilStream, pdbStream);
var actualIL = ImmutableArray.Create(ilStream.ToArray()).GetMethodIL();
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldc.i4.2
IL_0001: call 0x0A000006
IL_0006: ret
}";
// If the references are mismatched then the symbol matcher won't be able to find Task<T>
// and will recompile the method body of F (even though the method hasn't changed).
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL);
}
/// <summary>
/// The baseline metadata might have more references than the current compilation.
/// References that aren't found in the compilation are treated as missing.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void CompilationReferences_More()
{
string src1 = @"
using System;
class C
{
public static int F(object a) { return 1; }
public static void Main() { Console.WriteLine(F(null)); }
}
";
string src2 = @"
using System;
class C
{
public static int F(object a) { return 1; }
public static void Main() { F(null); }
}
";
// Let's say an IL rewriter inserts a new overload of F that references
// a type in a new AssemblyRef.
string srcPE = @"
using System;
class C
{
public static int F(System.Diagnostics.Process a) { return 2; }
public static int F(object a) { return 1; }
public static void Main() { F(null); }
}
";
var md1 = AssemblyMetadata.CreateFromStream(CreateEmptyCompilation(srcPE, new[] { MscorlibRef, SystemRef }).EmitToStream());
var c1 = CreateEmptyCompilation(src1, new[] { MscorlibRef });
var c2 = c1.WithSource(src2);
var baseline = EmitBaseline.CreateInitialBaseline(md1.GetModules()[0], handle => default(EditAndContinueMethodDebugInformation));
var mdStream = new MemoryStream();
var ilStream = new MemoryStream();
var pdbStream = new MemoryStream();
var updatedMethods = new List<MethodDefinitionHandle>();
var edits = new[]
{
SemanticEdit.Create(
SemanticEditKind.Update,
c1.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"),
c2.GlobalNamespace.GetMember<NamedTypeSymbol>("C").GetMember("Main"))
};
c2.EmitDifference(baseline, edits, s => false, mdStream, ilStream, pdbStream);
var actualIL = ImmutableArray.Create(ilStream.ToArray()).GetMethodIL();
// Symbol matcher should ignore overloads with missing type symbols and match
// F(object).
var expectedIL = @"
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldnull
IL_0001: call 0x06000002
IL_0006: pop
IL_0007: ret
}";
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL);
}
/// <summary>
/// Symbol matcher considers two source types that only differ in the declaring compilations different.
/// </summary>
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void ChangingCompilationDependencies()
{
string srcLib = @"
public class D { }
";
string src0 = @"
class C
{
public static int F(D a) { return 1; }
}
";
string src1 = @"
class C
{
public static int F(D a) { return 2; }
}
";
string src2 = @"
class C
{
public static int F(D a) { return 3; }
}
";
var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
lib0.VerifyDiagnostics();
var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
lib1.VerifyDiagnostics();
var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
lib2.VerifyDiagnostics();
var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.ToMetadataReference() }, assemblyName: "C", options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.ToMetadataReference() });
var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.ToMetadataReference() });
var v0 = CompileAndVerify(compilation0);
var v1 = CompileAndVerify(compilation1);
var v2 = CompileAndVerify(compilation2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
diff1.EmitResult.Diagnostics.Verify();
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2)));
diff2.EmitResult.Diagnostics.Verify();
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void DependencyVersionWildcards_Compilation()
{
TestDependencyVersionWildcards(
"1.0.0.*",
new Version(1, 0, 2000, 1001),
new Version(1, 0, 2000, 1001),
new Version(1, 0, 2000, 1002));
TestDependencyVersionWildcards(
"1.0.0.*",
new Version(1, 0, 2000, 1001),
new Version(1, 0, 2000, 1002),
new Version(1, 0, 2000, 1002));
TestDependencyVersionWildcards(
"1.0.0.*",
new Version(1, 0, 2000, 1003),
new Version(1, 0, 2000, 1002),
new Version(1, 0, 2000, 1001));
TestDependencyVersionWildcards(
"1.0.*",
new Version(1, 0, 2000, 1001),
new Version(1, 0, 2000, 1002),
new Version(1, 0, 2000, 1003));
TestDependencyVersionWildcards(
"1.0.*",
new Version(1, 0, 2000, 1001),
new Version(1, 0, 2000, 1005),
new Version(1, 0, 2000, 1002));
}
private void TestDependencyVersionWildcards(string sourceVersion, Version version0, Version version1, Version version2)
{
string srcLib = $@"
[assembly: System.Reflection.AssemblyVersion(""{sourceVersion}"")]
public class D {{ }}
";
string src0 = @"
class C
{
public static int F(D a) { return 1; }
}
";
string src1 = @"
class C
{
public static int F(D a) { return 2; }
}
";
string src2 = @"
class C
{
public static int F(D a) { return 3; }
public static int G(D a) { return 4; }
}
";
var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version0);
lib0.VerifyDiagnostics();
var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version1);
lib1.VerifyDiagnostics();
var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", version2);
lib2.VerifyDiagnostics();
var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.ToMetadataReference() }, assemblyName: "C", options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.ToMetadataReference() });
var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.ToMetadataReference() });
var v0 = CompileAndVerify(compilation0);
var v1 = CompileAndVerify(compilation1);
var v2 = CompileAndVerify(compilation2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2),
SemanticEdit.Create(SemanticEditKind.Insert, null, g2)));
var md1 = diff1.GetMetadata();
var md2 = diff2.GetMetadata();
var aggReader = new AggregatedMetadataReader(md0.MetadataReader, md1.Reader, md2.Reader);
// all references to Lib should be to the baseline version:
VerifyAssemblyReferences(aggReader, new[]
{
"mscorlib, 4.0.0.0",
"Lib, " + lib0.Assembly.Identity.Version,
"mscorlib, 4.0.0.0",
"Lib, " + lib0.Assembly.Identity.Version,
"mscorlib, 4.0.0.0",
"Lib, " + lib0.Assembly.Identity.Version,
});
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void DependencyVersionWildcards_Metadata()
{
string srcLib = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.*"")]
public class D { }
";
string src0 = @"
class C
{
public static int F(D a) { return 1; }
}
";
string src1 = @"
class C
{
public static int F(D a) { return 2; }
}
";
string src2 = @"
class C
{
public static int F(D a) { return 3; }
public static int G(D a) { return 4; }
}
";
var lib0 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib0.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1001));
lib0.VerifyDiagnostics();
var lib1 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib1.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1002));
lib1.VerifyDiagnostics();
var lib2 = CreateCompilation(srcLib, assemblyName: "Lib", options: TestOptions.DebugDll);
((SourceAssemblySymbol)lib2.Assembly).lazyAssemblyIdentity = new AssemblyIdentity("Lib", new Version(1, 0, 2000, 1003));
lib2.VerifyDiagnostics();
var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, lib0.EmitToImageReference() }, assemblyName: "C", options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, lib1.EmitToImageReference() });
var compilation2 = compilation1.WithSource(src2).WithReferences(new[] { MscorlibRef, lib2.EmitToImageReference() });
var v0 = CompileAndVerify(compilation0);
var v1 = CompileAndVerify(compilation1);
var v2 = CompileAndVerify(compilation2);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var g2 = compilation2.GetMember<MethodSymbol>("C.G");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7038: Failed to emit module 'C': Changing the version of an assembly reference is not allowed during debugging:
// 'Lib, Version=1.0.2000.1001, Culture=neutral, PublicKeyToken=null' changed version to '1.0.2000.1002'.
Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C",
string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging,
"Lib, Version=1.0.2000.1001, Culture=neutral, PublicKeyToken=null", "1.0.2000.1002")));
}
[WorkItem(9004, "https://github.com/dotnet/roslyn/issues/9004")]
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void DependencyVersionWildcardsCollisions()
{
string srcLib01 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.1"")]
public class D { }
";
string srcLib02 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.0.2"")]
public class D { }
";
string srcLib11 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.1.1"")]
public class D { }
";
string srcLib12 = @"
[assembly: System.Reflection.AssemblyVersion(""1.0.1.2"")]
public class D { }
";
string src0 = @"
extern alias L0;
extern alias L1;
class C
{
public static int F(L0::D a, L1::D b) => 1;
}
";
string src1 = @"
extern alias L0;
extern alias L1;
class C
{
public static int F(L0::D a, L1::D b) => 2;
}
";
var lib01 = CreateCompilation(srcLib01, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
var ref01 = lib01.ToMetadataReference(ImmutableArray.Create("L0"));
var lib02 = CreateCompilation(srcLib02, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
var ref02 = lib02.ToMetadataReference(ImmutableArray.Create("L0"));
var lib11 = CreateCompilation(srcLib11, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
var ref11 = lib11.ToMetadataReference(ImmutableArray.Create("L1"));
var lib12 = CreateCompilation(srcLib12, assemblyName: "Lib", options: s_signedDll).VerifyDiagnostics();
var ref12 = lib12.ToMetadataReference(ImmutableArray.Create("L1"));
var compilation0 = CreateEmptyCompilation(src0, new[] { MscorlibRef, ref01, ref11 }, assemblyName: "C", options: TestOptions.DebugDll);
var compilation1 = compilation0.WithSource(src1).WithReferences(new[] { MscorlibRef, ref02, ref12 });
var v0 = CompileAndVerify(compilation0);
var f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1)));
diff1.EmitResult.Diagnostics.Verify(
// error CS7038: Failed to emit module 'C': Changing the version of an assembly reference is not allowed during debugging:
// 'Lib, Version=1.0.0.1, Culture=neutral, PublicKeyToken=null' changed version to '1.0.0.2'.
Diagnostic(ErrorCode.ERR_ModuleEmitFailure).WithArguments("C",
string.Format(CodeAnalysisResources.ChangingVersionOfAssemblyReferenceIsNotAllowedDuringDebugging,
"Lib, Version=1.0.0.1, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "1.0.0.2")));
}
private void VerifyAssemblyReferences(AggregatedMetadataReader reader, string[] expected)
{
AssertEx.Equal(expected, reader.GetAssemblyReferences().Select(aref => $"{reader.GetString(aref.Name)}, {aref.Version}"));
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
[WorkItem(202017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/202017")]
public void CurrentCompilationVersionWildcards()
{
var source0 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]
class C
{
static void M()
{
new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
}
static void F()
{
}
}");
var source1 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]
class C
{
static void M()
{
new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke();
}
static void F()
{
}
}");
var source2 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]
class C
{
static void M()
{
new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke();
}
static void F()
{
Console.WriteLine(1);
}
}");
var source3 = MarkedSource(@"
using System;
[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]
class C
{
static void M()
{
new Action(<N:0>() => { Console.WriteLine(1); }</N:0>).Invoke();
new Action(<N:1>() => { Console.WriteLine(2); }</N:1>).Invoke();
new Action(<N:2>() => { Console.WriteLine(3); }</N:2>).Invoke();
new Action(<N:3>() => { Console.WriteLine(4); }</N:3>).Invoke();
}
static void F()
{
Console.WriteLine(1);
}
}");
var options = ComSafeDebugDll.WithCryptoPublicKey(TestResources.TestKeys.PublicKey_ce65828c82a341f2);
var compilation0 = CreateCompilation(source0.Tree, options: options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 0)));
var compilation1 = compilation0.WithSource(source1.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 10)));
var compilation2 = compilation1.WithSource(source2.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 20)));
var compilation3 = compilation2.WithSource(source3.Tree).WithOptions(options.WithCurrentLocalTime(new DateTime(2016, 1, 1, 1, 0, 30)));
var v0 = CompileAndVerify(compilation0, verify: Verification.Passes);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
var m0 = compilation0.GetMember<MethodSymbol>("C.M");
var m1 = compilation1.GetMember<MethodSymbol>("C.M");
var m2 = compilation2.GetMember<MethodSymbol>("C.M");
var m3 = compilation3.GetMember<MethodSymbol>("C.M");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
// First update adds some new synthesized members (lambda related)
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <M>b__0_0, <M>b__0_1#1}");
// Second update is to a method that doesn't produce any synthesized members
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <M>b__0_0, <M>b__0_1#1}");
// Last update again adds some new synthesized members (lambdas).
// Synthesized members added in the first update need to be mapped to the current compilation.
// Their containing assembly version is different than the version of the previous assembly and
// hence we need to account for wildcards when comparing the versions.
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m2, m3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <>9__0_2#3, <>9__0_3#3, <M>b__0_0, <M>b__0_1#1, <M>b__0_2#3, <M>b__0_3#3}");
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Tools/IdeCoreBenchmarks/Assets/Microsoft.CodeAnalysis.sln |
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30030.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis", "..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj", "{7B3C638D-D43E-4346-ACAC-56ACCE13B500}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
..\..\..\Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems*{7b3c638d-d43e-4346-acac-56acce13b500}*SharedItemsImports = 5
..\..\..\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.projitems*{7b3c638d-d43e-4346-acac-56acce13b500}*SharedItemsImports = 5
..\..\..\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{7b3c638d-d43e-4346-acac-56acce13b500}*SharedItemsImports = 5
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7B3C638D-D43E-4346-ACAC-56ACCE13B500}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7B3C638D-D43E-4346-ACAC-56ACCE13B500}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7B3C638D-D43E-4346-ACAC-56ACCE13B500}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7B3C638D-D43E-4346-ACAC-56ACCE13B500}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1A659683-1C0B-4A31-93C6-08B9E9D97170}
EndGlobalSection
EndGlobal
|
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30030.7
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.CodeAnalysis", "..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj", "{7B3C638D-D43E-4346-ACAC-56ACCE13B500}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
..\..\..\Compilers\Core\AnalyzerDriver\AnalyzerDriver.projitems*{7b3c638d-d43e-4346-acac-56acce13b500}*SharedItemsImports = 5
..\..\..\Dependencies\CodeAnalysis.Debugging\Microsoft.CodeAnalysis.Debugging.projitems*{7b3c638d-d43e-4346-acac-56acce13b500}*SharedItemsImports = 5
..\..\..\Dependencies\PooledObjects\Microsoft.CodeAnalysis.PooledObjects.projitems*{7b3c638d-d43e-4346-acac-56acce13b500}*SharedItemsImports = 5
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7B3C638D-D43E-4346-ACAC-56ACCE13B500}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7B3C638D-D43E-4346-ACAC-56ACCE13B500}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7B3C638D-D43E-4346-ACAC-56ACCE13B500}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7B3C638D-D43E-4346-ACAC-56ACCE13B500}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1A659683-1C0B-4A31-93C6-08B9E9D97170}
EndGlobalSection
EndGlobal
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Analyzers/Core/Analyzers/xlf/AnalyzersResources.zh-Hant.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../AnalyzersResources.resx">
<body>
<trans-unit id="A_source_file_contains_a_header_that_does_not_match_the_required_text">
<source>A source file contains a header that does not match the required text</source>
<target state="translated">來源檔案包含的標頭與必要文字不相符</target>
<note />
</trans-unit>
<trans-unit id="A_source_file_is_missing_a_required_header">
<source>A source file is missing a required header.</source>
<target state="translated">來源檔案缺少必要標頭。</target>
<note />
</trans-unit>
<trans-unit id="Accessibility_modifiers_required">
<source>Accessibility modifiers required</source>
<target state="translated">協助工具修飾元為必要項</target>
<note />
</trans-unit>
<trans-unit id="Add_accessibility_modifiers">
<source>Add accessibility modifiers</source>
<target state="translated">新增協助工具修飾元</target>
<note />
</trans-unit>
<trans-unit id="Add_parentheses_for_clarity">
<source>Add parentheses for clarity</source>
<target state="translated">新增括號以明確表示</target>
<note />
</trans-unit>
<trans-unit id="Add_readonly_modifier">
<source>Add readonly modifier</source>
<target state="translated">新增唯讀修飾元</target>
<note />
</trans-unit>
<trans-unit id="Add_this_or_Me_qualification">
<source>Add 'this' or 'Me' qualification.</source>
<target state="translated">新增 'this' 或 'Me' 限定性條件。</target>
<note />
</trans-unit>
<trans-unit id="Avoid_legacy_format_target_0_in_SuppressMessageAttribute">
<source>Avoid legacy format target '{0}' in 'SuppressMessageAttribute'</source>
<target state="translated">避免在 'SuppressMessageAttribute' 中使用舊版格式目標 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Avoid_legacy_format_target_in_SuppressMessageAttribute">
<source>Avoid legacy format target in 'SuppressMessageAttribute'</source>
<target state="translated">避免在 'SuppressMessageAttribute' 中使用舊版格式目標</target>
<note />
</trans-unit>
<trans-unit id="Avoid_multiple_blank_lines">
<source>Avoid multiple blank lines</source>
<target state="translated">避免多個空白行</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unnecessary_value_assignments_in_your_code_as_these_likely_indicate_redundant_value_computations_If_the_value_computation_is_not_redundant_and_you_intend_to_retain_the_assignmentcomma_then_change_the_assignment_target_to_a_local_variable_whose_name_starts_with_an_underscore_and_is_optionally_followed_by_an_integercomma_such_as___comma__1_comma__2_comma_etc">
<source>Avoid unnecessary value assignments in your code, as these likely indicate redundant value computations. If the value computation is not redundant and you intend to retain the assignment, then change the assignment target to a local variable whose name starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source>
<target state="translated">請避免在您的程式碼中指派非必要的值,因為這可能表示值會重複計算。如果值未重複計算,而且您想要保留指派,請將指派目標變更為名稱以底線開頭的區域變數,並可選擇在後面接著整數,例如 '_'、'_1'、'_2' 等。這些會視為特殊的捨棄符號名稱。</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unused_parameters_in_your_code_If_the_parameter_cannot_be_removed_then_change_its_name_so_it_starts_with_an_underscore_and_is_optionally_followed_by_an_integer_such_as__comma__1_comma__2_etc_These_are_treated_as_special_discard_symbol_names">
<source>Avoid unused parameters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source>
<target state="translated">請避免在您的程式碼中使用參數。如果無法移除參數,請變更其名稱,使其以底線開頭,並可選擇在後面接著整數,例如 '_'、'_1'、'_2' 等。這些會視為特殊的捨棄符號名稱。</target>
<note />
</trans-unit>
<trans-unit id="Blank_line_required_between_block_and_subsequent_statement">
<source>Blank line required between block and subsequent statement</source>
<target state="translated">區塊與後續陳述式之間必須有空白行</target>
<note />
</trans-unit>
<trans-unit id="Change_namespace_to_match_folder_structure">
<source>Change namespace to match folder structure</source>
<target state="translated">變更 namespace 以符合資料夾結構</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime">
<source>Changes to expression trees may result in behavior changes at runtime</source>
<target state="translated">變更運算式樹狀架構可能會導致執行階段的行為變更</target>
<note />
</trans-unit>
<trans-unit id="Conditional_expression_can_be_simplified">
<source>Conditional expression can be simplified</source>
<target state="translated">條件運算式可加以簡化</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_conditional_expression">
<source>Convert to conditional expression</source>
<target state="translated">轉換至條件運算式</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_tuple">
<source>Convert to tuple</source>
<target state="translated">轉換為元組</target>
<note />
</trans-unit>
<trans-unit id="Expression_value_is_never_used">
<source>Expression value is never used</source>
<target state="translated">永遠不會使用運算式值</target>
<note />
</trans-unit>
<trans-unit id="Collection_initialization_can_be_simplified">
<source>Collection initialization can be simplified</source>
<target state="translated">集合初始化可簡化</target>
<note />
</trans-unit>
<trans-unit id="Format_string_contains_invalid_placeholder">
<source>Format string contains invalid placeholder</source>
<target state="translated">格式字串包含無效的預留位置</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">'GetHashCode' 實作可簡化</target>
<note />
</trans-unit>
<trans-unit id="Interpolation_can_be_simplified">
<source>Interpolation can be simplified</source>
<target state="translated">可簡化內插補點</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="translated">格式字串無效</target>
<note />
</trans-unit>
<trans-unit id="Invalid_global_SuppressMessageAttribute">
<source>Invalid global 'SuppressMessageAttribute'</source>
<target state="translated">全域 'SuppressMessageAttribute' 無效</target>
<note />
</trans-unit>
<trans-unit id="Invalid_or_missing_target_for_SuppressMessageAttribute">
<source>Invalid or missing target for 'SuppressMessageAttribute'</source>
<target state="translated">'SuppressMessageAttribute' 缺少目標或其無效</target>
<note />
</trans-unit>
<trans-unit id="Invalid_scope_for_SuppressMessageAttribute">
<source>Invalid scope for 'SuppressMessageAttribute'</source>
<target state="translated">'SuppressMessageAttribute' 的範圍無效</target>
<note />
</trans-unit>
<trans-unit id="Make_field_readonly">
<source>Make field readonly</source>
<target state="translated">使欄位唯讀</target>
<note />
</trans-unit>
<trans-unit id="Member_access_should_be_qualified">
<source>Member access should be qualified.</source>
<target state="translated">必須限定成員存取。</target>
<note />
</trans-unit>
<trans-unit id="Add_missing_cases">
<source>Add missing cases</source>
<target state="translated">新增遺漏的案例</target>
<note />
</trans-unit>
<trans-unit id="Member_name_can_be_simplified">
<source>Member name can be simplified</source>
<target state="translated">成員名稱可簡化</target>
<note />
</trans-unit>
<trans-unit id="Modifiers_are_not_ordered">
<source>Modifiers are not ordered</source>
<target state="translated">修飾元未排序</target>
<note />
</trans-unit>
<trans-unit id="Namespace_0_does_not_match_folder_structure_expected_1">
<source>Namespace "{0}" does not match folder structure, expected "{1}"</source>
<target state="translated">命名空間 "{0}" 與資料夾結構不相符,必須為 "{1}"</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Namespace_does_not_match_folder_structure">
<source>Namespace does not match folder structure</source>
<target state="translated">命名空間與資料夾結構不相符</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Naming_Styles">
<source>Naming Styles</source>
<target state="translated">命名樣式</target>
<note />
</trans-unit>
<trans-unit id="Naming_rule_violation_0">
<source>Naming rule violation: {0}</source>
<target state="translated">違反命名規則: {0}</target>
<note>{0} is the rule title, {1} is the way in which the rule was violated</note>
</trans-unit>
<trans-unit id="Null_check_can_be_simplified">
<source>Null check can be simplified</source>
<target state="translated">Null 檢查可簡化</target>
<note />
</trans-unit>
<trans-unit id="Order_modifiers">
<source>Order modifiers</source>
<target state="translated">為修飾元排序</target>
<note />
</trans-unit>
<trans-unit id="Parameter_0_can_be_removed_if_it_is_not_part_of_a_shipped_public_API_its_initial_value_is_never_used">
<source>Parameter '{0}' can be removed if it is not part of a shipped public API; its initial value is never used</source>
<target state="translated">若參數 '{0}' 不屬於已經出貨的公用 API,將無法移除; 其初始值一律不會使用</target>
<note />
</trans-unit>
<trans-unit id="Parameter_0_can_be_removed_its_initial_value_is_never_used">
<source>Parameter '{0}' can be removed; its initial value is never used</source>
<target state="translated">參數 '{0}' 可以移除; 其初始值一律不會使用</target>
<note />
</trans-unit>
<trans-unit id="Object_initialization_can_be_simplified">
<source>Object initialization can be simplified</source>
<target state="translated">物件初始化可以簡化</target>
<note />
</trans-unit>
<trans-unit id="Parentheses_can_be_removed">
<source>Parentheses can be removed</source>
<target state="translated">可以移除括號</target>
<note />
</trans-unit>
<trans-unit id="Parentheses_should_be_added_for_clarity">
<source>Parentheses should be added for clarity</source>
<target state="translated">應新增括號以明確表示</target>
<note />
</trans-unit>
<trans-unit id="Populate_switch">
<source>Populate switch</source>
<target state="translated">填入切換</target>
<note />
</trans-unit>
<trans-unit id="Prefer_explicitly_provided_tuple_element_name">
<source>Prefer explicitly provided tuple element name</source>
<target state="translated">建議使用明確提供的元組元素名稱</target>
<note />
</trans-unit>
<trans-unit id="Private_member_0_can_be_removed_as_the_value_assigned_to_it_is_never_read">
<source>Private member '{0}' can be removed as the value assigned to it is never read</source>
<target state="translated">因為永遠不會讀取指派給 Private 成員 '{0}' 的值,所以可移除該成員</target>
<note />
</trans-unit>
<trans-unit id="Private_member_0_is_unused">
<source>Private member '{0}' is unused</source>
<target state="translated">未使用 Private 成員 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Private_method_0_can_be_removed_as_it_is_never_invoked">
<source>Private method '{0}' can be removed as it is never invoked.</source>
<target state="translated">因為永遠不會叫用私用方法 ‘{0}’,所以可予以移除。</target>
<note />
</trans-unit>
<trans-unit id="Private_property_0_can_be_converted_to_a_method_as_its_get_accessor_is_never_invoked">
<source>Private property '{0}' can be converted to a method as its get accessor is never invoked.</source>
<target state="translated">系統永遠不會叫用私用屬性 '{0}' 的 get 存取子,因此該屬性可以轉換成方法。</target>
<note />
</trans-unit>
<trans-unit id="Remove_Unnecessary_Cast">
<source>Remove Unnecessary Cast</source>
<target state="translated">移除不必要的 Cast</target>
<note />
</trans-unit>
<trans-unit id="Remove_redundant_equality">
<source>Remove redundant equality</source>
<target state="translated">移除多餘的等號</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_parentheses">
<source>Remove unnecessary parentheses</source>
<target state="translated">移除不必要的括號</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_suppression">
<source>Remove unnecessary suppression</source>
<target state="translated">移除非必要的隱藏項目</target>
<note />
</trans-unit>
<trans-unit id="Remove_unread_private_members">
<source>Remove unread private members</source>
<target state="translated">刪除未讀取的私用成員</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_member">
<source>Remove unused member</source>
<target state="translated">移除未使用的成員</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter">
<source>Remove unused parameter</source>
<target state="translated">移除未使用的參數</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter_0">
<source>Remove unused parameter '{0}'</source>
<target state="translated">移除未使用的參數 ‘{0}’</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter_0_if_it_is_not_part_of_a_shipped_public_API">
<source>Remove unused parameter '{0}' if it is not part of a shipped public API</source>
<target state="translated">如果未使用的參數 ‘{0}’ 不屬於已發行的公用 API,請予以移除</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_private_members">
<source>Remove unused private members</source>
<target state="translated">刪除未使用的私用成員</target>
<note />
</trans-unit>
<trans-unit id="Simplify_LINQ_expression">
<source>Simplify LINQ expression</source>
<target state="translated">簡化 LINQ 運算式</target>
<note />
</trans-unit>
<trans-unit id="Simplify_collection_initialization">
<source>Simplify collection initialization</source>
<target state="translated">簡化集合初始化</target>
<note />
</trans-unit>
<trans-unit id="Simplify_conditional_expression">
<source>Simplify conditional expression</source>
<target state="translated">簡化條件運算式</target>
<note />
</trans-unit>
<trans-unit id="Simplify_interpolation">
<source>Simplify interpolation</source>
<target state="translated">簡化內插補點</target>
<note />
</trans-unit>
<trans-unit id="Simplify_object_initialization">
<source>Simplify object initialization</source>
<target state="translated">簡化物件初始化</target>
<note />
</trans-unit>
<trans-unit id="The_file_header_does_not_match_the_required_text">
<source>The file header does not match the required text</source>
<target state="translated">檔案標頭與必要文字不相符</target>
<note />
</trans-unit>
<trans-unit id="The_file_header_is_missing_or_not_located_at_the_top_of_the_file">
<source>The file header is missing or not located at the top of the file</source>
<target state="translated">缺少檔案標頭或其不在檔案的頂端</target>
<note />
</trans-unit>
<trans-unit id="Unnecessary_assignment_of_a_value">
<source>Unnecessary assignment of a value</source>
<target state="translated">指派了不必要的值</target>
<note />
</trans-unit>
<trans-unit id="Unnecessary_assignment_of_a_value_to_0">
<source>Unnecessary assignment of a value to '{0}'</source>
<target state="translated">對 '{0}' 指派了不必要的值</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">使用 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_auto_property">
<source>Use auto property</source>
<target state="translated">使用 Auto 屬性</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="translated">使用 coalesce 運算式</target>
<note />
</trans-unit>
<trans-unit id="Use_compound_assignment">
<source>Use compound assignment</source>
<target state="translated">使用複合指派</target>
<note />
</trans-unit>
<trans-unit id="Use_decrement_operator">
<source>Use '--' operator</source>
<target state="translated">使用 '--' 運算子</target>
<note />
</trans-unit>
<trans-unit id="Use_explicitly_provided_tuple_name">
<source>Use explicitly provided tuple name</source>
<target state="translated">使用明確提供的元組名稱</target>
<note />
</trans-unit>
<trans-unit id="Use_increment_operator">
<source>Use '++' operator</source>
<target state="translated">使用 '+ +' 運算子</target>
<note />
</trans-unit>
<trans-unit id="Use_inferred_member_name">
<source>Use inferred member name</source>
<target state="translated">使用推斷的成員名稱</target>
<note />
</trans-unit>
<trans-unit id="Use_null_propagation">
<source>Use null propagation</source>
<target state="translated">使用 null 傳播</target>
<note />
</trans-unit>
<trans-unit id="Use_throw_expression">
<source>Use 'throw' expression</source>
<target state="translated">使用 'throw' 運算式</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../AnalyzersResources.resx">
<body>
<trans-unit id="A_source_file_contains_a_header_that_does_not_match_the_required_text">
<source>A source file contains a header that does not match the required text</source>
<target state="translated">來源檔案包含的標頭與必要文字不相符</target>
<note />
</trans-unit>
<trans-unit id="A_source_file_is_missing_a_required_header">
<source>A source file is missing a required header.</source>
<target state="translated">來源檔案缺少必要標頭。</target>
<note />
</trans-unit>
<trans-unit id="Accessibility_modifiers_required">
<source>Accessibility modifiers required</source>
<target state="translated">協助工具修飾元為必要項</target>
<note />
</trans-unit>
<trans-unit id="Add_accessibility_modifiers">
<source>Add accessibility modifiers</source>
<target state="translated">新增協助工具修飾元</target>
<note />
</trans-unit>
<trans-unit id="Add_parentheses_for_clarity">
<source>Add parentheses for clarity</source>
<target state="translated">新增括號以明確表示</target>
<note />
</trans-unit>
<trans-unit id="Add_readonly_modifier">
<source>Add readonly modifier</source>
<target state="translated">新增唯讀修飾元</target>
<note />
</trans-unit>
<trans-unit id="Add_this_or_Me_qualification">
<source>Add 'this' or 'Me' qualification.</source>
<target state="translated">新增 'this' 或 'Me' 限定性條件。</target>
<note />
</trans-unit>
<trans-unit id="Avoid_legacy_format_target_0_in_SuppressMessageAttribute">
<source>Avoid legacy format target '{0}' in 'SuppressMessageAttribute'</source>
<target state="translated">避免在 'SuppressMessageAttribute' 中使用舊版格式目標 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Avoid_legacy_format_target_in_SuppressMessageAttribute">
<source>Avoid legacy format target in 'SuppressMessageAttribute'</source>
<target state="translated">避免在 'SuppressMessageAttribute' 中使用舊版格式目標</target>
<note />
</trans-unit>
<trans-unit id="Avoid_multiple_blank_lines">
<source>Avoid multiple blank lines</source>
<target state="translated">避免多個空白行</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unnecessary_value_assignments_in_your_code_as_these_likely_indicate_redundant_value_computations_If_the_value_computation_is_not_redundant_and_you_intend_to_retain_the_assignmentcomma_then_change_the_assignment_target_to_a_local_variable_whose_name_starts_with_an_underscore_and_is_optionally_followed_by_an_integercomma_such_as___comma__1_comma__2_comma_etc">
<source>Avoid unnecessary value assignments in your code, as these likely indicate redundant value computations. If the value computation is not redundant and you intend to retain the assignment, then change the assignment target to a local variable whose name starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source>
<target state="translated">請避免在您的程式碼中指派非必要的值,因為這可能表示值會重複計算。如果值未重複計算,而且您想要保留指派,請將指派目標變更為名稱以底線開頭的區域變數,並可選擇在後面接著整數,例如 '_'、'_1'、'_2' 等。這些會視為特殊的捨棄符號名稱。</target>
<note />
</trans-unit>
<trans-unit id="Avoid_unused_parameters_in_your_code_If_the_parameter_cannot_be_removed_then_change_its_name_so_it_starts_with_an_underscore_and_is_optionally_followed_by_an_integer_such_as__comma__1_comma__2_etc_These_are_treated_as_special_discard_symbol_names">
<source>Avoid unused parameters in your code. If the parameter cannot be removed, then change its name so it starts with an underscore and is optionally followed by an integer, such as '_', '_1', '_2', etc. These are treated as special discard symbol names.</source>
<target state="translated">請避免在您的程式碼中使用參數。如果無法移除參數,請變更其名稱,使其以底線開頭,並可選擇在後面接著整數,例如 '_'、'_1'、'_2' 等。這些會視為特殊的捨棄符號名稱。</target>
<note />
</trans-unit>
<trans-unit id="Blank_line_required_between_block_and_subsequent_statement">
<source>Blank line required between block and subsequent statement</source>
<target state="translated">區塊與後續陳述式之間必須有空白行</target>
<note />
</trans-unit>
<trans-unit id="Change_namespace_to_match_folder_structure">
<source>Change namespace to match folder structure</source>
<target state="translated">變更 namespace 以符合資料夾結構</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Changes_to_expression_trees_may_result_in_behavior_changes_at_runtime">
<source>Changes to expression trees may result in behavior changes at runtime</source>
<target state="translated">變更運算式樹狀架構可能會導致執行階段的行為變更</target>
<note />
</trans-unit>
<trans-unit id="Conditional_expression_can_be_simplified">
<source>Conditional expression can be simplified</source>
<target state="translated">條件運算式可加以簡化</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_conditional_expression">
<source>Convert to conditional expression</source>
<target state="translated">轉換至條件運算式</target>
<note />
</trans-unit>
<trans-unit id="Convert_to_tuple">
<source>Convert to tuple</source>
<target state="translated">轉換為元組</target>
<note />
</trans-unit>
<trans-unit id="Expression_value_is_never_used">
<source>Expression value is never used</source>
<target state="translated">永遠不會使用運算式值</target>
<note />
</trans-unit>
<trans-unit id="Collection_initialization_can_be_simplified">
<source>Collection initialization can be simplified</source>
<target state="translated">集合初始化可簡化</target>
<note />
</trans-unit>
<trans-unit id="Format_string_contains_invalid_placeholder">
<source>Format string contains invalid placeholder</source>
<target state="translated">格式字串包含無效的預留位置</target>
<note />
</trans-unit>
<trans-unit id="GetHashCode_implementation_can_be_simplified">
<source>'GetHashCode' implementation can be simplified</source>
<target state="translated">'GetHashCode' 實作可簡化</target>
<note />
</trans-unit>
<trans-unit id="Interpolation_can_be_simplified">
<source>Interpolation can be simplified</source>
<target state="translated">可簡化內插補點</target>
<note />
</trans-unit>
<trans-unit id="Invalid_format_string">
<source>Invalid format string</source>
<target state="translated">格式字串無效</target>
<note />
</trans-unit>
<trans-unit id="Invalid_global_SuppressMessageAttribute">
<source>Invalid global 'SuppressMessageAttribute'</source>
<target state="translated">全域 'SuppressMessageAttribute' 無效</target>
<note />
</trans-unit>
<trans-unit id="Invalid_or_missing_target_for_SuppressMessageAttribute">
<source>Invalid or missing target for 'SuppressMessageAttribute'</source>
<target state="translated">'SuppressMessageAttribute' 缺少目標或其無效</target>
<note />
</trans-unit>
<trans-unit id="Invalid_scope_for_SuppressMessageAttribute">
<source>Invalid scope for 'SuppressMessageAttribute'</source>
<target state="translated">'SuppressMessageAttribute' 的範圍無效</target>
<note />
</trans-unit>
<trans-unit id="Make_field_readonly">
<source>Make field readonly</source>
<target state="translated">使欄位唯讀</target>
<note />
</trans-unit>
<trans-unit id="Member_access_should_be_qualified">
<source>Member access should be qualified.</source>
<target state="translated">必須限定成員存取。</target>
<note />
</trans-unit>
<trans-unit id="Add_missing_cases">
<source>Add missing cases</source>
<target state="translated">新增遺漏的案例</target>
<note />
</trans-unit>
<trans-unit id="Member_name_can_be_simplified">
<source>Member name can be simplified</source>
<target state="translated">成員名稱可簡化</target>
<note />
</trans-unit>
<trans-unit id="Modifiers_are_not_ordered">
<source>Modifiers are not ordered</source>
<target state="translated">修飾元未排序</target>
<note />
</trans-unit>
<trans-unit id="Namespace_0_does_not_match_folder_structure_expected_1">
<source>Namespace "{0}" does not match folder structure, expected "{1}"</source>
<target state="translated">命名空間 "{0}" 與資料夾結構不相符,必須為 "{1}"</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Namespace_does_not_match_folder_structure">
<source>Namespace does not match folder structure</source>
<target state="translated">命名空間與資料夾結構不相符</target>
<note>{Locked="namespace"} "namespace" is a keyword and should not be localized.</note>
</trans-unit>
<trans-unit id="Naming_Styles">
<source>Naming Styles</source>
<target state="translated">命名樣式</target>
<note />
</trans-unit>
<trans-unit id="Naming_rule_violation_0">
<source>Naming rule violation: {0}</source>
<target state="translated">違反命名規則: {0}</target>
<note>{0} is the rule title, {1} is the way in which the rule was violated</note>
</trans-unit>
<trans-unit id="Null_check_can_be_simplified">
<source>Null check can be simplified</source>
<target state="translated">Null 檢查可簡化</target>
<note />
</trans-unit>
<trans-unit id="Order_modifiers">
<source>Order modifiers</source>
<target state="translated">為修飾元排序</target>
<note />
</trans-unit>
<trans-unit id="Parameter_0_can_be_removed_if_it_is_not_part_of_a_shipped_public_API_its_initial_value_is_never_used">
<source>Parameter '{0}' can be removed if it is not part of a shipped public API; its initial value is never used</source>
<target state="translated">若參數 '{0}' 不屬於已經出貨的公用 API,將無法移除; 其初始值一律不會使用</target>
<note />
</trans-unit>
<trans-unit id="Parameter_0_can_be_removed_its_initial_value_is_never_used">
<source>Parameter '{0}' can be removed; its initial value is never used</source>
<target state="translated">參數 '{0}' 可以移除; 其初始值一律不會使用</target>
<note />
</trans-unit>
<trans-unit id="Object_initialization_can_be_simplified">
<source>Object initialization can be simplified</source>
<target state="translated">物件初始化可以簡化</target>
<note />
</trans-unit>
<trans-unit id="Parentheses_can_be_removed">
<source>Parentheses can be removed</source>
<target state="translated">可以移除括號</target>
<note />
</trans-unit>
<trans-unit id="Parentheses_should_be_added_for_clarity">
<source>Parentheses should be added for clarity</source>
<target state="translated">應新增括號以明確表示</target>
<note />
</trans-unit>
<trans-unit id="Populate_switch">
<source>Populate switch</source>
<target state="translated">填入切換</target>
<note />
</trans-unit>
<trans-unit id="Prefer_explicitly_provided_tuple_element_name">
<source>Prefer explicitly provided tuple element name</source>
<target state="translated">建議使用明確提供的元組元素名稱</target>
<note />
</trans-unit>
<trans-unit id="Private_member_0_can_be_removed_as_the_value_assigned_to_it_is_never_read">
<source>Private member '{0}' can be removed as the value assigned to it is never read</source>
<target state="translated">因為永遠不會讀取指派給 Private 成員 '{0}' 的值,所以可移除該成員</target>
<note />
</trans-unit>
<trans-unit id="Private_member_0_is_unused">
<source>Private member '{0}' is unused</source>
<target state="translated">未使用 Private 成員 '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Private_method_0_can_be_removed_as_it_is_never_invoked">
<source>Private method '{0}' can be removed as it is never invoked.</source>
<target state="translated">因為永遠不會叫用私用方法 ‘{0}’,所以可予以移除。</target>
<note />
</trans-unit>
<trans-unit id="Private_property_0_can_be_converted_to_a_method_as_its_get_accessor_is_never_invoked">
<source>Private property '{0}' can be converted to a method as its get accessor is never invoked.</source>
<target state="translated">系統永遠不會叫用私用屬性 '{0}' 的 get 存取子,因此該屬性可以轉換成方法。</target>
<note />
</trans-unit>
<trans-unit id="Remove_Unnecessary_Cast">
<source>Remove Unnecessary Cast</source>
<target state="translated">移除不必要的 Cast</target>
<note />
</trans-unit>
<trans-unit id="Remove_redundant_equality">
<source>Remove redundant equality</source>
<target state="translated">移除多餘的等號</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_parentheses">
<source>Remove unnecessary parentheses</source>
<target state="translated">移除不必要的括號</target>
<note />
</trans-unit>
<trans-unit id="Remove_unnecessary_suppression">
<source>Remove unnecessary suppression</source>
<target state="translated">移除非必要的隱藏項目</target>
<note />
</trans-unit>
<trans-unit id="Remove_unread_private_members">
<source>Remove unread private members</source>
<target state="translated">刪除未讀取的私用成員</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_member">
<source>Remove unused member</source>
<target state="translated">移除未使用的成員</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter">
<source>Remove unused parameter</source>
<target state="translated">移除未使用的參數</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter_0">
<source>Remove unused parameter '{0}'</source>
<target state="translated">移除未使用的參數 ‘{0}’</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_parameter_0_if_it_is_not_part_of_a_shipped_public_API">
<source>Remove unused parameter '{0}' if it is not part of a shipped public API</source>
<target state="translated">如果未使用的參數 ‘{0}’ 不屬於已發行的公用 API,請予以移除</target>
<note />
</trans-unit>
<trans-unit id="Remove_unused_private_members">
<source>Remove unused private members</source>
<target state="translated">刪除未使用的私用成員</target>
<note />
</trans-unit>
<trans-unit id="Simplify_LINQ_expression">
<source>Simplify LINQ expression</source>
<target state="translated">簡化 LINQ 運算式</target>
<note />
</trans-unit>
<trans-unit id="Simplify_collection_initialization">
<source>Simplify collection initialization</source>
<target state="translated">簡化集合初始化</target>
<note />
</trans-unit>
<trans-unit id="Simplify_conditional_expression">
<source>Simplify conditional expression</source>
<target state="translated">簡化條件運算式</target>
<note />
</trans-unit>
<trans-unit id="Simplify_interpolation">
<source>Simplify interpolation</source>
<target state="translated">簡化內插補點</target>
<note />
</trans-unit>
<trans-unit id="Simplify_object_initialization">
<source>Simplify object initialization</source>
<target state="translated">簡化物件初始化</target>
<note />
</trans-unit>
<trans-unit id="The_file_header_does_not_match_the_required_text">
<source>The file header does not match the required text</source>
<target state="translated">檔案標頭與必要文字不相符</target>
<note />
</trans-unit>
<trans-unit id="The_file_header_is_missing_or_not_located_at_the_top_of_the_file">
<source>The file header is missing or not located at the top of the file</source>
<target state="translated">缺少檔案標頭或其不在檔案的頂端</target>
<note />
</trans-unit>
<trans-unit id="Unnecessary_assignment_of_a_value">
<source>Unnecessary assignment of a value</source>
<target state="translated">指派了不必要的值</target>
<note />
</trans-unit>
<trans-unit id="Unnecessary_assignment_of_a_value_to_0">
<source>Unnecessary assignment of a value to '{0}'</source>
<target state="translated">對 '{0}' 指派了不必要的值</target>
<note />
</trans-unit>
<trans-unit id="Use_System_HashCode">
<source>Use 'System.HashCode'</source>
<target state="translated">使用 'System.HashCode'</target>
<note />
</trans-unit>
<trans-unit id="Use_auto_property">
<source>Use auto property</source>
<target state="translated">使用 Auto 屬性</target>
<note />
</trans-unit>
<trans-unit id="Use_coalesce_expression">
<source>Use coalesce expression</source>
<target state="translated">使用 coalesce 運算式</target>
<note />
</trans-unit>
<trans-unit id="Use_compound_assignment">
<source>Use compound assignment</source>
<target state="translated">使用複合指派</target>
<note />
</trans-unit>
<trans-unit id="Use_decrement_operator">
<source>Use '--' operator</source>
<target state="translated">使用 '--' 運算子</target>
<note />
</trans-unit>
<trans-unit id="Use_explicitly_provided_tuple_name">
<source>Use explicitly provided tuple name</source>
<target state="translated">使用明確提供的元組名稱</target>
<note />
</trans-unit>
<trans-unit id="Use_increment_operator">
<source>Use '++' operator</source>
<target state="translated">使用 '+ +' 運算子</target>
<note />
</trans-unit>
<trans-unit id="Use_inferred_member_name">
<source>Use inferred member name</source>
<target state="translated">使用推斷的成員名稱</target>
<note />
</trans-unit>
<trans-unit id="Use_null_propagation">
<source>Use null propagation</source>
<target state="translated">使用 null 傳播</target>
<note />
</trans-unit>
<trans-unit id="Use_throw_expression">
<source>Use 'throw' expression</source>
<target state="translated">使用 'throw' 運算式</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/xlf/WorkspaceExtensionsResources.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="../WorkspaceExtensionsResources.resx">
<body>
<trans-unit id="Compilation_is_required_to_accomplish_the_task_but_is_not_supported_by_project_0">
<source>Compilation is required to accomplish the task but is not supported by project {0}.</source>
<target state="translated">Une compilation est nécessaire pour accomplir la tâche, mais elle n'est pas prise en charge par le projet {0}.</target>
<note />
</trans-unit>
<trans-unit id="Fix_all_0">
<source>Fix all '{0}'</source>
<target state="translated">Corriger tous les '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Fix_all_0_in_1">
<source>Fix all '{0}' in '{1}'</source>
<target state="translated">Pour toutes les '{0}' dans '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Fix_all_0_in_Solution">
<source>Fix all '{0}' in Solution</source>
<target state="translated">Corriger tous les '{0}' dans la solution</target>
<note />
</trans-unit>
<trans-unit id="Project_of_ID_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_solution">
<source>Project of ID {0} is required to accomplish the task but is not available from the solution</source>
<target state="translated">Le projet de l'ID {0} est nécessaire pour accomplir la tâche mais n'est pas disponible dans la solution</target>
<note />
</trans-unit>
<trans-unit id="Supplied_diagnostic_cannot_be_null">
<source>Supplied diagnostic cannot be null.</source>
<target state="translated">Le diagnostic fourni ne peut pas être null.</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0">
<source>Syntax tree is required to accomplish the task but is not supported by document {0}.</source>
<target state="translated">Une arborescence de syntaxe est nécessaire pour accomplir la tâche, mais elle n'est pas prise en charge par le document {0}.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_does_not_contain_the_specified_document">
<source>The solution does not contain the specified document.</source>
<target state="translated">La solution ne contient pas le document spécifié.</target>
<note />
</trans-unit>
<trans-unit id="Warning_colon_Declaration_changes_scope_and_may_change_meaning">
<source>Warning: Declaration changes scope and may change meaning.</source>
<target state="translated">Avertissement : La déclaration change la portée et éventuellement la signification.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="fr" original="../WorkspaceExtensionsResources.resx">
<body>
<trans-unit id="Compilation_is_required_to_accomplish_the_task_but_is_not_supported_by_project_0">
<source>Compilation is required to accomplish the task but is not supported by project {0}.</source>
<target state="translated">Une compilation est nécessaire pour accomplir la tâche, mais elle n'est pas prise en charge par le projet {0}.</target>
<note />
</trans-unit>
<trans-unit id="Fix_all_0">
<source>Fix all '{0}'</source>
<target state="translated">Corriger tous les '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Fix_all_0_in_1">
<source>Fix all '{0}' in '{1}'</source>
<target state="translated">Pour toutes les '{0}' dans '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Fix_all_0_in_Solution">
<source>Fix all '{0}' in Solution</source>
<target state="translated">Corriger tous les '{0}' dans la solution</target>
<note />
</trans-unit>
<trans-unit id="Project_of_ID_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_solution">
<source>Project of ID {0} is required to accomplish the task but is not available from the solution</source>
<target state="translated">Le projet de l'ID {0} est nécessaire pour accomplir la tâche mais n'est pas disponible dans la solution</target>
<note />
</trans-unit>
<trans-unit id="Supplied_diagnostic_cannot_be_null">
<source>Supplied diagnostic cannot be null.</source>
<target state="translated">Le diagnostic fourni ne peut pas être null.</target>
<note />
</trans-unit>
<trans-unit id="SyntaxTree_is_required_to_accomplish_the_task_but_is_not_supported_by_document_0">
<source>Syntax tree is required to accomplish the task but is not supported by document {0}.</source>
<target state="translated">Une arborescence de syntaxe est nécessaire pour accomplir la tâche, mais elle n'est pas prise en charge par le document {0}.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_does_not_contain_the_specified_document">
<source>The solution does not contain the specified document.</source>
<target state="translated">La solution ne contient pas le document spécifié.</target>
<note />
</trans-unit>
<trans-unit id="Warning_colon_Declaration_changes_scope_and_may_change_meaning">
<source>Warning: Declaration changes scope and may change meaning.</source>
<target state="translated">Avertissement : La déclaration change la portée et éventuellement la signification.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Portable/Binder/NameofBinder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class NameofBinder : Binder
{
private readonly SyntaxNode _nameofArgument;
public NameofBinder(SyntaxNode nameofArgument, Binder next) : base(next)
{
_nameofArgument = nameofArgument;
}
protected override SyntaxNode EnclosingNameofArgument => _nameofArgument;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed class NameofBinder : Binder
{
private readonly SyntaxNode _nameofArgument;
public NameofBinder(SyntaxNode nameofArgument, Binder next) : base(next)
{
_nameofArgument = nameofArgument;
}
protected override SyntaxNode EnclosingNameofArgument => _nameofArgument;
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Portable/Compilation/SymbolInfoFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal static class SymbolInfoFactory
{
internal static SymbolInfo Create(ImmutableArray<Symbol> symbols, LookupResultKind resultKind, bool isDynamic)
{
if (isDynamic)
{
if (symbols.Length == 1)
{
return new SymbolInfo(symbols[0].GetPublicSymbol(), CandidateReason.LateBound);
}
else
{
return new SymbolInfo(symbols.GetPublicSymbols(), CandidateReason.LateBound);
}
}
else if (resultKind == LookupResultKind.Viable)
{
if (symbols.Length > 0)
{
Debug.Assert(symbols.Length == 1);
return new SymbolInfo(symbols[0].GetPublicSymbol());
}
else
{
return SymbolInfo.None;
}
}
else
{
return new SymbolInfo(symbols.GetPublicSymbols(), (symbols.Length > 0) ? resultKind.ToCandidateReason() : CandidateReason.None);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal static class SymbolInfoFactory
{
internal static SymbolInfo Create(ImmutableArray<Symbol> symbols, LookupResultKind resultKind, bool isDynamic)
{
if (isDynamic)
{
if (symbols.Length == 1)
{
return new SymbolInfo(symbols[0].GetPublicSymbol(), CandidateReason.LateBound);
}
else
{
return new SymbolInfo(symbols.GetPublicSymbols(), CandidateReason.LateBound);
}
}
else if (resultKind == LookupResultKind.Viable)
{
if (symbols.Length > 0)
{
Debug.Assert(symbols.Length == 1);
return new SymbolInfo(symbols[0].GetPublicSymbol());
}
else
{
return SymbolInfo.None;
}
}
else
{
return new SymbolInfo(symbols.GetPublicSymbols(), (symbols.Length > 0) ? resultKind.ToCandidateReason() : CandidateReason.None);
}
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/CSharp/SplitStringLiteral/SplitStringLiteralCommandHandler.SimpleStringSplitter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.Formatting.FormattingOptions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral
{
internal partial class SplitStringLiteralCommandHandler
{
private class SimpleStringSplitter : StringSplitter
{
private const char QuoteCharacter = '"';
private readonly SyntaxToken _token;
public SimpleStringSplitter(
Document document, int position,
SyntaxNode root, SourceText sourceText, SyntaxToken token,
bool useTabs, int tabSize, IndentStyle indentStyle, CancellationToken cancellationToken)
: base(document, position, root, sourceText, useTabs, tabSize, indentStyle, cancellationToken)
{
_token = token;
}
// Don't split @"" strings. They already support directly embedding newlines.
protected override bool CheckToken()
=> !_token.IsVerbatimStringLiteral();
protected override SyntaxNode GetNodeToReplace() => _token.Parent;
protected override BinaryExpressionSyntax CreateSplitString()
{
// TODO(cyrusn): Deal with the positoin being after a \ character
var prefix = SourceText.GetSubText(TextSpan.FromBounds(_token.SpanStart, CursorPosition)).ToString();
var suffix = SourceText.GetSubText(TextSpan.FromBounds(CursorPosition, _token.Span.End)).ToString();
var firstToken = SyntaxFactory.Token(
_token.LeadingTrivia,
_token.Kind(),
text: prefix + QuoteCharacter,
valueText: "",
trailing: SyntaxFactory.TriviaList(SyntaxFactory.ElasticSpace));
var secondToken = SyntaxFactory.Token(
default,
_token.Kind(),
text: QuoteCharacter + suffix,
valueText: "",
trailing: _token.TrailingTrivia);
var leftExpression = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, firstToken);
var rightExpression = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, secondToken);
return SyntaxFactory.BinaryExpression(
SyntaxKind.AddExpression,
leftExpression,
PlusNewLineToken,
rightExpression.WithAdditionalAnnotations(RightNodeAnnotation));
}
protected override int StringOpenQuoteLength() => "\"".Length;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static Microsoft.CodeAnalysis.Formatting.FormattingOptions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral
{
internal partial class SplitStringLiteralCommandHandler
{
private class SimpleStringSplitter : StringSplitter
{
private const char QuoteCharacter = '"';
private readonly SyntaxToken _token;
public SimpleStringSplitter(
Document document, int position,
SyntaxNode root, SourceText sourceText, SyntaxToken token,
bool useTabs, int tabSize, IndentStyle indentStyle, CancellationToken cancellationToken)
: base(document, position, root, sourceText, useTabs, tabSize, indentStyle, cancellationToken)
{
_token = token;
}
// Don't split @"" strings. They already support directly embedding newlines.
protected override bool CheckToken()
=> !_token.IsVerbatimStringLiteral();
protected override SyntaxNode GetNodeToReplace() => _token.Parent;
protected override BinaryExpressionSyntax CreateSplitString()
{
// TODO(cyrusn): Deal with the positoin being after a \ character
var prefix = SourceText.GetSubText(TextSpan.FromBounds(_token.SpanStart, CursorPosition)).ToString();
var suffix = SourceText.GetSubText(TextSpan.FromBounds(CursorPosition, _token.Span.End)).ToString();
var firstToken = SyntaxFactory.Token(
_token.LeadingTrivia,
_token.Kind(),
text: prefix + QuoteCharacter,
valueText: "",
trailing: SyntaxFactory.TriviaList(SyntaxFactory.ElasticSpace));
var secondToken = SyntaxFactory.Token(
default,
_token.Kind(),
text: QuoteCharacter + suffix,
valueText: "",
trailing: _token.TrailingTrivia);
var leftExpression = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, firstToken);
var rightExpression = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, secondToken);
return SyntaxFactory.BinaryExpression(
SyntaxKind.AddExpression,
leftExpression,
PlusNewLineToken,
rightExpression.WithAdditionalAnnotations(RightNodeAnnotation));
}
protected override int StringOpenQuoteLength() => "\"".Length;
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/Core/Portable/Indentation/AbstractIndentationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Indentation
{
internal abstract partial class AbstractIndentationService<TSyntaxRoot> : IIndentationService
where TSyntaxRoot : SyntaxNode, ICompilationUnitSyntax
{
protected abstract AbstractFormattingRule GetSpecializedIndentationFormattingRule(FormattingOptions.IndentStyle indentStyle);
private IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document, int position, FormattingOptions.IndentStyle indentStyle)
{
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
var baseIndentationRule = formattingRuleFactory.CreateRule(document, position);
var formattingRules = new[] { baseIndentationRule, this.GetSpecializedIndentationFormattingRule(indentStyle) }.Concat(Formatter.GetDefaultFormattingRules(document));
return formattingRules;
}
public IndentationResult GetIndentation(
Document document, int lineNumber,
FormattingOptions.IndentStyle indentStyle, CancellationToken cancellationToken)
{
var indenter = GetIndenter(document, lineNumber, indentStyle, cancellationToken);
if (indentStyle == FormattingOptions.IndentStyle.None)
{
// If there is no indent style, then do nothing.
return new IndentationResult(basePosition: 0, offset: 0);
}
if (indentStyle == FormattingOptions.IndentStyle.Smart &&
indenter.TryGetSmartTokenIndentation(out var indentationResult))
{
return indentationResult;
}
// If the indenter can't produce a valid result, just default to 0 as our indentation.
return indenter.GetDesiredIndentation(indentStyle) ?? default;
}
private Indenter GetIndenter(Document document, int lineNumber, FormattingOptions.IndentStyle indentStyle, CancellationToken cancellationToken)
{
var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
var syntacticDoc = SyntacticDocument.CreateAsync(document, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
var sourceText = syntacticDoc.Root.SyntaxTree.GetText(cancellationToken);
var lineToBeIndented = sourceText.Lines[lineNumber];
var formattingRules = GetFormattingRules(document, lineToBeIndented.Start, indentStyle);
return new Indenter(this, syntacticDoc, formattingRules, documentOptions, lineToBeIndented, cancellationToken);
}
/// <summary>
/// Returns <see langword="true"/> if the language specific <see
/// cref="ISmartTokenFormatter"/> should be deferred to figure out indentation. If so, it
/// will be asked to <see cref="ISmartTokenFormatter.FormatTokenAsync"/> the resultant
/// <paramref name="token"/> provided by this method.
/// </summary>
protected abstract bool ShouldUseTokenIndenter(Indenter indenter, out SyntaxToken token);
protected abstract ISmartTokenFormatter CreateSmartTokenFormatter(Indenter indenter);
protected abstract IndentationResult? GetDesiredIndentationWorker(
Indenter indenter, SyntaxToken? token, SyntaxTrivia? trivia);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Indentation
{
internal abstract partial class AbstractIndentationService<TSyntaxRoot> : IIndentationService
where TSyntaxRoot : SyntaxNode, ICompilationUnitSyntax
{
protected abstract AbstractFormattingRule GetSpecializedIndentationFormattingRule(FormattingOptions.IndentStyle indentStyle);
private IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document, int position, FormattingOptions.IndentStyle indentStyle)
{
var workspace = document.Project.Solution.Workspace;
var formattingRuleFactory = workspace.Services.GetRequiredService<IHostDependentFormattingRuleFactoryService>();
var baseIndentationRule = formattingRuleFactory.CreateRule(document, position);
var formattingRules = new[] { baseIndentationRule, this.GetSpecializedIndentationFormattingRule(indentStyle) }.Concat(Formatter.GetDefaultFormattingRules(document));
return formattingRules;
}
public IndentationResult GetIndentation(
Document document, int lineNumber,
FormattingOptions.IndentStyle indentStyle, CancellationToken cancellationToken)
{
var indenter = GetIndenter(document, lineNumber, indentStyle, cancellationToken);
if (indentStyle == FormattingOptions.IndentStyle.None)
{
// If there is no indent style, then do nothing.
return new IndentationResult(basePosition: 0, offset: 0);
}
if (indentStyle == FormattingOptions.IndentStyle.Smart &&
indenter.TryGetSmartTokenIndentation(out var indentationResult))
{
return indentationResult;
}
// If the indenter can't produce a valid result, just default to 0 as our indentation.
return indenter.GetDesiredIndentation(indentStyle) ?? default;
}
private Indenter GetIndenter(Document document, int lineNumber, FormattingOptions.IndentStyle indentStyle, CancellationToken cancellationToken)
{
var documentOptions = document.GetOptionsAsync(cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
var syntacticDoc = SyntacticDocument.CreateAsync(document, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
var sourceText = syntacticDoc.Root.SyntaxTree.GetText(cancellationToken);
var lineToBeIndented = sourceText.Lines[lineNumber];
var formattingRules = GetFormattingRules(document, lineToBeIndented.Start, indentStyle);
return new Indenter(this, syntacticDoc, formattingRules, documentOptions, lineToBeIndented, cancellationToken);
}
/// <summary>
/// Returns <see langword="true"/> if the language specific <see
/// cref="ISmartTokenFormatter"/> should be deferred to figure out indentation. If so, it
/// will be asked to <see cref="ISmartTokenFormatter.FormatTokenAsync"/> the resultant
/// <paramref name="token"/> provided by this method.
/// </summary>
protected abstract bool ShouldUseTokenIndenter(Indenter indenter, out SyntaxToken token);
protected abstract ISmartTokenFormatter CreateSmartTokenFormatter(Indenter indenter);
protected abstract IndentationResult? GetDesiredIndentationWorker(
Indenter indenter, SyntaxToken? token, SyntaxTrivia? trivia);
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/VisualBasic/Portable/Syntax/SyntaxNodeFactories.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.
'-----------------------------------------------------------------------------------------------------------
' Contains hand-written factories for the SyntaxNodes. Most factories are
' code-generated into SyntaxNodes.vb, but some are easier to hand-write.
'-----------------------------------------------------------------------------------------------------------
Imports System.Threading
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.Syntax
Imports System.Collections.Immutable
Imports System.ComponentModel
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class SyntaxFactory
#Region "ParseMethods"
' direct access to parsing for common grammar areas
''' <summary>
''' Create a new syntax tree from a syntax node.
''' </summary>
Public Shared Function SyntaxTree(
root As SyntaxNode,
Optional options As ParseOptions = Nothing,
Optional path As String = "",
Optional encoding As Encoding = Nothing) As SyntaxTree
Return VisualBasicSyntaxTree.Create(DirectCast(root, VisualBasicSyntaxNode), DirectCast(options, VisualBasicParseOptions), path, encoding)
End Function
''' <summary>
''' Produces a syntax tree by parsing the source text.
''' </summary>
Public Shared Function ParseSyntaxTree(
text As String,
options As ParseOptions,
path As String,
encoding As Encoding,
cancellationToken As CancellationToken) As SyntaxTree
Return ParseSyntaxTree(SourceText.From(text, encoding), options, path, cancellationToken)
End Function
''' <summary>
''' Produces a syntax tree by parsing the source text.
''' </summary>
Public Shared Function ParseSyntaxTree(
text As SourceText,
options As ParseOptions,
path As String,
cancellationToken As CancellationToken) As SyntaxTree
Return VisualBasicSyntaxTree.ParseText(text, DirectCast(options, VisualBasicParseOptions), path, cancellationToken)
End Function
#Disable Warning RS0026 ' Do not add multiple public overloads with optional parameters.
#Disable Warning RS0027 ' Public API with optional parameter(s) should have the most parameters amongst its public overloads.
''' <summary>
''' Produces a syntax tree by parsing the source text.
''' </summary>
Public Shared Function ParseSyntaxTree(
text As String,
Optional options As ParseOptions = Nothing,
Optional path As String = "",
Optional encoding As Encoding = Nothing,
Optional diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As SyntaxTree
Return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, cancellationToken)
End Function
''' <summary>
''' Produces a syntax tree by parsing the source text.
''' </summary>
Public Shared Function ParseSyntaxTree(
text As SourceText,
Optional options As ParseOptions = Nothing,
Optional path As String = "",
Optional diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As SyntaxTree
Return VisualBasicSyntaxTree.ParseText(text, DirectCast(options, VisualBasicParseOptions), path, diagnosticOptions, cancellationToken)
End Function
#Enable Warning RS0026 ' Do not add multiple public overloads with optional parameters.
#Enable Warning RS0027 ' Public API with optional parameter(s) should have the most parameters amongst its public overloads.
''' <summary>
'''Parse the input for leading trivia.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseLeadingTrivia(text As String, Optional offset As Integer = 0) As SyntaxTriviaList
Dim s = New InternalSyntax.Scanner(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
Using s
Return New SyntaxTriviaList(Nothing, s.ScanMultilineTrivia().Node, 0, 0)
End Using
End Function
''' <summary>
''' Parse the input for trailing trivia.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseTrailingTrivia(text As String, Optional offset As Integer = 0) As SyntaxTriviaList
Dim s = New InternalSyntax.Scanner(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
Using s
Return New SyntaxTriviaList(Nothing, s.ScanSingleLineTrivia().Node, 0, 0)
End Using
End Function
''' <summary>
''' Parse one token.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
''' <param name="startStatement">Scan using rules for the start of a statement</param>
Public Shared Function ParseToken(text As String, Optional offset As Integer = 0, Optional startStatement As Boolean = False) As SyntaxToken
Dim s = New InternalSyntax.Scanner(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
Using s
Dim state = If(startStatement,
InternalSyntax.ScannerState.VBAllowLeadingMultilineTrivia,
InternalSyntax.ScannerState.VB)
s.GetNextTokenInState(state)
Return New SyntaxToken(Nothing, s.GetCurrentToken, 0, 0)
End Using
End Function
''' <summary>
''' Parse tokens in the input.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
''' <param name="initialTokenPosition">The position of the first token</param>
Public Shared Iterator Function ParseTokens(text As String,
Optional offset As Integer = 0,
Optional initialTokenPosition As Integer = 0,
Optional options As VisualBasicParseOptions = Nothing) As IEnumerable(Of SyntaxToken)
Using parser = New InternalSyntax.Parser(MakeSourceText(text, offset), If(options, VisualBasicParseOptions.Default))
Dim state = InternalSyntax.ScannerState.VBAllowLeadingMultilineTrivia
Dim curTk As InternalSyntax.SyntaxToken
Do
parser.GetNextToken(state)
curTk = parser.CurrentToken
Yield New SyntaxToken(Nothing, curTk, initialTokenPosition, 0)
initialTokenPosition += curTk.FullWidth
state = If(curTk.Kind = SyntaxKind.StatementTerminatorToken,
InternalSyntax.ScannerState.VBAllowLeadingMultilineTrivia,
InternalSyntax.ScannerState.VB)
Loop While curTk.Kind <> SyntaxKind.EndOfFileToken
End Using
End Function
''' <summary>
''' Parse a name.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseName(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As NameSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
p.GetNextToken()
' "allow everything" arguments
Dim node = p.ParseName(
requireQualification:=False,
allowGlobalNameSpace:=True,
allowGenericArguments:=True,
allowGenericsWithoutOf:=False,
disallowGenericArgumentsOnLastQualifiedName:=False,
allowEmptyGenericArguments:=True,
allowedEmptyGenericArguments:=True)
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), NameSyntax)
End Using
End Function
''' <summary>
''' Parse a type name.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseTypeName(text As String, Optional offset As Integer = 0, Optional options As ParseOptions = Nothing, Optional consumeFullText As Boolean = True) As TypeSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), If(DirectCast(options, VisualBasicParseOptions), VisualBasicParseOptions.Default))
p.GetNextToken()
Dim node = p.ParseGeneralType()
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), TypeSyntax)
End Using
End Function
'' Backcompat overload, do not touch
''' <summary>
''' Parse a type name.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shared Function ParseTypeName(text As String, offset As Integer, consumeFullText As Boolean) As TypeSyntax
Return ParseTypeName(text, offset, options:=Nothing, consumeFullText)
End Function
''' <summary>
''' Parse an expression.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseExpression(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As ExpressionSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
p.GetNextToken()
Dim node = p.ParseExpression()
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), ExpressionSyntax)
End Using
End Function
''' <summary>
''' Parse an executable statement.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseExecutableStatement(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As StatementSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
Dim node = p.ParseExecutableStatement()
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), StatementSyntax)
End Using
End Function
''' <summary>
''' Parse a compilation unit (a single source file).
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseCompilationUnit(text As String, Optional offset As Integer = 0, Optional options As VisualBasicParseOptions = Nothing) As CompilationUnitSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), If(options, VisualBasicParseOptions.Default))
Return DirectCast(p.ParseCompilationUnit().CreateRed(Nothing, 0), CompilationUnitSyntax)
End Using
End Function
''' <summary>
''' Parse a parameter list.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseParameterList(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As ParameterListSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
p.GetNextToken()
Dim node = p.ParseParameterList()
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), ParameterListSyntax)
End Using
End Function
''' <summary>
''' Parse an argument list.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseArgumentList(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As ArgumentListSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
p.GetNextToken()
Dim node = p.ParseParenthesizedArguments()
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), ArgumentListSyntax)
End Using
End Function
''' <summary>
''' Helper method for wrapping a string and offset in a SourceText.
''' </summary>
Friend Shared Function MakeSourceText(text As String, offset As Integer) As SourceText
Return SourceText.From(text, Encoding.UTF8).GetSubText(offset)
End Function
''' <summary>
''' Try parse the attribute represented as a stand-alone string like [cref="A.B"] and recognize
''' 'cref' and 'name' attributes like in documentation-comment mode. This method should only be
''' used internally from code handling documentation comment includes.
''' </summary>
Friend Shared Function ParseDocCommentAttributeAsStandAloneEntity(text As String, parentElementName As String) As BaseXmlAttributeSyntax
Using scanner As New InternalSyntax.Scanner(MakeSourceText(text, 0), VisualBasicParseOptions.Default) ' NOTE: Default options should be enough
scanner.ForceScanningXmlDocMode()
Dim parser = New InternalSyntax.Parser(scanner)
parser.GetNextToken(InternalSyntax.ScannerState.Element)
Dim xmlName = InternalSyntax.SyntaxFactory.XmlName(
Nothing, InternalSyntax.SyntaxFactory.XmlNameToken(parentElementName, SyntaxKind.XmlNameToken, Nothing, Nothing))
Return DirectCast(
parser.ParseXmlAttribute(
requireLeadingWhitespace:=False,
AllowNameAsExpression:=False,
xmlElementName:=xmlName).CreateRed(Nothing, 0), BaseXmlAttributeSyntax)
End Using
End Function
#End Region
#Region "TokenFactories"
Public Shared Function IntegerLiteralToken(text As String, base As LiteralBase, typeSuffix As TypeCharacter, value As ULong) As SyntaxToken
Return IntegerLiteralToken(SyntaxFactory.TriviaList(ElasticMarker), text, base, typeSuffix, value, SyntaxFactory.TriviaList(ElasticMarker))
End Function
Public Shared Function IntegerLiteralToken(leadingTrivia As SyntaxTriviaList, text As String, base As LiteralBase, typeSuffix As TypeCharacter, value As ULong, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentNullException(NameOf(text))
End If
Return New SyntaxToken(Nothing, InternalSyntax.SyntaxFactory.IntegerLiteralToken(text, base, typeSuffix, value, leadingTrivia.Node, trailingTrivia.Node), 0, 0)
End Function
Public Shared Function FloatingLiteralToken(text As String, typeSuffix As TypeCharacter, value As Double) As SyntaxToken
Return FloatingLiteralToken(SyntaxFactory.TriviaList(ElasticMarker), text, typeSuffix, value, SyntaxFactory.TriviaList(ElasticMarker))
End Function
Public Shared Function FloatingLiteralToken(leadingTrivia As SyntaxTriviaList, text As String, typeSuffix As TypeCharacter, value As Double, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentNullException(NameOf(text))
End If
Return New SyntaxToken(Nothing, InternalSyntax.SyntaxFactory.FloatingLiteralToken(text, typeSuffix, value, leadingTrivia.Node, trailingTrivia.Node), 0, 0)
End Function
Public Shared Function Identifier(text As String, isBracketed As Boolean, identifierText As String, typeCharacter As TypeCharacter) As SyntaxToken
Return Identifier(SyntaxFactory.TriviaList(ElasticMarker), text, isBracketed, identifierText, typeCharacter, SyntaxFactory.TriviaList(ElasticMarker))
End Function
Friend Shared Function Identifier(leadingTrivia As SyntaxTrivia, text As String, isBracketed As Boolean, identifierText As String, typeCharacter As TypeCharacter, trailingTrivia As SyntaxTrivia) As SyntaxToken
Return Identifier(SyntaxTriviaList.Create(leadingTrivia), text, isBracketed, identifierText, typeCharacter, SyntaxTriviaList.Create(trailingTrivia))
End Function
Public Shared Function Identifier(leadingTrivia As SyntaxTriviaList, text As String, isBracketed As Boolean, identifierText As String, typeCharacter As TypeCharacter, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentException(NameOf(text))
End If
Return New SyntaxToken(Nothing, New InternalSyntax.ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, leadingTrivia.Node, trailingTrivia.Node, SyntaxKind.IdentifierToken, isBracketed, identifierText, typeCharacter), 0, 0)
End Function
Public Shared Function Identifier(text As String) As SyntaxToken
Return Identifier(SyntaxFactory.TriviaList(ElasticMarker), text, SyntaxFactory.TriviaList(ElasticMarker))
End Function
Friend Shared Function Identifier(leadingTrivia As SyntaxTrivia, text As String, trailingTrivia As SyntaxTrivia) As SyntaxToken
Return Identifier(SyntaxTriviaList.Create(leadingTrivia), text, SyntaxTriviaList.Create(trailingTrivia))
End Function
Public Shared Function Identifier(leadingTrivia As SyntaxTriviaList, text As String, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentException(NameOf(text))
End If
Return New SyntaxToken(Nothing, New InternalSyntax.ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, leadingTrivia.Node, trailingTrivia.Node, SyntaxKind.IdentifierToken, False, text, TypeCharacter.None), 0, 0)
End Function
''' <summary>
''' Create a bracketed identifier.
''' </summary>
Public Shared Function BracketedIdentifier(text As String) As SyntaxToken
Return BracketedIdentifier(SyntaxFactory.TriviaList(ElasticMarker), text, SyntaxFactory.TriviaList(ElasticMarker))
End Function
''' <summary>
''' Create a bracketed identifier.
''' </summary>
Public Shared Function BracketedIdentifier(leadingTrivia As SyntaxTriviaList, text As String, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentException(NameOf(text))
End If
If MakeHalfWidthIdentifier(text.First) = "[" AndAlso MakeHalfWidthIdentifier(text.Last) = "]" Then
Throw New ArgumentException(NameOf(text))
End If
Return New SyntaxToken(Nothing, New InternalSyntax.ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, "[" + text + "]", leadingTrivia.Node, trailingTrivia.Node, SyntaxKind.IdentifierToken, True, text, TypeCharacter.None), 0, 0)
End Function
''' <summary>
''' Create a missing identifier.
''' </summary>
Friend Shared Function MissingIdentifier() As SyntaxToken
Return New SyntaxToken(Nothing, New InternalSyntax.SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, "",
ElasticMarker.UnderlyingNode, ElasticMarker.UnderlyingNode), 0, 0)
End Function
''' <summary>
''' Create a missing contextual keyword.
''' </summary>
Friend Shared Function MissingIdentifier(kind As SyntaxKind) As SyntaxToken
Return New SyntaxToken(Nothing, New InternalSyntax.ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, "",
ElasticMarker.UnderlyingNode, ElasticMarker.UnderlyingNode,
kind, False, "", TypeCharacter.None), 0, 0)
End Function
''' <summary>
''' Create a missing keyword.
''' </summary>
Friend Shared Function MissingKeyword(kind As SyntaxKind) As SyntaxToken
Return New SyntaxToken(Nothing, New InternalSyntax.KeywordSyntax(kind, "",
ElasticMarker.UnderlyingNode, ElasticMarker.UnderlyingNode), 0, 0)
End Function
''' <summary>
''' Create a missing punctuation mark.
''' </summary>
Friend Shared Function MissingPunctuation(kind As SyntaxKind) As SyntaxToken
Return New SyntaxToken(Nothing, New InternalSyntax.PunctuationSyntax(kind, "",
ElasticMarker.UnderlyingNode, ElasticMarker.UnderlyingNode), 0, 0)
End Function
''' <summary>
''' Create a missing string literal.
''' </summary>
Friend Shared Function MissingStringLiteral() As SyntaxToken
Return SyntaxFactory.StringLiteralToken("", "")
End Function
''' <summary>
''' Create a missing character literal.
''' </summary>
Friend Shared Function MissingCharacterLiteralToken() As SyntaxToken
Return CharacterLiteralToken("", Nothing)
End Function
''' <summary>
''' Create a missing integer literal.
''' </summary>
Friend Shared Function MissingIntegerLiteralToken() As SyntaxToken
Return IntegerLiteralToken(SyntaxFactory.TriviaList(ElasticMarker), "", LiteralBase.Decimal, TypeCharacter.None, Nothing, SyntaxFactory.TriviaList(ElasticMarker))
End Function
''' <summary>
''' Creates a copy of a token.
''' <para name="err"></para>
''' <para name="trivia"></para>
''' </summary>
''' <returns>The new token</returns>
Friend Shared Function MissingToken(kind As SyntaxKind) As SyntaxToken
Dim t As SyntaxToken
Select Case kind
Case SyntaxKind.StatementTerminatorToken
t = SyntaxFactory.Token(SyntaxKind.StatementTerminatorToken)
Case SyntaxKind.EndOfFileToken
t = SyntaxFactory.Token(SyntaxKind.EndOfFileToken)
Case SyntaxKind.AddHandlerKeyword,
SyntaxKind.AddressOfKeyword,
SyntaxKind.AliasKeyword,
SyntaxKind.AndKeyword,
SyntaxKind.AndAlsoKeyword,
SyntaxKind.AsKeyword,
SyntaxKind.BooleanKeyword,
SyntaxKind.ByRefKeyword,
SyntaxKind.ByteKeyword,
SyntaxKind.ByValKeyword,
SyntaxKind.CallKeyword,
SyntaxKind.CaseKeyword,
SyntaxKind.CatchKeyword,
SyntaxKind.CBoolKeyword,
SyntaxKind.CByteKeyword,
SyntaxKind.CCharKeyword,
SyntaxKind.CDateKeyword,
SyntaxKind.CDecKeyword,
SyntaxKind.CDblKeyword,
SyntaxKind.CharKeyword,
SyntaxKind.CIntKeyword,
SyntaxKind.ClassKeyword,
SyntaxKind.CLngKeyword,
SyntaxKind.CObjKeyword,
SyntaxKind.ConstKeyword,
SyntaxKind.ContinueKeyword,
SyntaxKind.CSByteKeyword,
SyntaxKind.CShortKeyword,
SyntaxKind.CSngKeyword,
SyntaxKind.CStrKeyword,
SyntaxKind.CTypeKeyword,
SyntaxKind.CUIntKeyword,
SyntaxKind.CULngKeyword,
SyntaxKind.CUShortKeyword,
SyntaxKind.DateKeyword,
SyntaxKind.DecimalKeyword,
SyntaxKind.DeclareKeyword,
SyntaxKind.DefaultKeyword,
SyntaxKind.DelegateKeyword,
SyntaxKind.DimKeyword,
SyntaxKind.DirectCastKeyword,
SyntaxKind.DoKeyword,
SyntaxKind.DoubleKeyword,
SyntaxKind.EachKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ElseIfKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.EnumKeyword,
SyntaxKind.EraseKeyword,
SyntaxKind.ErrorKeyword,
SyntaxKind.EventKeyword,
SyntaxKind.ExitKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.FinallyKeyword,
SyntaxKind.ForKeyword,
SyntaxKind.FriendKeyword,
SyntaxKind.FunctionKeyword,
SyntaxKind.GetKeyword,
SyntaxKind.GetTypeKeyword,
SyntaxKind.GetXmlNamespaceKeyword,
SyntaxKind.GlobalKeyword,
SyntaxKind.GoToKeyword,
SyntaxKind.HandlesKeyword,
SyntaxKind.IfKeyword,
SyntaxKind.ImplementsKeyword,
SyntaxKind.ImportsKeyword,
SyntaxKind.InKeyword,
SyntaxKind.InheritsKeyword,
SyntaxKind.IntegerKeyword,
SyntaxKind.InterfaceKeyword,
SyntaxKind.IsKeyword,
SyntaxKind.IsNotKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.LibKeyword,
SyntaxKind.LikeKeyword,
SyntaxKind.LongKeyword,
SyntaxKind.LoopKeyword,
SyntaxKind.MeKeyword,
SyntaxKind.ModKeyword,
SyntaxKind.ModuleKeyword,
SyntaxKind.MustInheritKeyword,
SyntaxKind.MustOverrideKeyword,
SyntaxKind.MyBaseKeyword,
SyntaxKind.MyClassKeyword,
SyntaxKind.NameOfKeyword,
SyntaxKind.NamespaceKeyword,
SyntaxKind.NarrowingKeyword,
SyntaxKind.NextKeyword,
SyntaxKind.NewKeyword,
SyntaxKind.NotKeyword,
SyntaxKind.NothingKeyword,
SyntaxKind.NotInheritableKeyword,
SyntaxKind.NotOverridableKeyword,
SyntaxKind.ObjectKeyword,
SyntaxKind.OfKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.OperatorKeyword,
SyntaxKind.OptionKeyword,
SyntaxKind.OptionalKeyword,
SyntaxKind.OrKeyword,
SyntaxKind.OrElseKeyword,
SyntaxKind.OverloadsKeyword,
SyntaxKind.OverridableKeyword,
SyntaxKind.OverridesKeyword,
SyntaxKind.ParamArrayKeyword,
SyntaxKind.PartialKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.PropertyKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.RaiseEventKeyword,
SyntaxKind.ReadOnlyKeyword,
SyntaxKind.ReDimKeyword,
SyntaxKind.ReferenceKeyword,
SyntaxKind.REMKeyword,
SyntaxKind.RemoveHandlerKeyword,
SyntaxKind.ResumeKeyword,
SyntaxKind.ReturnKeyword,
SyntaxKind.SByteKeyword,
SyntaxKind.SelectKeyword,
SyntaxKind.SetKeyword,
SyntaxKind.ShadowsKeyword,
SyntaxKind.SharedKeyword,
SyntaxKind.ShortKeyword,
SyntaxKind.SingleKeyword,
SyntaxKind.StaticKeyword,
SyntaxKind.StepKeyword,
SyntaxKind.StopKeyword,
SyntaxKind.StringKeyword,
SyntaxKind.StructureKeyword,
SyntaxKind.SubKeyword,
SyntaxKind.SyncLockKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ThrowKeyword,
SyntaxKind.ToKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.TryKeyword,
SyntaxKind.TryCastKeyword,
SyntaxKind.TypeOfKeyword,
SyntaxKind.UIntegerKeyword,
SyntaxKind.ULongKeyword,
SyntaxKind.UShortKeyword,
SyntaxKind.UsingKeyword,
SyntaxKind.WhenKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.WideningKeyword,
SyntaxKind.WithKeyword,
SyntaxKind.WithEventsKeyword,
SyntaxKind.WriteOnlyKeyword,
SyntaxKind.XorKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.GosubKeyword,
SyntaxKind.VariantKeyword,
SyntaxKind.WendKeyword,
SyntaxKind.OutKeyword
t = SyntaxFactory.MissingKeyword(kind)
Case SyntaxKind.AggregateKeyword,
SyntaxKind.AllKeyword,
SyntaxKind.AnsiKeyword,
SyntaxKind.AscendingKeyword,
SyntaxKind.AssemblyKeyword,
SyntaxKind.AutoKeyword,
SyntaxKind.BinaryKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.CompareKeyword,
SyntaxKind.CustomKeyword,
SyntaxKind.DescendingKeyword,
SyntaxKind.DisableKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.EnableKeyword,
SyntaxKind.EqualsKeyword,
SyntaxKind.ExplicitKeyword,
SyntaxKind.ExternalSourceKeyword,
SyntaxKind.ExternalChecksumKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.GroupKeyword,
SyntaxKind.InferKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.IsFalseKeyword,
SyntaxKind.IsTrueKeyword,
SyntaxKind.JoinKeyword,
SyntaxKind.KeyKeyword,
SyntaxKind.MidKeyword,
SyntaxKind.OffKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.PreserveKeyword,
SyntaxKind.RegionKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.StrictKeyword,
SyntaxKind.TextKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.UnicodeKeyword,
SyntaxKind.UntilKeyword,
SyntaxKind.WarningKeyword,
SyntaxKind.WhereKeyword
' These are identifiers that have a contextual kind
Return SyntaxFactory.MissingIdentifier(kind)
Case SyntaxKind.ExclamationToken,
SyntaxKind.CommaToken,
SyntaxKind.HashToken,
SyntaxKind.AmpersandToken,
SyntaxKind.SingleQuoteToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.OpenBraceToken,
SyntaxKind.CloseBraceToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.SemicolonToken,
SyntaxKind.AsteriskToken,
SyntaxKind.PlusToken,
SyntaxKind.MinusToken,
SyntaxKind.DotToken,
SyntaxKind.SlashToken,
SyntaxKind.ColonToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanEqualsToken,
SyntaxKind.LessThanGreaterThanToken,
SyntaxKind.EqualsToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.GreaterThanEqualsToken,
SyntaxKind.BackslashToken,
SyntaxKind.CaretToken,
SyntaxKind.ColonEqualsToken,
SyntaxKind.AmpersandEqualsToken,
SyntaxKind.AsteriskEqualsToken,
SyntaxKind.PlusEqualsToken,
SyntaxKind.MinusEqualsToken,
SyntaxKind.SlashEqualsToken,
SyntaxKind.BackslashEqualsToken,
SyntaxKind.CaretEqualsToken,
SyntaxKind.LessThanLessThanToken,
SyntaxKind.GreaterThanGreaterThanToken,
SyntaxKind.LessThanLessThanEqualsToken,
SyntaxKind.GreaterThanGreaterThanEqualsToken,
SyntaxKind.QuestionToken
t = SyntaxFactory.MissingPunctuation(kind)
Case SyntaxKind.FloatingLiteralToken
t = SyntaxFactory.FloatingLiteralToken("", TypeCharacter.None, Nothing)
Case SyntaxKind.DecimalLiteralToken
t = SyntaxFactory.DecimalLiteralToken("", TypeCharacter.None, Nothing)
Case SyntaxKind.DateLiteralToken
t = SyntaxFactory.DateLiteralToken("", Nothing)
Case SyntaxKind.XmlNameToken
t = SyntaxFactory.XmlNameToken("", SyntaxKind.XmlNameToken)
Case SyntaxKind.XmlTextLiteralToken
t = SyntaxFactory.XmlTextLiteralToken("", "")
Case SyntaxKind.SlashGreaterThanToken,
SyntaxKind.LessThanSlashToken,
SyntaxKind.LessThanExclamationMinusMinusToken,
SyntaxKind.MinusMinusGreaterThanToken,
SyntaxKind.LessThanQuestionToken,
SyntaxKind.QuestionGreaterThanToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.PercentGreaterThanToken,
SyntaxKind.BeginCDataToken,
SyntaxKind.EndCDataToken
t = SyntaxFactory.MissingPunctuation(kind)
Case SyntaxKind.IdentifierToken
t = SyntaxFactory.MissingIdentifier()
Case SyntaxKind.IntegerLiteralToken
t = MissingIntegerLiteralToken()
Case SyntaxKind.StringLiteralToken
t = SyntaxFactory.MissingStringLiteral()
Case SyntaxKind.CharacterLiteralToken
t = SyntaxFactory.MissingCharacterLiteralToken()
Case Else
Throw ExceptionUtilities.UnexpectedValue(kind)
End Select
Return t
End Function
Public Shared Function BadToken(text As String) As SyntaxToken
Return BadToken(Nothing, text, Nothing)
End Function
Public Shared Function BadToken(leadingTrivia As SyntaxTriviaList, text As String, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentException(NameOf(text))
End If
Return New SyntaxToken(Nothing, New InternalSyntax.BadTokenSyntax(SyntaxKind.BadToken, InternalSyntax.SyntaxSubKind.None, Nothing, Nothing, text,
leadingTrivia.Node, trailingTrivia.Node), 0, 0)
End Function
#End Region
#Region "TriviaFactories"
Public Shared Function Trivia(node As StructuredTriviaSyntax) As SyntaxTrivia
Return New SyntaxTrivia(Nothing, node.Green, position:=0, index:=0)
End Function
#End Region
#Region "ListFactories"
''' <summary>
''' Creates an empty list of syntax nodes.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
Public Shared Function List(Of TNode As SyntaxNode)() As SyntaxList(Of TNode)
Return New SyntaxList(Of TNode)
End Function
''' <summary>
''' Creates a singleton list of syntax nodes.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="node">The single element node.</param>
Public Shared Function SingletonList(Of TNode As SyntaxNode)(node As TNode) As SyntaxList(Of TNode)
Return New SyntaxList(Of TNode)(node)
End Function
''' <summary>
''' Creates a list of syntax nodes.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="nodes">A sequence of element nodes.</param>
Public Shared Function List(Of TNode As SyntaxNode)(nodes As IEnumerable(Of TNode)) As SyntaxList(Of TNode)
Return New SyntaxList(Of TNode)(nodes)
End Function
''' <summary>
''' Creates an empty list of tokens.
''' </summary>
Public Shared Function TokenList() As SyntaxTokenList
Return New SyntaxTokenList()
End Function
''' <summary>
''' Creates a singleton list of tokens.
''' </summary>
''' <param name="token">The single token.</param>
Public Shared Function TokenList(token As SyntaxToken) As SyntaxTokenList
Return New SyntaxTokenList(token)
End Function
''' <summary>
''' Creates a list of tokens.
''' </summary>
''' <param name="tokens">An array of tokens.</param>
Public Shared Function TokenList(ParamArray tokens As SyntaxToken()) As SyntaxTokenList
Return New SyntaxTokenList(tokens)
End Function
''' <summary>
''' Creates a list of tokens.
''' </summary>
''' <param name="tokens"></param>
Public Shared Function TokenList(tokens As IEnumerable(Of SyntaxToken)) As SyntaxTokenList
Return New SyntaxTokenList(tokens)
End Function
''' <summary>
''' Creates an empty list of trivia.
''' </summary>
Public Shared Function TriviaList() As SyntaxTriviaList
Return New SyntaxTriviaList()
End Function
''' <summary>
''' Creates a singleton list of trivia.
''' </summary>
''' <param name="trivia">A single trivia.</param>
Public Shared Function TriviaList(trivia As SyntaxTrivia) As SyntaxTriviaList
Return New SyntaxTriviaList(Nothing, trivia.UnderlyingNode)
End Function
''' <summary>
''' Creates a list of trivia.
''' </summary>
''' <param name="trivias">An array of trivia.</param>
Public Shared Function TriviaList(ParamArray trivias As SyntaxTrivia()) As SyntaxTriviaList
Return New SyntaxTriviaList(trivias)
End Function
''' <summary>
''' Creates a list of trivia.
''' </summary>
''' <param name="trivias">A sequence of trivia.</param>
Public Shared Function TriviaList(trivias As IEnumerable(Of SyntaxTrivia)) As SyntaxTriviaList
Return New SyntaxTriviaList(trivias)
End Function
''' <summary>
''' Creates an empty separated list.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
Public Shared Function SeparatedList(Of TNode As SyntaxNode)() As SeparatedSyntaxList(Of TNode)
Return New SeparatedSyntaxList(Of TNode)
End Function
''' <summary>
''' Creates a singleton separated list.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="node">A single node.</param>
Public Shared Function SingletonSeparatedList(Of TNode As SyntaxNode)(node As TNode) As SeparatedSyntaxList(Of TNode)
Return New SeparatedSyntaxList(Of TNode)(node, 0)
End Function
''' <summary>
''' Creates a separated list of nodes from a sequence of nodes, synthesizing comma separators in between.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="nodes">A sequence of syntax nodes.</param>
Public Shared Function SeparatedList(Of TNode As SyntaxNode)(nodes As IEnumerable(Of TNode)) As SeparatedSyntaxList(Of TNode)
If nodes Is Nothing Then Return Nothing
Dim collection = TryCast(nodes, ICollection(Of TNode))
If collection IsNot Nothing AndAlso collection.Count = 0 Then Return Nothing
Using enumerator = nodes.GetEnumerator()
If Not enumerator.MoveNext() Then Return Nothing
Dim firstNode = enumerator.Current
If Not enumerator.MoveNext() Then Return SingletonSeparatedList(firstNode)
Dim builder As New SeparatedSyntaxListBuilder(Of TNode)(If(collection IsNot Nothing, (collection.Count * 2) - 1, 3))
builder.Add(firstNode)
Dim commaToken = Token(SyntaxKind.CommaToken)
Do
builder.AddSeparator(commaToken)
builder.Add(enumerator.Current)
Loop While enumerator.MoveNext()
Return builder.ToList()
End Using
End Function
''' <summary>
''' Creates a separated list of nodes from a sequence of nodes and a sequence of separator tokens.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="nodes">A sequence of syntax nodes.</param>
''' <param name="separators">A sequence of token to be interleaved between the nodes. The number of tokens must
''' be one less than the number of nodes.</param>
Public Shared Function SeparatedList(Of TNode As SyntaxNode)(nodes As IEnumerable(Of TNode), separators As IEnumerable(Of SyntaxToken)) As SeparatedSyntaxList(Of TNode)
If nodes IsNot Nothing Then
Dim nodeEnum = nodes.GetEnumerator
Dim builder = SeparatedSyntaxListBuilder(Of TNode).Create()
If separators IsNot Nothing Then
For Each separator In separators
' The number of nodes must be equal to or one greater than the number of separators
If nodeEnum.MoveNext() Then
builder.Add(nodeEnum.Current)
Else
Throw New ArgumentException()
End If
builder.AddSeparator(separator)
Next
End If
' Check that there is zero or one node left in the enumerator
If nodeEnum.MoveNext() Then
builder.Add(nodeEnum.Current)
If nodeEnum.MoveNext() Then
Throw New ArgumentException()
End If
End If
Return builder.ToList()
ElseIf separators Is Nothing Then
' Both are nothing so return empty list
Return New SeparatedSyntaxList(Of TNode)
Else
' No nodes but have separators. This is an argument error.
Throw New ArgumentException()
End If
End Function
''' <summary>
''' Creates a separated list from a sequence of nodes or tokens.
''' The sequence must start with a node and alternate between nodes and separator tokens.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="nodesAndTokens">A alternating sequence of nodes and tokens.</param>
Public Shared Function SeparatedList(Of TNode As SyntaxNode)(nodesAndTokens As IEnumerable(Of SyntaxNodeOrToken)) As SeparatedSyntaxList(Of TNode)
Return SeparatedList(Of TNode)(NodeOrTokenList(nodesAndTokens))
End Function
''' <summary>
''' Creates a separated list from a <see cref="SyntaxNodeOrTokenList"/>.
''' The <see cref="SyntaxNodeOrTokenList"/> must start with a node and alternate between nodes and separator tokens.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="nodesAndTokens">An alternating list of nodes and tokens.</param>
Public Shared Function SeparatedList(Of TNode As SyntaxNode)(nodesAndTokens As SyntaxNodeOrTokenList) As SeparatedSyntaxList(Of TNode)
If Not HasSeparatedNodeTokenPattern(nodesAndTokens) Then
Throw New ArgumentException(CodeAnalysisResources.NodeOrTokenOutOfSequence)
End If
If Not NodesAreCorrectType(Of TNode)(nodesAndTokens) Then
Throw New ArgumentException(CodeAnalysisResources.UnexpectedTypeOfNodeInList)
End If
Return New SeparatedSyntaxList(Of TNode)(nodesAndTokens)
End Function
Private Shared Function NodesAreCorrectType(Of TNode)(list As SyntaxNodeOrTokenList) As Boolean
Dim n = list.Count
For i = 0 To n - 1
Dim element = list(i)
If element.IsNode AndAlso Not (TypeOf element.AsNode() Is TNode) Then
Return False
End If
Next
Return True
End Function
Private Shared Function HasSeparatedNodeTokenPattern(list As SyntaxNodeOrTokenList) As Boolean
For i = 0 To list.Count - 1
Dim element = list(i)
If element.IsToken = ((i And 1) = 0) Then
Return False
End If
Next
Return True
End Function
''' <summary>
''' Creates an empty <see cref="SyntaxNodeOrTokenList"/>.
''' </summary>
Public Shared Function NodeOrTokenList() As SyntaxNodeOrTokenList
Return Nothing
End Function
''' <summary>
''' Creates a <see cref="SyntaxNodeOrTokenList"/> from a sequence of nodes and tokens.
''' </summary>
''' <param name="nodesAndTokens">A sequence of nodes and tokens.</param>
Public Shared Function NodeOrTokenList(nodesAndTokens As IEnumerable(Of SyntaxNodeOrToken)) As SyntaxNodeOrTokenList
Return New SyntaxNodeOrTokenList(nodesAndTokens)
End Function
''' <summary>
''' Creates a <see cref="SyntaxNodeOrTokenList"/> from one or more nodes and tokens.
''' </summary>
''' <param name="nodesAndTokens">An array of nodes and tokens.</param>
Public Shared Function NodeOrTokenList(ParamArray nodesAndTokens As SyntaxNodeOrToken()) As SyntaxNodeOrTokenList
Return New SyntaxNodeOrTokenList(nodesAndTokens)
End Function
#End Region
Public Shared Function InvocationExpression(expression As ExpressionSyntax) As InvocationExpressionSyntax
Return InvocationExpression(expression, Nothing)
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.
'-----------------------------------------------------------------------------------------------------------
' Contains hand-written factories for the SyntaxNodes. Most factories are
' code-generated into SyntaxNodes.vb, but some are easier to hand-write.
'-----------------------------------------------------------------------------------------------------------
Imports System.Threading
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts
Imports InternalSyntax = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.Syntax
Imports System.Collections.Immutable
Imports System.ComponentModel
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class SyntaxFactory
#Region "ParseMethods"
' direct access to parsing for common grammar areas
''' <summary>
''' Create a new syntax tree from a syntax node.
''' </summary>
Public Shared Function SyntaxTree(
root As SyntaxNode,
Optional options As ParseOptions = Nothing,
Optional path As String = "",
Optional encoding As Encoding = Nothing) As SyntaxTree
Return VisualBasicSyntaxTree.Create(DirectCast(root, VisualBasicSyntaxNode), DirectCast(options, VisualBasicParseOptions), path, encoding)
End Function
''' <summary>
''' Produces a syntax tree by parsing the source text.
''' </summary>
Public Shared Function ParseSyntaxTree(
text As String,
options As ParseOptions,
path As String,
encoding As Encoding,
cancellationToken As CancellationToken) As SyntaxTree
Return ParseSyntaxTree(SourceText.From(text, encoding), options, path, cancellationToken)
End Function
''' <summary>
''' Produces a syntax tree by parsing the source text.
''' </summary>
Public Shared Function ParseSyntaxTree(
text As SourceText,
options As ParseOptions,
path As String,
cancellationToken As CancellationToken) As SyntaxTree
Return VisualBasicSyntaxTree.ParseText(text, DirectCast(options, VisualBasicParseOptions), path, cancellationToken)
End Function
#Disable Warning RS0026 ' Do not add multiple public overloads with optional parameters.
#Disable Warning RS0027 ' Public API with optional parameter(s) should have the most parameters amongst its public overloads.
''' <summary>
''' Produces a syntax tree by parsing the source text.
''' </summary>
Public Shared Function ParseSyntaxTree(
text As String,
Optional options As ParseOptions = Nothing,
Optional path As String = "",
Optional encoding As Encoding = Nothing,
Optional diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As SyntaxTree
Return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, cancellationToken)
End Function
''' <summary>
''' Produces a syntax tree by parsing the source text.
''' </summary>
Public Shared Function ParseSyntaxTree(
text As SourceText,
Optional options As ParseOptions = Nothing,
Optional path As String = "",
Optional diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) = Nothing,
Optional cancellationToken As CancellationToken = Nothing) As SyntaxTree
Return VisualBasicSyntaxTree.ParseText(text, DirectCast(options, VisualBasicParseOptions), path, diagnosticOptions, cancellationToken)
End Function
#Enable Warning RS0026 ' Do not add multiple public overloads with optional parameters.
#Enable Warning RS0027 ' Public API with optional parameter(s) should have the most parameters amongst its public overloads.
''' <summary>
'''Parse the input for leading trivia.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseLeadingTrivia(text As String, Optional offset As Integer = 0) As SyntaxTriviaList
Dim s = New InternalSyntax.Scanner(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
Using s
Return New SyntaxTriviaList(Nothing, s.ScanMultilineTrivia().Node, 0, 0)
End Using
End Function
''' <summary>
''' Parse the input for trailing trivia.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseTrailingTrivia(text As String, Optional offset As Integer = 0) As SyntaxTriviaList
Dim s = New InternalSyntax.Scanner(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
Using s
Return New SyntaxTriviaList(Nothing, s.ScanSingleLineTrivia().Node, 0, 0)
End Using
End Function
''' <summary>
''' Parse one token.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
''' <param name="startStatement">Scan using rules for the start of a statement</param>
Public Shared Function ParseToken(text As String, Optional offset As Integer = 0, Optional startStatement As Boolean = False) As SyntaxToken
Dim s = New InternalSyntax.Scanner(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
Using s
Dim state = If(startStatement,
InternalSyntax.ScannerState.VBAllowLeadingMultilineTrivia,
InternalSyntax.ScannerState.VB)
s.GetNextTokenInState(state)
Return New SyntaxToken(Nothing, s.GetCurrentToken, 0, 0)
End Using
End Function
''' <summary>
''' Parse tokens in the input.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
''' <param name="initialTokenPosition">The position of the first token</param>
Public Shared Iterator Function ParseTokens(text As String,
Optional offset As Integer = 0,
Optional initialTokenPosition As Integer = 0,
Optional options As VisualBasicParseOptions = Nothing) As IEnumerable(Of SyntaxToken)
Using parser = New InternalSyntax.Parser(MakeSourceText(text, offset), If(options, VisualBasicParseOptions.Default))
Dim state = InternalSyntax.ScannerState.VBAllowLeadingMultilineTrivia
Dim curTk As InternalSyntax.SyntaxToken
Do
parser.GetNextToken(state)
curTk = parser.CurrentToken
Yield New SyntaxToken(Nothing, curTk, initialTokenPosition, 0)
initialTokenPosition += curTk.FullWidth
state = If(curTk.Kind = SyntaxKind.StatementTerminatorToken,
InternalSyntax.ScannerState.VBAllowLeadingMultilineTrivia,
InternalSyntax.ScannerState.VB)
Loop While curTk.Kind <> SyntaxKind.EndOfFileToken
End Using
End Function
''' <summary>
''' Parse a name.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseName(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As NameSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
p.GetNextToken()
' "allow everything" arguments
Dim node = p.ParseName(
requireQualification:=False,
allowGlobalNameSpace:=True,
allowGenericArguments:=True,
allowGenericsWithoutOf:=False,
disallowGenericArgumentsOnLastQualifiedName:=False,
allowEmptyGenericArguments:=True,
allowedEmptyGenericArguments:=True)
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), NameSyntax)
End Using
End Function
''' <summary>
''' Parse a type name.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseTypeName(text As String, Optional offset As Integer = 0, Optional options As ParseOptions = Nothing, Optional consumeFullText As Boolean = True) As TypeSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), If(DirectCast(options, VisualBasicParseOptions), VisualBasicParseOptions.Default))
p.GetNextToken()
Dim node = p.ParseGeneralType()
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), TypeSyntax)
End Using
End Function
'' Backcompat overload, do not touch
''' <summary>
''' Parse a type name.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
<EditorBrowsable(EditorBrowsableState.Never)>
Public Shared Function ParseTypeName(text As String, offset As Integer, consumeFullText As Boolean) As TypeSyntax
Return ParseTypeName(text, offset, options:=Nothing, consumeFullText)
End Function
''' <summary>
''' Parse an expression.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseExpression(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As ExpressionSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
p.GetNextToken()
Dim node = p.ParseExpression()
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), ExpressionSyntax)
End Using
End Function
''' <summary>
''' Parse an executable statement.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseExecutableStatement(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As StatementSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
Dim node = p.ParseExecutableStatement()
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), StatementSyntax)
End Using
End Function
''' <summary>
''' Parse a compilation unit (a single source file).
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseCompilationUnit(text As String, Optional offset As Integer = 0, Optional options As VisualBasicParseOptions = Nothing) As CompilationUnitSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), If(options, VisualBasicParseOptions.Default))
Return DirectCast(p.ParseCompilationUnit().CreateRed(Nothing, 0), CompilationUnitSyntax)
End Using
End Function
''' <summary>
''' Parse a parameter list.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseParameterList(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As ParameterListSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
p.GetNextToken()
Dim node = p.ParseParameterList()
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), ParameterListSyntax)
End Using
End Function
''' <summary>
''' Parse an argument list.
''' </summary>
''' <param name="text">The input string</param>
''' <param name="offset">The starting offset in the string</param>
Public Shared Function ParseArgumentList(text As String, Optional offset As Integer = 0, Optional consumeFullText As Boolean = True) As ArgumentListSyntax
Using p = New InternalSyntax.Parser(MakeSourceText(text, offset), VisualBasicParseOptions.Default)
p.GetNextToken()
Dim node = p.ParseParenthesizedArguments()
Return DirectCast(If(consumeFullText, p.ConsumeUnexpectedTokens(node), node).CreateRed(Nothing, 0), ArgumentListSyntax)
End Using
End Function
''' <summary>
''' Helper method for wrapping a string and offset in a SourceText.
''' </summary>
Friend Shared Function MakeSourceText(text As String, offset As Integer) As SourceText
Return SourceText.From(text, Encoding.UTF8).GetSubText(offset)
End Function
''' <summary>
''' Try parse the attribute represented as a stand-alone string like [cref="A.B"] and recognize
''' 'cref' and 'name' attributes like in documentation-comment mode. This method should only be
''' used internally from code handling documentation comment includes.
''' </summary>
Friend Shared Function ParseDocCommentAttributeAsStandAloneEntity(text As String, parentElementName As String) As BaseXmlAttributeSyntax
Using scanner As New InternalSyntax.Scanner(MakeSourceText(text, 0), VisualBasicParseOptions.Default) ' NOTE: Default options should be enough
scanner.ForceScanningXmlDocMode()
Dim parser = New InternalSyntax.Parser(scanner)
parser.GetNextToken(InternalSyntax.ScannerState.Element)
Dim xmlName = InternalSyntax.SyntaxFactory.XmlName(
Nothing, InternalSyntax.SyntaxFactory.XmlNameToken(parentElementName, SyntaxKind.XmlNameToken, Nothing, Nothing))
Return DirectCast(
parser.ParseXmlAttribute(
requireLeadingWhitespace:=False,
AllowNameAsExpression:=False,
xmlElementName:=xmlName).CreateRed(Nothing, 0), BaseXmlAttributeSyntax)
End Using
End Function
#End Region
#Region "TokenFactories"
Public Shared Function IntegerLiteralToken(text As String, base As LiteralBase, typeSuffix As TypeCharacter, value As ULong) As SyntaxToken
Return IntegerLiteralToken(SyntaxFactory.TriviaList(ElasticMarker), text, base, typeSuffix, value, SyntaxFactory.TriviaList(ElasticMarker))
End Function
Public Shared Function IntegerLiteralToken(leadingTrivia As SyntaxTriviaList, text As String, base As LiteralBase, typeSuffix As TypeCharacter, value As ULong, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentNullException(NameOf(text))
End If
Return New SyntaxToken(Nothing, InternalSyntax.SyntaxFactory.IntegerLiteralToken(text, base, typeSuffix, value, leadingTrivia.Node, trailingTrivia.Node), 0, 0)
End Function
Public Shared Function FloatingLiteralToken(text As String, typeSuffix As TypeCharacter, value As Double) As SyntaxToken
Return FloatingLiteralToken(SyntaxFactory.TriviaList(ElasticMarker), text, typeSuffix, value, SyntaxFactory.TriviaList(ElasticMarker))
End Function
Public Shared Function FloatingLiteralToken(leadingTrivia As SyntaxTriviaList, text As String, typeSuffix As TypeCharacter, value As Double, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentNullException(NameOf(text))
End If
Return New SyntaxToken(Nothing, InternalSyntax.SyntaxFactory.FloatingLiteralToken(text, typeSuffix, value, leadingTrivia.Node, trailingTrivia.Node), 0, 0)
End Function
Public Shared Function Identifier(text As String, isBracketed As Boolean, identifierText As String, typeCharacter As TypeCharacter) As SyntaxToken
Return Identifier(SyntaxFactory.TriviaList(ElasticMarker), text, isBracketed, identifierText, typeCharacter, SyntaxFactory.TriviaList(ElasticMarker))
End Function
Friend Shared Function Identifier(leadingTrivia As SyntaxTrivia, text As String, isBracketed As Boolean, identifierText As String, typeCharacter As TypeCharacter, trailingTrivia As SyntaxTrivia) As SyntaxToken
Return Identifier(SyntaxTriviaList.Create(leadingTrivia), text, isBracketed, identifierText, typeCharacter, SyntaxTriviaList.Create(trailingTrivia))
End Function
Public Shared Function Identifier(leadingTrivia As SyntaxTriviaList, text As String, isBracketed As Boolean, identifierText As String, typeCharacter As TypeCharacter, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentException(NameOf(text))
End If
Return New SyntaxToken(Nothing, New InternalSyntax.ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, leadingTrivia.Node, trailingTrivia.Node, SyntaxKind.IdentifierToken, isBracketed, identifierText, typeCharacter), 0, 0)
End Function
Public Shared Function Identifier(text As String) As SyntaxToken
Return Identifier(SyntaxFactory.TriviaList(ElasticMarker), text, SyntaxFactory.TriviaList(ElasticMarker))
End Function
Friend Shared Function Identifier(leadingTrivia As SyntaxTrivia, text As String, trailingTrivia As SyntaxTrivia) As SyntaxToken
Return Identifier(SyntaxTriviaList.Create(leadingTrivia), text, SyntaxTriviaList.Create(trailingTrivia))
End Function
Public Shared Function Identifier(leadingTrivia As SyntaxTriviaList, text As String, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentException(NameOf(text))
End If
Return New SyntaxToken(Nothing, New InternalSyntax.ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, text, leadingTrivia.Node, trailingTrivia.Node, SyntaxKind.IdentifierToken, False, text, TypeCharacter.None), 0, 0)
End Function
''' <summary>
''' Create a bracketed identifier.
''' </summary>
Public Shared Function BracketedIdentifier(text As String) As SyntaxToken
Return BracketedIdentifier(SyntaxFactory.TriviaList(ElasticMarker), text, SyntaxFactory.TriviaList(ElasticMarker))
End Function
''' <summary>
''' Create a bracketed identifier.
''' </summary>
Public Shared Function BracketedIdentifier(leadingTrivia As SyntaxTriviaList, text As String, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentException(NameOf(text))
End If
If MakeHalfWidthIdentifier(text.First) = "[" AndAlso MakeHalfWidthIdentifier(text.Last) = "]" Then
Throw New ArgumentException(NameOf(text))
End If
Return New SyntaxToken(Nothing, New InternalSyntax.ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, "[" + text + "]", leadingTrivia.Node, trailingTrivia.Node, SyntaxKind.IdentifierToken, True, text, TypeCharacter.None), 0, 0)
End Function
''' <summary>
''' Create a missing identifier.
''' </summary>
Friend Shared Function MissingIdentifier() As SyntaxToken
Return New SyntaxToken(Nothing, New InternalSyntax.SimpleIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, "",
ElasticMarker.UnderlyingNode, ElasticMarker.UnderlyingNode), 0, 0)
End Function
''' <summary>
''' Create a missing contextual keyword.
''' </summary>
Friend Shared Function MissingIdentifier(kind As SyntaxKind) As SyntaxToken
Return New SyntaxToken(Nothing, New InternalSyntax.ComplexIdentifierSyntax(SyntaxKind.IdentifierToken, Nothing, Nothing, "",
ElasticMarker.UnderlyingNode, ElasticMarker.UnderlyingNode,
kind, False, "", TypeCharacter.None), 0, 0)
End Function
''' <summary>
''' Create a missing keyword.
''' </summary>
Friend Shared Function MissingKeyword(kind As SyntaxKind) As SyntaxToken
Return New SyntaxToken(Nothing, New InternalSyntax.KeywordSyntax(kind, "",
ElasticMarker.UnderlyingNode, ElasticMarker.UnderlyingNode), 0, 0)
End Function
''' <summary>
''' Create a missing punctuation mark.
''' </summary>
Friend Shared Function MissingPunctuation(kind As SyntaxKind) As SyntaxToken
Return New SyntaxToken(Nothing, New InternalSyntax.PunctuationSyntax(kind, "",
ElasticMarker.UnderlyingNode, ElasticMarker.UnderlyingNode), 0, 0)
End Function
''' <summary>
''' Create a missing string literal.
''' </summary>
Friend Shared Function MissingStringLiteral() As SyntaxToken
Return SyntaxFactory.StringLiteralToken("", "")
End Function
''' <summary>
''' Create a missing character literal.
''' </summary>
Friend Shared Function MissingCharacterLiteralToken() As SyntaxToken
Return CharacterLiteralToken("", Nothing)
End Function
''' <summary>
''' Create a missing integer literal.
''' </summary>
Friend Shared Function MissingIntegerLiteralToken() As SyntaxToken
Return IntegerLiteralToken(SyntaxFactory.TriviaList(ElasticMarker), "", LiteralBase.Decimal, TypeCharacter.None, Nothing, SyntaxFactory.TriviaList(ElasticMarker))
End Function
''' <summary>
''' Creates a copy of a token.
''' <para name="err"></para>
''' <para name="trivia"></para>
''' </summary>
''' <returns>The new token</returns>
Friend Shared Function MissingToken(kind As SyntaxKind) As SyntaxToken
Dim t As SyntaxToken
Select Case kind
Case SyntaxKind.StatementTerminatorToken
t = SyntaxFactory.Token(SyntaxKind.StatementTerminatorToken)
Case SyntaxKind.EndOfFileToken
t = SyntaxFactory.Token(SyntaxKind.EndOfFileToken)
Case SyntaxKind.AddHandlerKeyword,
SyntaxKind.AddressOfKeyword,
SyntaxKind.AliasKeyword,
SyntaxKind.AndKeyword,
SyntaxKind.AndAlsoKeyword,
SyntaxKind.AsKeyword,
SyntaxKind.BooleanKeyword,
SyntaxKind.ByRefKeyword,
SyntaxKind.ByteKeyword,
SyntaxKind.ByValKeyword,
SyntaxKind.CallKeyword,
SyntaxKind.CaseKeyword,
SyntaxKind.CatchKeyword,
SyntaxKind.CBoolKeyword,
SyntaxKind.CByteKeyword,
SyntaxKind.CCharKeyword,
SyntaxKind.CDateKeyword,
SyntaxKind.CDecKeyword,
SyntaxKind.CDblKeyword,
SyntaxKind.CharKeyword,
SyntaxKind.CIntKeyword,
SyntaxKind.ClassKeyword,
SyntaxKind.CLngKeyword,
SyntaxKind.CObjKeyword,
SyntaxKind.ConstKeyword,
SyntaxKind.ContinueKeyword,
SyntaxKind.CSByteKeyword,
SyntaxKind.CShortKeyword,
SyntaxKind.CSngKeyword,
SyntaxKind.CStrKeyword,
SyntaxKind.CTypeKeyword,
SyntaxKind.CUIntKeyword,
SyntaxKind.CULngKeyword,
SyntaxKind.CUShortKeyword,
SyntaxKind.DateKeyword,
SyntaxKind.DecimalKeyword,
SyntaxKind.DeclareKeyword,
SyntaxKind.DefaultKeyword,
SyntaxKind.DelegateKeyword,
SyntaxKind.DimKeyword,
SyntaxKind.DirectCastKeyword,
SyntaxKind.DoKeyword,
SyntaxKind.DoubleKeyword,
SyntaxKind.EachKeyword,
SyntaxKind.ElseKeyword,
SyntaxKind.ElseIfKeyword,
SyntaxKind.EndKeyword,
SyntaxKind.EnumKeyword,
SyntaxKind.EraseKeyword,
SyntaxKind.ErrorKeyword,
SyntaxKind.EventKeyword,
SyntaxKind.ExitKeyword,
SyntaxKind.FalseKeyword,
SyntaxKind.FinallyKeyword,
SyntaxKind.ForKeyword,
SyntaxKind.FriendKeyword,
SyntaxKind.FunctionKeyword,
SyntaxKind.GetKeyword,
SyntaxKind.GetTypeKeyword,
SyntaxKind.GetXmlNamespaceKeyword,
SyntaxKind.GlobalKeyword,
SyntaxKind.GoToKeyword,
SyntaxKind.HandlesKeyword,
SyntaxKind.IfKeyword,
SyntaxKind.ImplementsKeyword,
SyntaxKind.ImportsKeyword,
SyntaxKind.InKeyword,
SyntaxKind.InheritsKeyword,
SyntaxKind.IntegerKeyword,
SyntaxKind.InterfaceKeyword,
SyntaxKind.IsKeyword,
SyntaxKind.IsNotKeyword,
SyntaxKind.LetKeyword,
SyntaxKind.LibKeyword,
SyntaxKind.LikeKeyword,
SyntaxKind.LongKeyword,
SyntaxKind.LoopKeyword,
SyntaxKind.MeKeyword,
SyntaxKind.ModKeyword,
SyntaxKind.ModuleKeyword,
SyntaxKind.MustInheritKeyword,
SyntaxKind.MustOverrideKeyword,
SyntaxKind.MyBaseKeyword,
SyntaxKind.MyClassKeyword,
SyntaxKind.NameOfKeyword,
SyntaxKind.NamespaceKeyword,
SyntaxKind.NarrowingKeyword,
SyntaxKind.NextKeyword,
SyntaxKind.NewKeyword,
SyntaxKind.NotKeyword,
SyntaxKind.NothingKeyword,
SyntaxKind.NotInheritableKeyword,
SyntaxKind.NotOverridableKeyword,
SyntaxKind.ObjectKeyword,
SyntaxKind.OfKeyword,
SyntaxKind.OnKeyword,
SyntaxKind.OperatorKeyword,
SyntaxKind.OptionKeyword,
SyntaxKind.OptionalKeyword,
SyntaxKind.OrKeyword,
SyntaxKind.OrElseKeyword,
SyntaxKind.OverloadsKeyword,
SyntaxKind.OverridableKeyword,
SyntaxKind.OverridesKeyword,
SyntaxKind.ParamArrayKeyword,
SyntaxKind.PartialKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.PropertyKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.RaiseEventKeyword,
SyntaxKind.ReadOnlyKeyword,
SyntaxKind.ReDimKeyword,
SyntaxKind.ReferenceKeyword,
SyntaxKind.REMKeyword,
SyntaxKind.RemoveHandlerKeyword,
SyntaxKind.ResumeKeyword,
SyntaxKind.ReturnKeyword,
SyntaxKind.SByteKeyword,
SyntaxKind.SelectKeyword,
SyntaxKind.SetKeyword,
SyntaxKind.ShadowsKeyword,
SyntaxKind.SharedKeyword,
SyntaxKind.ShortKeyword,
SyntaxKind.SingleKeyword,
SyntaxKind.StaticKeyword,
SyntaxKind.StepKeyword,
SyntaxKind.StopKeyword,
SyntaxKind.StringKeyword,
SyntaxKind.StructureKeyword,
SyntaxKind.SubKeyword,
SyntaxKind.SyncLockKeyword,
SyntaxKind.ThenKeyword,
SyntaxKind.ThrowKeyword,
SyntaxKind.ToKeyword,
SyntaxKind.TrueKeyword,
SyntaxKind.TryKeyword,
SyntaxKind.TryCastKeyword,
SyntaxKind.TypeOfKeyword,
SyntaxKind.UIntegerKeyword,
SyntaxKind.ULongKeyword,
SyntaxKind.UShortKeyword,
SyntaxKind.UsingKeyword,
SyntaxKind.WhenKeyword,
SyntaxKind.WhileKeyword,
SyntaxKind.WideningKeyword,
SyntaxKind.WithKeyword,
SyntaxKind.WithEventsKeyword,
SyntaxKind.WriteOnlyKeyword,
SyntaxKind.XorKeyword,
SyntaxKind.EndIfKeyword,
SyntaxKind.GosubKeyword,
SyntaxKind.VariantKeyword,
SyntaxKind.WendKeyword,
SyntaxKind.OutKeyword
t = SyntaxFactory.MissingKeyword(kind)
Case SyntaxKind.AggregateKeyword,
SyntaxKind.AllKeyword,
SyntaxKind.AnsiKeyword,
SyntaxKind.AscendingKeyword,
SyntaxKind.AssemblyKeyword,
SyntaxKind.AutoKeyword,
SyntaxKind.BinaryKeyword,
SyntaxKind.ByKeyword,
SyntaxKind.CompareKeyword,
SyntaxKind.CustomKeyword,
SyntaxKind.DescendingKeyword,
SyntaxKind.DisableKeyword,
SyntaxKind.DistinctKeyword,
SyntaxKind.EnableKeyword,
SyntaxKind.EqualsKeyword,
SyntaxKind.ExplicitKeyword,
SyntaxKind.ExternalSourceKeyword,
SyntaxKind.ExternalChecksumKeyword,
SyntaxKind.FromKeyword,
SyntaxKind.GroupKeyword,
SyntaxKind.InferKeyword,
SyntaxKind.IntoKeyword,
SyntaxKind.IsFalseKeyword,
SyntaxKind.IsTrueKeyword,
SyntaxKind.JoinKeyword,
SyntaxKind.KeyKeyword,
SyntaxKind.MidKeyword,
SyntaxKind.OffKeyword,
SyntaxKind.OrderKeyword,
SyntaxKind.PreserveKeyword,
SyntaxKind.RegionKeyword,
SyntaxKind.SkipKeyword,
SyntaxKind.StrictKeyword,
SyntaxKind.TextKeyword,
SyntaxKind.TakeKeyword,
SyntaxKind.UnicodeKeyword,
SyntaxKind.UntilKeyword,
SyntaxKind.WarningKeyword,
SyntaxKind.WhereKeyword
' These are identifiers that have a contextual kind
Return SyntaxFactory.MissingIdentifier(kind)
Case SyntaxKind.ExclamationToken,
SyntaxKind.CommaToken,
SyntaxKind.HashToken,
SyntaxKind.AmpersandToken,
SyntaxKind.SingleQuoteToken,
SyntaxKind.OpenParenToken,
SyntaxKind.CloseParenToken,
SyntaxKind.OpenBraceToken,
SyntaxKind.CloseBraceToken,
SyntaxKind.DoubleQuoteToken,
SyntaxKind.SemicolonToken,
SyntaxKind.AsteriskToken,
SyntaxKind.PlusToken,
SyntaxKind.MinusToken,
SyntaxKind.DotToken,
SyntaxKind.SlashToken,
SyntaxKind.ColonToken,
SyntaxKind.LessThanToken,
SyntaxKind.LessThanEqualsToken,
SyntaxKind.LessThanGreaterThanToken,
SyntaxKind.EqualsToken,
SyntaxKind.GreaterThanToken,
SyntaxKind.GreaterThanEqualsToken,
SyntaxKind.BackslashToken,
SyntaxKind.CaretToken,
SyntaxKind.ColonEqualsToken,
SyntaxKind.AmpersandEqualsToken,
SyntaxKind.AsteriskEqualsToken,
SyntaxKind.PlusEqualsToken,
SyntaxKind.MinusEqualsToken,
SyntaxKind.SlashEqualsToken,
SyntaxKind.BackslashEqualsToken,
SyntaxKind.CaretEqualsToken,
SyntaxKind.LessThanLessThanToken,
SyntaxKind.GreaterThanGreaterThanToken,
SyntaxKind.LessThanLessThanEqualsToken,
SyntaxKind.GreaterThanGreaterThanEqualsToken,
SyntaxKind.QuestionToken
t = SyntaxFactory.MissingPunctuation(kind)
Case SyntaxKind.FloatingLiteralToken
t = SyntaxFactory.FloatingLiteralToken("", TypeCharacter.None, Nothing)
Case SyntaxKind.DecimalLiteralToken
t = SyntaxFactory.DecimalLiteralToken("", TypeCharacter.None, Nothing)
Case SyntaxKind.DateLiteralToken
t = SyntaxFactory.DateLiteralToken("", Nothing)
Case SyntaxKind.XmlNameToken
t = SyntaxFactory.XmlNameToken("", SyntaxKind.XmlNameToken)
Case SyntaxKind.XmlTextLiteralToken
t = SyntaxFactory.XmlTextLiteralToken("", "")
Case SyntaxKind.SlashGreaterThanToken,
SyntaxKind.LessThanSlashToken,
SyntaxKind.LessThanExclamationMinusMinusToken,
SyntaxKind.MinusMinusGreaterThanToken,
SyntaxKind.LessThanQuestionToken,
SyntaxKind.QuestionGreaterThanToken,
SyntaxKind.LessThanPercentEqualsToken,
SyntaxKind.PercentGreaterThanToken,
SyntaxKind.BeginCDataToken,
SyntaxKind.EndCDataToken
t = SyntaxFactory.MissingPunctuation(kind)
Case SyntaxKind.IdentifierToken
t = SyntaxFactory.MissingIdentifier()
Case SyntaxKind.IntegerLiteralToken
t = MissingIntegerLiteralToken()
Case SyntaxKind.StringLiteralToken
t = SyntaxFactory.MissingStringLiteral()
Case SyntaxKind.CharacterLiteralToken
t = SyntaxFactory.MissingCharacterLiteralToken()
Case Else
Throw ExceptionUtilities.UnexpectedValue(kind)
End Select
Return t
End Function
Public Shared Function BadToken(text As String) As SyntaxToken
Return BadToken(Nothing, text, Nothing)
End Function
Public Shared Function BadToken(leadingTrivia As SyntaxTriviaList, text As String, trailingTrivia As SyntaxTriviaList) As SyntaxToken
If text Is Nothing Then
Throw New ArgumentException(NameOf(text))
End If
Return New SyntaxToken(Nothing, New InternalSyntax.BadTokenSyntax(SyntaxKind.BadToken, InternalSyntax.SyntaxSubKind.None, Nothing, Nothing, text,
leadingTrivia.Node, trailingTrivia.Node), 0, 0)
End Function
#End Region
#Region "TriviaFactories"
Public Shared Function Trivia(node As StructuredTriviaSyntax) As SyntaxTrivia
Return New SyntaxTrivia(Nothing, node.Green, position:=0, index:=0)
End Function
#End Region
#Region "ListFactories"
''' <summary>
''' Creates an empty list of syntax nodes.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
Public Shared Function List(Of TNode As SyntaxNode)() As SyntaxList(Of TNode)
Return New SyntaxList(Of TNode)
End Function
''' <summary>
''' Creates a singleton list of syntax nodes.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="node">The single element node.</param>
Public Shared Function SingletonList(Of TNode As SyntaxNode)(node As TNode) As SyntaxList(Of TNode)
Return New SyntaxList(Of TNode)(node)
End Function
''' <summary>
''' Creates a list of syntax nodes.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="nodes">A sequence of element nodes.</param>
Public Shared Function List(Of TNode As SyntaxNode)(nodes As IEnumerable(Of TNode)) As SyntaxList(Of TNode)
Return New SyntaxList(Of TNode)(nodes)
End Function
''' <summary>
''' Creates an empty list of tokens.
''' </summary>
Public Shared Function TokenList() As SyntaxTokenList
Return New SyntaxTokenList()
End Function
''' <summary>
''' Creates a singleton list of tokens.
''' </summary>
''' <param name="token">The single token.</param>
Public Shared Function TokenList(token As SyntaxToken) As SyntaxTokenList
Return New SyntaxTokenList(token)
End Function
''' <summary>
''' Creates a list of tokens.
''' </summary>
''' <param name="tokens">An array of tokens.</param>
Public Shared Function TokenList(ParamArray tokens As SyntaxToken()) As SyntaxTokenList
Return New SyntaxTokenList(tokens)
End Function
''' <summary>
''' Creates a list of tokens.
''' </summary>
''' <param name="tokens"></param>
Public Shared Function TokenList(tokens As IEnumerable(Of SyntaxToken)) As SyntaxTokenList
Return New SyntaxTokenList(tokens)
End Function
''' <summary>
''' Creates an empty list of trivia.
''' </summary>
Public Shared Function TriviaList() As SyntaxTriviaList
Return New SyntaxTriviaList()
End Function
''' <summary>
''' Creates a singleton list of trivia.
''' </summary>
''' <param name="trivia">A single trivia.</param>
Public Shared Function TriviaList(trivia As SyntaxTrivia) As SyntaxTriviaList
Return New SyntaxTriviaList(Nothing, trivia.UnderlyingNode)
End Function
''' <summary>
''' Creates a list of trivia.
''' </summary>
''' <param name="trivias">An array of trivia.</param>
Public Shared Function TriviaList(ParamArray trivias As SyntaxTrivia()) As SyntaxTriviaList
Return New SyntaxTriviaList(trivias)
End Function
''' <summary>
''' Creates a list of trivia.
''' </summary>
''' <param name="trivias">A sequence of trivia.</param>
Public Shared Function TriviaList(trivias As IEnumerable(Of SyntaxTrivia)) As SyntaxTriviaList
Return New SyntaxTriviaList(trivias)
End Function
''' <summary>
''' Creates an empty separated list.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
Public Shared Function SeparatedList(Of TNode As SyntaxNode)() As SeparatedSyntaxList(Of TNode)
Return New SeparatedSyntaxList(Of TNode)
End Function
''' <summary>
''' Creates a singleton separated list.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="node">A single node.</param>
Public Shared Function SingletonSeparatedList(Of TNode As SyntaxNode)(node As TNode) As SeparatedSyntaxList(Of TNode)
Return New SeparatedSyntaxList(Of TNode)(node, 0)
End Function
''' <summary>
''' Creates a separated list of nodes from a sequence of nodes, synthesizing comma separators in between.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="nodes">A sequence of syntax nodes.</param>
Public Shared Function SeparatedList(Of TNode As SyntaxNode)(nodes As IEnumerable(Of TNode)) As SeparatedSyntaxList(Of TNode)
If nodes Is Nothing Then Return Nothing
Dim collection = TryCast(nodes, ICollection(Of TNode))
If collection IsNot Nothing AndAlso collection.Count = 0 Then Return Nothing
Using enumerator = nodes.GetEnumerator()
If Not enumerator.MoveNext() Then Return Nothing
Dim firstNode = enumerator.Current
If Not enumerator.MoveNext() Then Return SingletonSeparatedList(firstNode)
Dim builder As New SeparatedSyntaxListBuilder(Of TNode)(If(collection IsNot Nothing, (collection.Count * 2) - 1, 3))
builder.Add(firstNode)
Dim commaToken = Token(SyntaxKind.CommaToken)
Do
builder.AddSeparator(commaToken)
builder.Add(enumerator.Current)
Loop While enumerator.MoveNext()
Return builder.ToList()
End Using
End Function
''' <summary>
''' Creates a separated list of nodes from a sequence of nodes and a sequence of separator tokens.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="nodes">A sequence of syntax nodes.</param>
''' <param name="separators">A sequence of token to be interleaved between the nodes. The number of tokens must
''' be one less than the number of nodes.</param>
Public Shared Function SeparatedList(Of TNode As SyntaxNode)(nodes As IEnumerable(Of TNode), separators As IEnumerable(Of SyntaxToken)) As SeparatedSyntaxList(Of TNode)
If nodes IsNot Nothing Then
Dim nodeEnum = nodes.GetEnumerator
Dim builder = SeparatedSyntaxListBuilder(Of TNode).Create()
If separators IsNot Nothing Then
For Each separator In separators
' The number of nodes must be equal to or one greater than the number of separators
If nodeEnum.MoveNext() Then
builder.Add(nodeEnum.Current)
Else
Throw New ArgumentException()
End If
builder.AddSeparator(separator)
Next
End If
' Check that there is zero or one node left in the enumerator
If nodeEnum.MoveNext() Then
builder.Add(nodeEnum.Current)
If nodeEnum.MoveNext() Then
Throw New ArgumentException()
End If
End If
Return builder.ToList()
ElseIf separators Is Nothing Then
' Both are nothing so return empty list
Return New SeparatedSyntaxList(Of TNode)
Else
' No nodes but have separators. This is an argument error.
Throw New ArgumentException()
End If
End Function
''' <summary>
''' Creates a separated list from a sequence of nodes or tokens.
''' The sequence must start with a node and alternate between nodes and separator tokens.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="nodesAndTokens">A alternating sequence of nodes and tokens.</param>
Public Shared Function SeparatedList(Of TNode As SyntaxNode)(nodesAndTokens As IEnumerable(Of SyntaxNodeOrToken)) As SeparatedSyntaxList(Of TNode)
Return SeparatedList(Of TNode)(NodeOrTokenList(nodesAndTokens))
End Function
''' <summary>
''' Creates a separated list from a <see cref="SyntaxNodeOrTokenList"/>.
''' The <see cref="SyntaxNodeOrTokenList"/> must start with a node and alternate between nodes and separator tokens.
''' </summary>
''' <typeparam name="TNode">The specific type of the element nodes.</typeparam>
''' <param name="nodesAndTokens">An alternating list of nodes and tokens.</param>
Public Shared Function SeparatedList(Of TNode As SyntaxNode)(nodesAndTokens As SyntaxNodeOrTokenList) As SeparatedSyntaxList(Of TNode)
If Not HasSeparatedNodeTokenPattern(nodesAndTokens) Then
Throw New ArgumentException(CodeAnalysisResources.NodeOrTokenOutOfSequence)
End If
If Not NodesAreCorrectType(Of TNode)(nodesAndTokens) Then
Throw New ArgumentException(CodeAnalysisResources.UnexpectedTypeOfNodeInList)
End If
Return New SeparatedSyntaxList(Of TNode)(nodesAndTokens)
End Function
Private Shared Function NodesAreCorrectType(Of TNode)(list As SyntaxNodeOrTokenList) As Boolean
Dim n = list.Count
For i = 0 To n - 1
Dim element = list(i)
If element.IsNode AndAlso Not (TypeOf element.AsNode() Is TNode) Then
Return False
End If
Next
Return True
End Function
Private Shared Function HasSeparatedNodeTokenPattern(list As SyntaxNodeOrTokenList) As Boolean
For i = 0 To list.Count - 1
Dim element = list(i)
If element.IsToken = ((i And 1) = 0) Then
Return False
End If
Next
Return True
End Function
''' <summary>
''' Creates an empty <see cref="SyntaxNodeOrTokenList"/>.
''' </summary>
Public Shared Function NodeOrTokenList() As SyntaxNodeOrTokenList
Return Nothing
End Function
''' <summary>
''' Creates a <see cref="SyntaxNodeOrTokenList"/> from a sequence of nodes and tokens.
''' </summary>
''' <param name="nodesAndTokens">A sequence of nodes and tokens.</param>
Public Shared Function NodeOrTokenList(nodesAndTokens As IEnumerable(Of SyntaxNodeOrToken)) As SyntaxNodeOrTokenList
Return New SyntaxNodeOrTokenList(nodesAndTokens)
End Function
''' <summary>
''' Creates a <see cref="SyntaxNodeOrTokenList"/> from one or more nodes and tokens.
''' </summary>
''' <param name="nodesAndTokens">An array of nodes and tokens.</param>
Public Shared Function NodeOrTokenList(ParamArray nodesAndTokens As SyntaxNodeOrToken()) As SyntaxNodeOrTokenList
Return New SyntaxNodeOrTokenList(nodesAndTokens)
End Function
#End Region
Public Shared Function InvocationExpression(expression As ExpressionSyntax) As InvocationExpressionSyntax
Return InvocationExpression(expression, Nothing)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Workspaces/CSharp/Portable/Classification/SyntaxClassification/NameSyntaxClassifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Classification.Classifiers
{
internal class NameSyntaxClassifier : AbstractNameSyntaxClassifier
{
public override void AddClassifications(
Workspace workspace,
SyntaxNode syntax,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
if (syntax is NameSyntax name)
{
ClassifyTypeSyntax(name, semanticModel, result, cancellationToken);
}
}
public override ImmutableArray<Type> SyntaxNodeTypes { get; } = ImmutableArray.Create(typeof(NameSyntax));
protected override int? GetRightmostNameArity(SyntaxNode node)
{
if (node is ExpressionSyntax expressionSyntax)
{
return expressionSyntax.GetRightmostName()?.Arity;
}
return null;
}
protected override bool IsParentAnAttribute(SyntaxNode node)
=> node.IsParentKind(SyntaxKind.Attribute);
private void ClassifyTypeSyntax(
NameSyntax name,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
var symbolInfo = semanticModel.GetSymbolInfo(name, cancellationToken);
var _ =
TryClassifySymbol(name, symbolInfo, semanticModel, result, cancellationToken) ||
TryClassifyFromIdentifier(name, symbolInfo, result) ||
TryClassifyValueIdentifier(name, symbolInfo, result) ||
TryClassifyNameOfIdentifier(name, symbolInfo, result);
}
private bool TryClassifySymbol(
NameSyntax name,
SymbolInfo symbolInfo,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
if (symbolInfo.CandidateReason == CandidateReason.Ambiguous ||
symbolInfo.CandidateReason == CandidateReason.MemberGroup)
{
return TryClassifyAmbiguousSymbol(name, symbolInfo, semanticModel, result, cancellationToken);
}
// Only classify if we get one good symbol back, or if it bound to a constructor symbol with
// overload resolution/accessibility errors, or bound to type/constructor and type wasn't creatable.
var symbol = TryGetSymbol(name, symbolInfo, semanticModel);
if (TryClassifySymbol(name, symbol, semanticModel, cancellationToken, out var classifiedSpan))
{
result.Add(classifiedSpan);
if (classifiedSpan.ClassificationType != ClassificationTypeNames.Keyword)
{
// Additionally classify static symbols
TryClassifyStaticSymbol(symbol, classifiedSpan.TextSpan, result);
}
return true;
}
return false;
}
private static bool TryClassifyAmbiguousSymbol(
NameSyntax name,
SymbolInfo symbolInfo,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
// If everything classifies the same way, then just pick that classification.
using var _ = PooledHashSet<ClassifiedSpan>.GetInstance(out var set);
var isStatic = false;
foreach (var symbol in symbolInfo.CandidateSymbols)
{
if (TryClassifySymbol(name, symbol, semanticModel, cancellationToken, out var classifiedSpan))
{
// If one symbol resolves to static, then just make it bold
isStatic = isStatic || IsStaticSymbol(symbol);
set.Add(classifiedSpan);
}
}
if (set.Count == 1)
{
// If any of the symbols are static, add the static classification and the regular symbol classification
if (isStatic)
{
result.Add(new ClassifiedSpan(set.First().TextSpan, ClassificationTypeNames.StaticSymbol));
}
result.Add(set.First());
return true;
}
return false;
}
private static bool TryClassifySymbol(
NameSyntax name,
[NotNullWhen(returnValue: true)] ISymbol? symbol,
SemanticModel semanticModel,
CancellationToken cancellationToken,
out ClassifiedSpan classifiedSpan)
{
// For Namespace parts, we want don't want to classify the QualifiedNameSyntax
// nodes, we instead wait for the each IdentifierNameSyntax node to avoid
// creating overlapping ClassifiedSpans.
if (symbol is INamespaceSymbol namespaceSymbol &&
name is IdentifierNameSyntax identifierNameSyntax)
{
// Do not classify the global:: namespace. It is already syntactically classified as a keyword.
var isGlobalNamespace = namespaceSymbol.IsGlobalNamespace &&
identifierNameSyntax.Identifier.IsKind(SyntaxKind.GlobalKeyword);
if (isGlobalNamespace)
{
classifiedSpan = default;
return false;
}
// Classifies both extern aliases and namespaces.
classifiedSpan = new ClassifiedSpan(name.Span, ClassificationTypeNames.NamespaceName);
return true;
}
if (name.IsVar &&
IsInVarContext(name))
{
var alias = semanticModel.GetAliasInfo(name, cancellationToken);
if (alias == null || alias.Name != "var")
{
if (!IsSymbolWithName(symbol, "var"))
{
// We bound to a symbol. If we bound to a symbol called "var" then we want to
// classify this appropriately as a type. Otherwise, we want to classify this as
// a keyword.
classifiedSpan = new ClassifiedSpan(name.Span, ClassificationTypeNames.Keyword);
return true;
}
}
}
if (name.IsNint || name.IsNuint)
{
if (symbol is ITypeSymbol type && type.IsNativeIntegerType)
{
classifiedSpan = new ClassifiedSpan(name.Span, ClassificationTypeNames.Keyword);
return true;
}
}
if ((name.IsUnmanaged || name.IsNotNull) && name.Parent.IsKind(SyntaxKind.TypeConstraint))
{
var nameToCheck = name.IsUnmanaged ? "unmanaged" : "notnull";
var alias = semanticModel.GetAliasInfo(name, cancellationToken);
if (alias == null || alias.Name != nameToCheck)
{
if (!IsSymbolWithName(symbol, nameToCheck))
{
// We bound to a symbol. If we bound to a symbol called "unmanaged"/"notnull" then we want to
// classify this appropriately as a type. Otherwise, we want to classify this as
// a keyword.
classifiedSpan = new ClassifiedSpan(name.Span, ClassificationTypeNames.Keyword);
return true;
}
}
}
// Use .Equals since we can't rely on object identity for constructed types.
SyntaxToken token;
switch (symbol)
{
case ITypeSymbol typeSymbol:
var classification = GetClassificationForType(typeSymbol);
if (classification != null)
{
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, classification);
return true;
}
break;
case IFieldSymbol fieldSymbol:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, GetClassificationForField(fieldSymbol));
return true;
case IMethodSymbol methodSymbol:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, GetClassificationForMethod(methodSymbol));
return true;
case IPropertySymbol _:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, ClassificationTypeNames.PropertyName);
return true;
case IEventSymbol _:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, ClassificationTypeNames.EventName);
return true;
case IParameterSymbol parameterSymbol:
if (parameterSymbol.IsImplicitlyDeclared && parameterSymbol.Name == "value")
{
break;
}
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, ClassificationTypeNames.ParameterName);
return true;
case ILocalSymbol localSymbol:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, GetClassificationForLocal(localSymbol));
return true;
case ILabelSymbol _:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, ClassificationTypeNames.LabelName);
return true;
}
classifiedSpan = default;
return false;
}
private static string GetClassificationForField(IFieldSymbol fieldSymbol)
{
if (fieldSymbol.IsConst)
{
return fieldSymbol.ContainingType.IsEnumType() ? ClassificationTypeNames.EnumMemberName : ClassificationTypeNames.ConstantName;
}
return ClassificationTypeNames.FieldName;
}
private static string GetClassificationForLocal(ILocalSymbol localSymbol)
{
return localSymbol.IsConst
? ClassificationTypeNames.ConstantName
: ClassificationTypeNames.LocalName;
}
private static string GetClassificationForMethod(IMethodSymbol methodSymbol)
{
// Classify constructors by their containing type. We do not need to worry about
// destructors because their declaration is handled by syntactic classification
// and they cannot be invoked, so their is no usage to semantically classify.
if (methodSymbol.MethodKind == MethodKind.Constructor)
{
return methodSymbol.ContainingType?.GetClassification() ?? ClassificationTypeNames.MethodName;
}
// Note: We only classify an extension method if it is in reduced form.
// If an extension method is called as a static method invocation (e.g. Enumerable.Select(...)),
// it is classified as an ordinary method.
return methodSymbol.MethodKind == MethodKind.ReducedExtension
? ClassificationTypeNames.ExtensionMethodName
: ClassificationTypeNames.MethodName;
}
private static bool IsInVarContext(NameSyntax name)
{
return
name.CheckParent<RefTypeSyntax>(v => v.Type == name) ||
name.CheckParent<ForEachStatementSyntax>(f => f.Type == name) ||
name.CheckParent<DeclarationPatternSyntax>(v => v.Type == name) ||
name.CheckParent<VariableDeclarationSyntax>(v => v.Type == name) ||
name.CheckParent<DeclarationExpressionSyntax>(f => f.Type == name);
}
private static bool TryClassifyFromIdentifier(
NameSyntax name,
SymbolInfo symbolInfo,
ArrayBuilder<ClassifiedSpan> result)
{
// Okay - it wasn't a type. If the syntax matches "var q = from" or "q = from", and from
// doesn't bind to anything then optimistically color from as a keyword.
if (name is IdentifierNameSyntax identifierName &&
identifierName.Identifier.HasMatchingText(SyntaxKind.FromKeyword) &&
symbolInfo.Symbol == null)
{
var token = identifierName.Identifier;
if (identifierName.IsRightSideOfAnyAssignExpression() || identifierName.IsVariableDeclaratorValue())
{
result.Add(new ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword));
return true;
}
}
return false;
}
private static bool TryClassifyValueIdentifier(
NameSyntax name,
SymbolInfo symbolInfo,
ArrayBuilder<ClassifiedSpan> result)
{
var identifierName = name as IdentifierNameSyntax;
if (symbolInfo.Symbol.IsImplicitValueParameter())
{
#nullable disable // Can 'identifierName' be null here?
result.Add(new ClassifiedSpan(identifierName.Identifier.Span, ClassificationTypeNames.Keyword));
#nullable enable
return true;
}
return false;
}
private static bool TryClassifyNameOfIdentifier(
NameSyntax name, SymbolInfo symbolInfo, ArrayBuilder<ClassifiedSpan> result)
{
if (name is IdentifierNameSyntax identifierName &&
identifierName.Identifier.IsKindOrHasMatchingText(SyntaxKind.NameOfKeyword) &&
symbolInfo.Symbol == null &&
!symbolInfo.CandidateSymbols.Any())
{
result.Add(new ClassifiedSpan(identifierName.Identifier.Span, ClassificationTypeNames.Keyword));
return true;
}
return false;
}
private static bool IsSymbolWithName([NotNullWhen(returnValue: true)] ISymbol? symbol, string name)
{
if (symbol is null || symbol.Name != name)
{
return false;
}
if (symbol is INamedTypeSymbol namedType)
{
return namedType.Arity == 0;
}
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Classification.Classifiers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Classification.Classifiers
{
internal class NameSyntaxClassifier : AbstractNameSyntaxClassifier
{
public override void AddClassifications(
Workspace workspace,
SyntaxNode syntax,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
if (syntax is NameSyntax name)
{
ClassifyTypeSyntax(name, semanticModel, result, cancellationToken);
}
}
public override ImmutableArray<Type> SyntaxNodeTypes { get; } = ImmutableArray.Create(typeof(NameSyntax));
protected override int? GetRightmostNameArity(SyntaxNode node)
{
if (node is ExpressionSyntax expressionSyntax)
{
return expressionSyntax.GetRightmostName()?.Arity;
}
return null;
}
protected override bool IsParentAnAttribute(SyntaxNode node)
=> node.IsParentKind(SyntaxKind.Attribute);
private void ClassifyTypeSyntax(
NameSyntax name,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
var symbolInfo = semanticModel.GetSymbolInfo(name, cancellationToken);
var _ =
TryClassifySymbol(name, symbolInfo, semanticModel, result, cancellationToken) ||
TryClassifyFromIdentifier(name, symbolInfo, result) ||
TryClassifyValueIdentifier(name, symbolInfo, result) ||
TryClassifyNameOfIdentifier(name, symbolInfo, result);
}
private bool TryClassifySymbol(
NameSyntax name,
SymbolInfo symbolInfo,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
if (symbolInfo.CandidateReason == CandidateReason.Ambiguous ||
symbolInfo.CandidateReason == CandidateReason.MemberGroup)
{
return TryClassifyAmbiguousSymbol(name, symbolInfo, semanticModel, result, cancellationToken);
}
// Only classify if we get one good symbol back, or if it bound to a constructor symbol with
// overload resolution/accessibility errors, or bound to type/constructor and type wasn't creatable.
var symbol = TryGetSymbol(name, symbolInfo, semanticModel);
if (TryClassifySymbol(name, symbol, semanticModel, cancellationToken, out var classifiedSpan))
{
result.Add(classifiedSpan);
if (classifiedSpan.ClassificationType != ClassificationTypeNames.Keyword)
{
// Additionally classify static symbols
TryClassifyStaticSymbol(symbol, classifiedSpan.TextSpan, result);
}
return true;
}
return false;
}
private static bool TryClassifyAmbiguousSymbol(
NameSyntax name,
SymbolInfo symbolInfo,
SemanticModel semanticModel,
ArrayBuilder<ClassifiedSpan> result,
CancellationToken cancellationToken)
{
// If everything classifies the same way, then just pick that classification.
using var _ = PooledHashSet<ClassifiedSpan>.GetInstance(out var set);
var isStatic = false;
foreach (var symbol in symbolInfo.CandidateSymbols)
{
if (TryClassifySymbol(name, symbol, semanticModel, cancellationToken, out var classifiedSpan))
{
// If one symbol resolves to static, then just make it bold
isStatic = isStatic || IsStaticSymbol(symbol);
set.Add(classifiedSpan);
}
}
if (set.Count == 1)
{
// If any of the symbols are static, add the static classification and the regular symbol classification
if (isStatic)
{
result.Add(new ClassifiedSpan(set.First().TextSpan, ClassificationTypeNames.StaticSymbol));
}
result.Add(set.First());
return true;
}
return false;
}
private static bool TryClassifySymbol(
NameSyntax name,
[NotNullWhen(returnValue: true)] ISymbol? symbol,
SemanticModel semanticModel,
CancellationToken cancellationToken,
out ClassifiedSpan classifiedSpan)
{
// For Namespace parts, we want don't want to classify the QualifiedNameSyntax
// nodes, we instead wait for the each IdentifierNameSyntax node to avoid
// creating overlapping ClassifiedSpans.
if (symbol is INamespaceSymbol namespaceSymbol &&
name is IdentifierNameSyntax identifierNameSyntax)
{
// Do not classify the global:: namespace. It is already syntactically classified as a keyword.
var isGlobalNamespace = namespaceSymbol.IsGlobalNamespace &&
identifierNameSyntax.Identifier.IsKind(SyntaxKind.GlobalKeyword);
if (isGlobalNamespace)
{
classifiedSpan = default;
return false;
}
// Classifies both extern aliases and namespaces.
classifiedSpan = new ClassifiedSpan(name.Span, ClassificationTypeNames.NamespaceName);
return true;
}
if (name.IsVar &&
IsInVarContext(name))
{
var alias = semanticModel.GetAliasInfo(name, cancellationToken);
if (alias == null || alias.Name != "var")
{
if (!IsSymbolWithName(symbol, "var"))
{
// We bound to a symbol. If we bound to a symbol called "var" then we want to
// classify this appropriately as a type. Otherwise, we want to classify this as
// a keyword.
classifiedSpan = new ClassifiedSpan(name.Span, ClassificationTypeNames.Keyword);
return true;
}
}
}
if (name.IsNint || name.IsNuint)
{
if (symbol is ITypeSymbol type && type.IsNativeIntegerType)
{
classifiedSpan = new ClassifiedSpan(name.Span, ClassificationTypeNames.Keyword);
return true;
}
}
if ((name.IsUnmanaged || name.IsNotNull) && name.Parent.IsKind(SyntaxKind.TypeConstraint))
{
var nameToCheck = name.IsUnmanaged ? "unmanaged" : "notnull";
var alias = semanticModel.GetAliasInfo(name, cancellationToken);
if (alias == null || alias.Name != nameToCheck)
{
if (!IsSymbolWithName(symbol, nameToCheck))
{
// We bound to a symbol. If we bound to a symbol called "unmanaged"/"notnull" then we want to
// classify this appropriately as a type. Otherwise, we want to classify this as
// a keyword.
classifiedSpan = new ClassifiedSpan(name.Span, ClassificationTypeNames.Keyword);
return true;
}
}
}
// Use .Equals since we can't rely on object identity for constructed types.
SyntaxToken token;
switch (symbol)
{
case ITypeSymbol typeSymbol:
var classification = GetClassificationForType(typeSymbol);
if (classification != null)
{
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, classification);
return true;
}
break;
case IFieldSymbol fieldSymbol:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, GetClassificationForField(fieldSymbol));
return true;
case IMethodSymbol methodSymbol:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, GetClassificationForMethod(methodSymbol));
return true;
case IPropertySymbol _:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, ClassificationTypeNames.PropertyName);
return true;
case IEventSymbol _:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, ClassificationTypeNames.EventName);
return true;
case IParameterSymbol parameterSymbol:
if (parameterSymbol.IsImplicitlyDeclared && parameterSymbol.Name == "value")
{
break;
}
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, ClassificationTypeNames.ParameterName);
return true;
case ILocalSymbol localSymbol:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, GetClassificationForLocal(localSymbol));
return true;
case ILabelSymbol _:
token = name.GetNameToken();
classifiedSpan = new ClassifiedSpan(token.Span, ClassificationTypeNames.LabelName);
return true;
}
classifiedSpan = default;
return false;
}
private static string GetClassificationForField(IFieldSymbol fieldSymbol)
{
if (fieldSymbol.IsConst)
{
return fieldSymbol.ContainingType.IsEnumType() ? ClassificationTypeNames.EnumMemberName : ClassificationTypeNames.ConstantName;
}
return ClassificationTypeNames.FieldName;
}
private static string GetClassificationForLocal(ILocalSymbol localSymbol)
{
return localSymbol.IsConst
? ClassificationTypeNames.ConstantName
: ClassificationTypeNames.LocalName;
}
private static string GetClassificationForMethod(IMethodSymbol methodSymbol)
{
// Classify constructors by their containing type. We do not need to worry about
// destructors because their declaration is handled by syntactic classification
// and they cannot be invoked, so their is no usage to semantically classify.
if (methodSymbol.MethodKind == MethodKind.Constructor)
{
return methodSymbol.ContainingType?.GetClassification() ?? ClassificationTypeNames.MethodName;
}
// Note: We only classify an extension method if it is in reduced form.
// If an extension method is called as a static method invocation (e.g. Enumerable.Select(...)),
// it is classified as an ordinary method.
return methodSymbol.MethodKind == MethodKind.ReducedExtension
? ClassificationTypeNames.ExtensionMethodName
: ClassificationTypeNames.MethodName;
}
private static bool IsInVarContext(NameSyntax name)
{
return
name.CheckParent<RefTypeSyntax>(v => v.Type == name) ||
name.CheckParent<ForEachStatementSyntax>(f => f.Type == name) ||
name.CheckParent<DeclarationPatternSyntax>(v => v.Type == name) ||
name.CheckParent<VariableDeclarationSyntax>(v => v.Type == name) ||
name.CheckParent<DeclarationExpressionSyntax>(f => f.Type == name);
}
private static bool TryClassifyFromIdentifier(
NameSyntax name,
SymbolInfo symbolInfo,
ArrayBuilder<ClassifiedSpan> result)
{
// Okay - it wasn't a type. If the syntax matches "var q = from" or "q = from", and from
// doesn't bind to anything then optimistically color from as a keyword.
if (name is IdentifierNameSyntax identifierName &&
identifierName.Identifier.HasMatchingText(SyntaxKind.FromKeyword) &&
symbolInfo.Symbol == null)
{
var token = identifierName.Identifier;
if (identifierName.IsRightSideOfAnyAssignExpression() || identifierName.IsVariableDeclaratorValue())
{
result.Add(new ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword));
return true;
}
}
return false;
}
private static bool TryClassifyValueIdentifier(
NameSyntax name,
SymbolInfo symbolInfo,
ArrayBuilder<ClassifiedSpan> result)
{
var identifierName = name as IdentifierNameSyntax;
if (symbolInfo.Symbol.IsImplicitValueParameter())
{
#nullable disable // Can 'identifierName' be null here?
result.Add(new ClassifiedSpan(identifierName.Identifier.Span, ClassificationTypeNames.Keyword));
#nullable enable
return true;
}
return false;
}
private static bool TryClassifyNameOfIdentifier(
NameSyntax name, SymbolInfo symbolInfo, ArrayBuilder<ClassifiedSpan> result)
{
if (name is IdentifierNameSyntax identifierName &&
identifierName.Identifier.IsKindOrHasMatchingText(SyntaxKind.NameOfKeyword) &&
symbolInfo.Symbol == null &&
!symbolInfo.CandidateSymbols.Any())
{
result.Add(new ClassifiedSpan(identifierName.Identifier.Span, ClassificationTypeNames.Keyword));
return true;
}
return false;
}
private static bool IsSymbolWithName([NotNullWhen(returnValue: true)] ISymbol? symbol, string name)
{
if (symbol is null || symbol.Name != name)
{
return false;
}
if (symbol is INamedTypeSymbol namedType)
{
return namedType.Arity == 0;
}
return true;
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./eng/SourceBuildPrebuiltBaseline.xml | <UsageData>
<IgnorePatterns>
<UsagePattern IdentityGlob="*/*" />
</IgnorePatterns>
</UsageData>
| <UsageData>
<IgnorePatterns>
<UsagePattern IdentityGlob="*/*" />
</IgnorePatterns>
</UsageData>
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenImplicitlyTypeArraysTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.IO;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenImplicitlyTypeArraysTests : CompilingTestBase
{
#region "Functionality tests"
[Fact]
public void Test_001_Simple()
{
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {1, 2, 3};
System.Console.Write(a.SequenceEqual(new int[]{1, 2, 3}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_002_IntTypeBest()
{
// Best type: int
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {1, (byte)2, (short)3};
System.Console.Write(a.SequenceEqual(new int[]{1, (byte)2, (short)3}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_003_DoubleTypeBest()
{
// Best type: double
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {(sbyte)1, (byte)2, (short)3, (ushort)4, 5, 6u, 7l, 8ul, (char)9, 10.0f, 11.0d};
System.Console.Write(a.SequenceEqual(new double[]{(sbyte)1, (byte)2, (short)3, (ushort)4, 5, 6u, 7l, 8ul, (char)9, 10.0f, 11.0d}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact, WorkItem(895655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895655")]
public void Test_004_Enum()
{
// Enums conversions
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
enum E
{
START
};
public static void Main()
{
var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
}
}
}
";
var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40Extended);
comp.VerifyDiagnostics(
// (15,54): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 54),
// (15,88): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 88),
// (15,93): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 93),
// (17,84): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 84),
// (17,118): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 118),
// (17,123): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 123),
// (15,21): error CS0826: No best type found for implicitly-typed array
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}").WithLocation(15, 21),
// (17,35): error CS1929: '?[]' does not contain a definition for 'SequenceEqual' and the best extension method overload 'System.Linq.Queryable.SequenceEqual<Test.Program.E>(System.Linq.IQueryable<Test.Program.E>, System.Collections.Generic.IEnumerable<Test.Program.E>)' requires a receiver of type 'System.Linq.IQueryable<Test.Program.E>'
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("?[]", "SequenceEqual", "System.Linq.Queryable.SequenceEqual<Test.Program.E>(System.Linq.IQueryable<Test.Program.E>, System.Collections.Generic.IEnumerable<Test.Program.E>)", "System.Linq.IQueryable<Test.Program.E>").WithLocation(17, 35)
);
}
[Fact]
public void Test_005_ObjectTypeBest()
{
// Implicit reference conversions -- From any reference-type to object.
var source = @"
using System.Linq;
namespace Test
{
public class C { };
public interface I { };
public class C2 : I { };
public class Program
{
delegate void D();
public static void M() { }
public static void Main()
{
object o = new object();
C c = new C();
I i = new C2();
D d = new D(M);
int[] aa = new int[] {1};
var a = new [] {o, """", c, i, d, aa};
System.Console.Write(a.SequenceEqual(new object[]{o, """", c, i, d, aa}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_006_ArrayTypeBest()
{
// Implicit reference conversions -- From an array-type S with an element type SE to an array-type T with an element type TE,
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
object[] oa = new object[] {null};
string[] sa = new string[] {null};
var a = new [] {oa, sa};
System.Console.Write(a.SequenceEqual(new object[][]{oa, sa}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_007A()
{
// Implicit reference conversions -- From a one-dimensional array-type S[] to System.Collections.Generic.IList<S>.
var testSrc = @"
using System.Linq;
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static void Main()
{
int[] ia = new int[] {1, 2, 3};
IList<int> la = new List<int> {1, 2, 3};
var a = new [] {ia, la};
System.Console.Write(a.SequenceEqual(new IList<int>[]{ia, la}));
}
}
}
";
var compilation = CompileAndVerify(
testSrc,
expectedOutput: "True");
}
[Fact]
public void Test_007B()
{
// Implicit reference conversions -- From a one-dimensional array-type S[] to System.Collections.Generic.IReadOnlyList<S>.
var testSrc = @"
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static void Main()
{
int[] array = new int[] {1, 2, 3};
object obj = array;
IEnumerable<int> ro1 = array;
IReadOnlyList<int> ro2 = (IReadOnlyList<int>)obj;
IReadOnlyList<int> ro3 = (IReadOnlyList<int>)array;
IReadOnlyList<int> ro4 = obj as IReadOnlyList<int>;
System.Console.WriteLine(ro4 != null ? 1 : 2);
}
}
}
";
var mscorlib17626 = MetadataReference.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib);
CompileAndVerify(testSrc, new MetadataReference[] { mscorlib17626 }, expectedOutput: "1", targetFramework: TargetFramework.Empty);
}
[Fact]
public void Test_008_DelegateType()
{
// Implicit reference conversions -- From any delegate-type to System.Delegate.
var source = @"
using System;
using System.Linq;
namespace Test
{
public class Program
{
delegate void D1();
public static void M1() {}
delegate int D2();
public static int M2() { return 0;}
delegate void D3(int i);
public static void M3(int i) {}
delegate void D4(params object[] o);
public static void M4(params object[] o) { }
public static void Main()
{
D1 d1 = new D1(M1);
D2 d2 = new D2(M2);
D3 d3 = new D3(M3);
D4 d4 = new D4(M4);
Delegate d = d1;
var a = new [] {d, d1, d2, d3, d4};
System.Console.Write(a.SequenceEqual(new Delegate[]{d, d1, d2, d3, d4}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_009_Null()
{
// Implicit reference conversions -- From the null type to any reference-type.
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {""aa"", ""bb"", null};
System.Console.Write(a.SequenceEqual(new string[]{""aa"", ""bb"", null}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_010_TypeParameter()
{
// Implicit reference conversions --
// For a type-parameter T that is known to be a reference type , the following
// implicit reference conversions exist:
// From T to its effective base class C, from T to any base class of C,
// and from T to any interface implemented by C.
var source = @"
using System.Linq;
namespace Test
{
public interface I {}
public class B {}
public class C : B, I {}
public class D : C {}
public class Program
{
public static void M<T>() where T : C, new()
{
T t = new T();
I i = t;
var a = new [] {i, t};
System.Console.Write(a.SequenceEqual(new I[]{i, t}));
}
public static void Main()
{
M<D>();
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_011_BoxingConversion()
{
// Implicit reference conversions -- Boxing conversions
var testSrc = @"
using System;
using System.Linq;
namespace Test
{
public struct S
{
}
public class Program
{
enum E { START };
public static void Main()
{
IComparable v = 1;
int? i = 1;
var a = new [] {v, i, E.START, true, (byte)2, (sbyte)3, (short)4, (ushort)5, 6, 7U, 8L, 9UL, 10.0F, 11.0D, 12M, (char)13};
System.Console.Write(a.SequenceEqual(new IComparable[]{v, i, E.START, true, (byte)2, (sbyte)3, (short)4, (ushort)5, 6, 7U, 8L, 9UL, 10.0F, 11.0D, 12M, (char)13}));
}
}
}
";
var compilation = CompileAndVerify(
testSrc,
expectedOutput: "True");
}
[Fact]
public void Test_012_UserDefinedImplicitConversion()
{
// User-defined implicit conversions.
var testSrc = @"
using System.Linq;
namespace Test
{
public class B {}
public class C
{
public static B b = new B();
public static implicit operator B(C c)
{
return b;
}
}
public class Program
{
public static void Main()
{
B b = new B();
C c = new C();
var a = new [] {b, c};
System.Console.Write(a.SequenceEqual(new B[]{b, c}));
}
}
}
";
// NYI: When user-defined conversion lowering is implemented, replace the
// NYI: error checking below with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
[Fact]
public void Test_013_A_UserDefinedNullableConversions()
{
// Lifted user-defined conversions
var testSrc = @"
using System.Linq;
namespace Test
{
public struct B { }
public struct C
{
public static B b = new B();
public static implicit operator B(C c)
{
return b;
}
}
public class Program
{
public static void Main()
{
C? c = new C();
B? b = new B();
if (!(new [] {b, c}.SequenceEqual(new B?[] {b, c})))
{
System.Console.WriteLine(""Test fail at struct C? implicitly convert to struct B?"");
}
}
}
}
";
// NYI: When lifted user-defined conversion lowering is implemented, replace the
// NYI: error checking below with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
// Bug 10700: We should be able to infer the array type from elements of types int? and short?
[Fact]
public void Test_013_B_NullableConversions()
{
// Lifted implicit numeric conversions
var testSrc = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
int? i = 1;
short? s = 2;
if (!new [] {i, s}.SequenceEqual(new int?[] {i, s}))
{
System.Console.WriteLine(""Test fail at short? implicitly convert to int?"");
}
}
}
}
";
// NYI: When lifted conversions are implemented, remove the diagnostics check
// NYI: and replace it with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
[Fact]
public void Test_014_LambdaExpression()
{
// Implicitly conversion from lambda expression to compatible delegate type
var source = @"
using System;
namespace Test
{
public class Program
{
delegate int D(int i);
public static int M(int i) {return i;}
public static void Main()
{
var a = new [] {new D(M), (int i)=>{return i;}, x => x+1, (int i)=>{short s = 2; return s;}};
Console.Write(((a is D[]) && (a.Length==4)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_015_ImplicitlyTypedLocalExpr()
{
// local variable declared as "var" type is used inside an implicitly typed array.
var source = @"
using System.Linq;
namespace Test
{
public class B { };
public class C : B { };
public class Program
{
public static void Main()
{
var b = new B();
var c = new C();
var a = new [] {b, c};
System.Console.Write(a.SequenceEqual(new B[]{b, c}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_016_ArrayCreationExpression()
{
// Array creation expression as element in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {new int[1] , new int[3] {11, 12, 13}, new int[] {21, 22, 23}};
Console.Write(((a is int[][]) && (a.Length==3)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_017_AnonymousObjectCreationExpression()
{
// Anonymous object creation expression as element in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {new {i = 2, s = ""bb""}, new {i = 3, s = ""cc""}};
Console.Write(((a is Array) && (a.Length==2)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_018_MemberAccessExpression()
{
// Member access expression as element in implicitly typed arrays
var source = @"
using System.Linq;
using NT = Test;
namespace Test
{
public class Program
{
public delegate int D(string s);
public static D d1 = new D(M2);
public static int M<T>(string s) {return 1;}
public static int M2(string s) {return 2;}
public D d2 = new D(M2);
public static Program p = new Program();
public static Program GetP() {return p;}
public static void Main()
{
System.Console.Write(new [] {Program.d1, Program.M<int>, GetP().d2, int.Parse, NT::Program.M2}.SequenceEqual(
new D[] {Program.d1, Program.M<int>, GetP().d2, int.Parse, NT::Program.M2}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_019_JaggedArray()
{
// JaggedArray in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [] { new [] {new [] {1}},
new [] {new int[] {2}},
new int[][] {new int[] {3}},
new int[][] {new [] {4}} };
if ( !((a3 is int[][][]) && (a3.Length == 4)) )
{
Console.Write(""Test fail"");
}
else
{
Console.Write(""True"");
}
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_020_MultiDimensionalArray()
{
// MultiDimensionalArray in implicitly typed arrays
var testSrc = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [] { new int[,,] {{{3, 4}}},
new int[,,] {{{3, 4}}} };
if ( !((a3 is int[][,,]) && (a3.Rank == 1) && (a3.Length == 2)) )
{
Console.WriteLine(0);
}
else
{
Console.WriteLine(1);
}
}
}
}";
CompileAndVerify(testSrc, expectedOutput: "1");
}
[Fact]
public void Test_021_MultiDimensionalArray_02()
{
// Implicitly typed arrays should can be used in creating MultiDimensionalArray
var testSrc = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [,,] { {{2, 3, 4}}, {{2, 3, 4}} };
if ( !((a3 is int[,,]) && (a3.Rank == 3) && (a3.Length == 6)) )
{
Console.WriteLine(0);
}
else
{
Console.WriteLine(1);
}
}
}
}
";
CompileAndVerify(testSrc, expectedOutput: "1");
}
[Fact]
public void Test_022_GenericMethod()
{
// Implicitly typed arrays used in generic method
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
System.Console.Write(GM(new [] {1, 2, 3}).SequenceEqual(new int[]{1, 2, 3}));
}
public static T GM<T>(T t)
{
return t;
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_023_Query()
{
// Query expression as element in implicitly typed arrays
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
int[] ta = new int[] {1, 2, 3, 4, 5};
IEnumerable i = ta;
IEnumerable[] a = new [] {i, from c in ta select c, from c in ta group c by c,
from c in ta select c into g select g, from c in ta where c==3 select c,
from c in ta orderby c select c, from c in ta orderby c ascending select c,
from c in ta orderby c descending select c, from c in ta where c==3 orderby c select c};
Console.Write((a is IEnumerable[]) && (a.Length==9));
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_023_Literal()
{
// Query expression as element in implicitly typed arrays
var source = @"
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.Write(new [] {true, false}.SequenceEqual(new bool[] {true, false}));
Console.Write(new [] {0123456789U, 1234567890U, 2345678901u, 3456789012UL, 4567890123Ul, 5678901234UL, 6789012345Ul, 7890123456uL, 8901234567ul, 9012345678LU, 9123456780Lu, 1234567809LU, 2345678091LU}.SequenceEqual(
new ulong[] {0123456789U, 1234567890U, 2345678901u, 3456789012UL, 4567890123Ul, 5678901234UL, 6789012345Ul, 7890123456uL, 8901234567ul, 9012345678LU, 9123456780Lu, 1234567809LU, 2345678091LU}));
Console.Write(new [] {0123456789, 1234567890, 2345678901, 3456789012L, 4567890123L, 5678901234L, 6789012345L, 7890123456L, 8901234567L, 9012345678L, 9123456780L, 1234567809L, 2345678091L}.SequenceEqual(
new long[] {0123456789, 1234567890, 2345678901, 3456789012L, 4567890123L, 5678901234L, 6789012345L, 7890123456L, 8901234567L, 9012345678L, 9123456780L, 1234567809L, 2345678091L}));
Console.Write(new [] {0x012345U, 0x6789ABU, 0xCDEFabU, 0xcdef01U, 0X123456U, 0x12579BU, 0x13579Bu, 0x14579BLU, 0x15579BLU, 0x16579BUL, 0x17579BUl, 0x18579BuL, 0x19579Bul, 0x1A579BLU, 0x1B579BLu, 0x1C579BLU, 0x1C579BLu}.SequenceEqual(
new ulong[] {0x012345U, 0x6789ABU, 0xCDEFabU, 0xcdef01U, 0X123456U, 0x12579BU, 0x13579Bu, 0x14579BLU, 0x15579BLU, 0x16579BUL, 0x17579BUl, 0x18579BuL, 0x19579Bul, 0x1A579BLU, 0x1B579BLu, 0x1C579BLU, 0x1C579BLu}));
Console.Write(new [] {0x012345, 0x6789AB, 0xCDEFab, 0xcdef01, 0X123456, 0x12579B, 0x13579B, 0x14579BL, 0x15579BL, 0x16579BL, 0x17579BL, 0x18579BL, 0x19579BL, 0x1A579BL, 0x1B579BL, 0x1C579BL, 0x1C579BL}.SequenceEqual(
new long[] {0x012345, 0x6789AB, 0xCDEFab, 0xcdef01, 0X123456, 0x12579B, 0x13579B, 0x14579BL, 0x15579BL, 0x16579BL, 0x17579BL, 0x18579BL, 0x19579BL, 0x1A579BL, 0x1B579BL, 0x1C579BL, 0x1C579BL}));
Console.Write(new [] {0123456789F, 1234567890f, 2345678901D, 3456789012d, 3.2, 3.3F, 3.4e5, 3.5E5, 3.6E+5, 3.7E-5, 3.8e+5, 3.9e-5, 3.22E5D, .234, .23456D, .245e3, .2334e7D, 3E5, 3E-5, 3E+6, 4E4D}.SequenceEqual(
new double[] {0123456789F, 1234567890f, 2345678901D, 3456789012d, 3.2, 3.3F, 3.4e5, 3.5E5, 3.6E+5, 3.7E-5, 3.8e+5, 3.9e-5, 3.22E5D, .234, .23456D, .245e3, .2334e7D, 3E5, 3E-5, 3E+6, 4E4D})) ;
Console.Write(new [] {0123456789M, 1234567890m, 3.3M, 3.22E5M, 3.2E+4M, 3.3E-4M, .234M, .245e3M, .2334e+7M, .24e-3M, 3E5M, 3E-5M, 3E+6M}.SequenceEqual(
new decimal[] {0123456789M, 1234567890m, 3.3M, 3.22E5M, 3.2E+4M, 3.3E-4M, .234M, .245e3M, .2334e+7M, .24e-3M, 3E5M, 3E-5M, 3E+6M}));
Console.Write(new [] {0123456789, 5678901234UL, 2345678901D, 3.2, 3.4E5, 3.6E+5, 3.7E-5, 3.22E5D, .234, .23456D, .245E3, 3E5, 4E4D}.SequenceEqual(
new double[] {0123456789, 5678901234UL, 2345678901D, 3.2, 3.4E5, 3.6E+5, 3.7E-5, 3.22E5D, .234, .23456D, .245E3, 3E5, 4E4D}));
Console.Write(new [] {0123456789, 5678901234UL, 2345678901M, 3.2M, 3.4E5M, 3.6E+5M, 3.7E-5M, .234M, .245E3M, 3E5M}.SequenceEqual(
new decimal[] {0123456789, 5678901234UL, 2345678901M, 3.2M, 3.4E5M, 3.6E+5M, 3.7E-5M, .234M, .245E3M, 3E5M}));
}
}
";
CompileAndVerify(
source,
expectedOutput: "TrueTrueTrueTrueTrueTrueTrueTrueTrue");
}
#endregion
#region "Error tests"
[Fact]
public void Error_NonArrayInitExpr()
{
var testSrc = @"
namespace Test
{
public class Program
{
public void Goo()
{
var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
}
}
}
";
var comp = CreateCompilation(testSrc);
comp.VerifyDiagnostics(
// (8,46): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "3").WithLocation(8, 46),
// (8,49): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "4").WithLocation(8, 49));
}
[Fact]
public void Error_NonArrayInitExpr_02()
{
var testSrc = @"
namespace Test
{
public class Program
{
public void Goo()
{
var a3 = new[,,] { { { 3, 4 } }, x, 4 };
}
}
}
";
var comp = CreateCompilation(testSrc);
comp.VerifyDiagnostics(
// (8,46): error CS0103: The name 'x' does not exist in the current context
// var a3 = new[,,] { { { 3, 4 } }, x, 4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(8, 46),
// (8,49): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, x, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "4").WithLocation(8, 49));
}
[WorkItem(543571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543571")]
[Fact]
public void CS0826ERR_ImplicitlyTypedArrayNoBestType()
{
var text = @"
using System;
namespace Test
{
public class Program
{
enum E
{
Zero,
FortyTwo = 42
};
public static void Main()
{
E[] a = new[] { E.FortyTwo, 0 }; // Dev10 error CS0826
Console.WriteLine(String.Format(""Type={0}, a[0]={1}, a[1]={2}"", a.GetType(), a[0], a[1]));
}
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (16,21): error CS0826: No best type found for implicitly-typed array
// E[] a = new[] { E.FortyTwo, 0 }; // Dev10 error CS0826
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { E.FortyTwo, 0 }").WithLocation(16, 21));
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.IO;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public class CodeGenImplicitlyTypeArraysTests : CompilingTestBase
{
#region "Functionality tests"
[Fact]
public void Test_001_Simple()
{
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {1, 2, 3};
System.Console.Write(a.SequenceEqual(new int[]{1, 2, 3}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_002_IntTypeBest()
{
// Best type: int
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {1, (byte)2, (short)3};
System.Console.Write(a.SequenceEqual(new int[]{1, (byte)2, (short)3}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_003_DoubleTypeBest()
{
// Best type: double
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {(sbyte)1, (byte)2, (short)3, (ushort)4, 5, 6u, 7l, 8ul, (char)9, 10.0f, 11.0d};
System.Console.Write(a.SequenceEqual(new double[]{(sbyte)1, (byte)2, (short)3, (ushort)4, 5, 6u, 7l, 8ul, (char)9, 10.0f, 11.0d}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact, WorkItem(895655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895655")]
public void Test_004_Enum()
{
// Enums conversions
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
enum E
{
START
};
public static void Main()
{
var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
}
}
}
";
var comp = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib40Extended);
comp.VerifyDiagnostics(
// (15,54): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 54),
// (15,88): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 88),
// (15,93): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(15, 93),
// (17,84): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 84),
// (17,118): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 118),
// (17,123): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(17, 123),
// (15,21): error CS0826: No best type found for implicitly-typed array
// var a = new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu};
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new [] {E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}").WithLocation(15, 21),
// (17,35): error CS1929: '?[]' does not contain a definition for 'SequenceEqual' and the best extension method overload 'System.Linq.Queryable.SequenceEqual<Test.Program.E>(System.Linq.IQueryable<Test.Program.E>, System.Collections.Generic.IEnumerable<Test.Program.E>)' requires a receiver of type 'System.Linq.IQueryable<Test.Program.E>'
// System.Console.Write(a.SequenceEqual(new E[]{E.START, 0, 0U, 0u, 0L, 0l, 0UL, 0Ul, 0uL, 0ul, 0LU, 0Lu, 0lU, 0lu}));
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("?[]", "SequenceEqual", "System.Linq.Queryable.SequenceEqual<Test.Program.E>(System.Linq.IQueryable<Test.Program.E>, System.Collections.Generic.IEnumerable<Test.Program.E>)", "System.Linq.IQueryable<Test.Program.E>").WithLocation(17, 35)
);
}
[Fact]
public void Test_005_ObjectTypeBest()
{
// Implicit reference conversions -- From any reference-type to object.
var source = @"
using System.Linq;
namespace Test
{
public class C { };
public interface I { };
public class C2 : I { };
public class Program
{
delegate void D();
public static void M() { }
public static void Main()
{
object o = new object();
C c = new C();
I i = new C2();
D d = new D(M);
int[] aa = new int[] {1};
var a = new [] {o, """", c, i, d, aa};
System.Console.Write(a.SequenceEqual(new object[]{o, """", c, i, d, aa}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_006_ArrayTypeBest()
{
// Implicit reference conversions -- From an array-type S with an element type SE to an array-type T with an element type TE,
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
object[] oa = new object[] {null};
string[] sa = new string[] {null};
var a = new [] {oa, sa};
System.Console.Write(a.SequenceEqual(new object[][]{oa, sa}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_007A()
{
// Implicit reference conversions -- From a one-dimensional array-type S[] to System.Collections.Generic.IList<S>.
var testSrc = @"
using System.Linq;
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static void Main()
{
int[] ia = new int[] {1, 2, 3};
IList<int> la = new List<int> {1, 2, 3};
var a = new [] {ia, la};
System.Console.Write(a.SequenceEqual(new IList<int>[]{ia, la}));
}
}
}
";
var compilation = CompileAndVerify(
testSrc,
expectedOutput: "True");
}
[Fact]
public void Test_007B()
{
// Implicit reference conversions -- From a one-dimensional array-type S[] to System.Collections.Generic.IReadOnlyList<S>.
var testSrc = @"
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static void Main()
{
int[] array = new int[] {1, 2, 3};
object obj = array;
IEnumerable<int> ro1 = array;
IReadOnlyList<int> ro2 = (IReadOnlyList<int>)obj;
IReadOnlyList<int> ro3 = (IReadOnlyList<int>)array;
IReadOnlyList<int> ro4 = obj as IReadOnlyList<int>;
System.Console.WriteLine(ro4 != null ? 1 : 2);
}
}
}
";
var mscorlib17626 = MetadataReference.CreateFromImage(TestMetadata.ResourcesNet451.mscorlib);
CompileAndVerify(testSrc, new MetadataReference[] { mscorlib17626 }, expectedOutput: "1", targetFramework: TargetFramework.Empty);
}
[Fact]
public void Test_008_DelegateType()
{
// Implicit reference conversions -- From any delegate-type to System.Delegate.
var source = @"
using System;
using System.Linq;
namespace Test
{
public class Program
{
delegate void D1();
public static void M1() {}
delegate int D2();
public static int M2() { return 0;}
delegate void D3(int i);
public static void M3(int i) {}
delegate void D4(params object[] o);
public static void M4(params object[] o) { }
public static void Main()
{
D1 d1 = new D1(M1);
D2 d2 = new D2(M2);
D3 d3 = new D3(M3);
D4 d4 = new D4(M4);
Delegate d = d1;
var a = new [] {d, d1, d2, d3, d4};
System.Console.Write(a.SequenceEqual(new Delegate[]{d, d1, d2, d3, d4}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_009_Null()
{
// Implicit reference conversions -- From the null type to any reference-type.
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {""aa"", ""bb"", null};
System.Console.Write(a.SequenceEqual(new string[]{""aa"", ""bb"", null}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_010_TypeParameter()
{
// Implicit reference conversions --
// For a type-parameter T that is known to be a reference type , the following
// implicit reference conversions exist:
// From T to its effective base class C, from T to any base class of C,
// and from T to any interface implemented by C.
var source = @"
using System.Linq;
namespace Test
{
public interface I {}
public class B {}
public class C : B, I {}
public class D : C {}
public class Program
{
public static void M<T>() where T : C, new()
{
T t = new T();
I i = t;
var a = new [] {i, t};
System.Console.Write(a.SequenceEqual(new I[]{i, t}));
}
public static void Main()
{
M<D>();
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_011_BoxingConversion()
{
// Implicit reference conversions -- Boxing conversions
var testSrc = @"
using System;
using System.Linq;
namespace Test
{
public struct S
{
}
public class Program
{
enum E { START };
public static void Main()
{
IComparable v = 1;
int? i = 1;
var a = new [] {v, i, E.START, true, (byte)2, (sbyte)3, (short)4, (ushort)5, 6, 7U, 8L, 9UL, 10.0F, 11.0D, 12M, (char)13};
System.Console.Write(a.SequenceEqual(new IComparable[]{v, i, E.START, true, (byte)2, (sbyte)3, (short)4, (ushort)5, 6, 7U, 8L, 9UL, 10.0F, 11.0D, 12M, (char)13}));
}
}
}
";
var compilation = CompileAndVerify(
testSrc,
expectedOutput: "True");
}
[Fact]
public void Test_012_UserDefinedImplicitConversion()
{
// User-defined implicit conversions.
var testSrc = @"
using System.Linq;
namespace Test
{
public class B {}
public class C
{
public static B b = new B();
public static implicit operator B(C c)
{
return b;
}
}
public class Program
{
public static void Main()
{
B b = new B();
C c = new C();
var a = new [] {b, c};
System.Console.Write(a.SequenceEqual(new B[]{b, c}));
}
}
}
";
// NYI: When user-defined conversion lowering is implemented, replace the
// NYI: error checking below with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
[Fact]
public void Test_013_A_UserDefinedNullableConversions()
{
// Lifted user-defined conversions
var testSrc = @"
using System.Linq;
namespace Test
{
public struct B { }
public struct C
{
public static B b = new B();
public static implicit operator B(C c)
{
return b;
}
}
public class Program
{
public static void Main()
{
C? c = new C();
B? b = new B();
if (!(new [] {b, c}.SequenceEqual(new B?[] {b, c})))
{
System.Console.WriteLine(""Test fail at struct C? implicitly convert to struct B?"");
}
}
}
}
";
// NYI: When lifted user-defined conversion lowering is implemented, replace the
// NYI: error checking below with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
// Bug 10700: We should be able to infer the array type from elements of types int? and short?
[Fact]
public void Test_013_B_NullableConversions()
{
// Lifted implicit numeric conversions
var testSrc = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
int? i = 1;
short? s = 2;
if (!new [] {i, s}.SequenceEqual(new int?[] {i, s}))
{
System.Console.WriteLine(""Test fail at short? implicitly convert to int?"");
}
}
}
}
";
// NYI: When lifted conversions are implemented, remove the diagnostics check
// NYI: and replace it with:
// var compilation = CompileAndVerify(testSrc, emitOptions: EmitOptions.CCI,
// additionalRefs: GetReferences(), expectedOutput: "");
var compilation = CreateCompilationWithMscorlib40AndSystemCore(testSrc);
compilation.VerifyDiagnostics();
}
[Fact]
public void Test_014_LambdaExpression()
{
// Implicitly conversion from lambda expression to compatible delegate type
var source = @"
using System;
namespace Test
{
public class Program
{
delegate int D(int i);
public static int M(int i) {return i;}
public static void Main()
{
var a = new [] {new D(M), (int i)=>{return i;}, x => x+1, (int i)=>{short s = 2; return s;}};
Console.Write(((a is D[]) && (a.Length==4)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_015_ImplicitlyTypedLocalExpr()
{
// local variable declared as "var" type is used inside an implicitly typed array.
var source = @"
using System.Linq;
namespace Test
{
public class B { };
public class C : B { };
public class Program
{
public static void Main()
{
var b = new B();
var c = new C();
var a = new [] {b, c};
System.Console.Write(a.SequenceEqual(new B[]{b, c}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_016_ArrayCreationExpression()
{
// Array creation expression as element in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {new int[1] , new int[3] {11, 12, 13}, new int[] {21, 22, 23}};
Console.Write(((a is int[][]) && (a.Length==3)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_017_AnonymousObjectCreationExpression()
{
// Anonymous object creation expression as element in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a = new [] {new {i = 2, s = ""bb""}, new {i = 3, s = ""cc""}};
Console.Write(((a is Array) && (a.Length==2)));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_018_MemberAccessExpression()
{
// Member access expression as element in implicitly typed arrays
var source = @"
using System.Linq;
using NT = Test;
namespace Test
{
public class Program
{
public delegate int D(string s);
public static D d1 = new D(M2);
public static int M<T>(string s) {return 1;}
public static int M2(string s) {return 2;}
public D d2 = new D(M2);
public static Program p = new Program();
public static Program GetP() {return p;}
public static void Main()
{
System.Console.Write(new [] {Program.d1, Program.M<int>, GetP().d2, int.Parse, NT::Program.M2}.SequenceEqual(
new D[] {Program.d1, Program.M<int>, GetP().d2, int.Parse, NT::Program.M2}));
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_019_JaggedArray()
{
// JaggedArray in implicitly typed arrays
var source = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [] { new [] {new [] {1}},
new [] {new int[] {2}},
new int[][] {new int[] {3}},
new int[][] {new [] {4}} };
if ( !((a3 is int[][][]) && (a3.Length == 4)) )
{
Console.Write(""Test fail"");
}
else
{
Console.Write(""True"");
}
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_020_MultiDimensionalArray()
{
// MultiDimensionalArray in implicitly typed arrays
var testSrc = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [] { new int[,,] {{{3, 4}}},
new int[,,] {{{3, 4}}} };
if ( !((a3 is int[][,,]) && (a3.Rank == 1) && (a3.Length == 2)) )
{
Console.WriteLine(0);
}
else
{
Console.WriteLine(1);
}
}
}
}";
CompileAndVerify(testSrc, expectedOutput: "1");
}
[Fact]
public void Test_021_MultiDimensionalArray_02()
{
// Implicitly typed arrays should can be used in creating MultiDimensionalArray
var testSrc = @"
using System;
namespace Test
{
public class Program
{
public static void Main()
{
var a3 = new [,,] { {{2, 3, 4}}, {{2, 3, 4}} };
if ( !((a3 is int[,,]) && (a3.Rank == 3) && (a3.Length == 6)) )
{
Console.WriteLine(0);
}
else
{
Console.WriteLine(1);
}
}
}
}
";
CompileAndVerify(testSrc, expectedOutput: "1");
}
[Fact]
public void Test_022_GenericMethod()
{
// Implicitly typed arrays used in generic method
var source = @"
using System.Linq;
namespace Test
{
public class Program
{
public static void Main()
{
System.Console.Write(GM(new [] {1, 2, 3}).SequenceEqual(new int[]{1, 2, 3}));
}
public static T GM<T>(T t)
{
return t;
}
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_023_Query()
{
// Query expression as element in implicitly typed arrays
var source = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
int[] ta = new int[] {1, 2, 3, 4, 5};
IEnumerable i = ta;
IEnumerable[] a = new [] {i, from c in ta select c, from c in ta group c by c,
from c in ta select c into g select g, from c in ta where c==3 select c,
from c in ta orderby c select c, from c in ta orderby c ascending select c,
from c in ta orderby c descending select c, from c in ta where c==3 orderby c select c};
Console.Write((a is IEnumerable[]) && (a.Length==9));
}
}
";
CompileAndVerify(
source,
expectedOutput: "True");
}
[Fact]
public void Test_023_Literal()
{
// Query expression as element in implicitly typed arrays
var source = @"
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Console.Write(new [] {true, false}.SequenceEqual(new bool[] {true, false}));
Console.Write(new [] {0123456789U, 1234567890U, 2345678901u, 3456789012UL, 4567890123Ul, 5678901234UL, 6789012345Ul, 7890123456uL, 8901234567ul, 9012345678LU, 9123456780Lu, 1234567809LU, 2345678091LU}.SequenceEqual(
new ulong[] {0123456789U, 1234567890U, 2345678901u, 3456789012UL, 4567890123Ul, 5678901234UL, 6789012345Ul, 7890123456uL, 8901234567ul, 9012345678LU, 9123456780Lu, 1234567809LU, 2345678091LU}));
Console.Write(new [] {0123456789, 1234567890, 2345678901, 3456789012L, 4567890123L, 5678901234L, 6789012345L, 7890123456L, 8901234567L, 9012345678L, 9123456780L, 1234567809L, 2345678091L}.SequenceEqual(
new long[] {0123456789, 1234567890, 2345678901, 3456789012L, 4567890123L, 5678901234L, 6789012345L, 7890123456L, 8901234567L, 9012345678L, 9123456780L, 1234567809L, 2345678091L}));
Console.Write(new [] {0x012345U, 0x6789ABU, 0xCDEFabU, 0xcdef01U, 0X123456U, 0x12579BU, 0x13579Bu, 0x14579BLU, 0x15579BLU, 0x16579BUL, 0x17579BUl, 0x18579BuL, 0x19579Bul, 0x1A579BLU, 0x1B579BLu, 0x1C579BLU, 0x1C579BLu}.SequenceEqual(
new ulong[] {0x012345U, 0x6789ABU, 0xCDEFabU, 0xcdef01U, 0X123456U, 0x12579BU, 0x13579Bu, 0x14579BLU, 0x15579BLU, 0x16579BUL, 0x17579BUl, 0x18579BuL, 0x19579Bul, 0x1A579BLU, 0x1B579BLu, 0x1C579BLU, 0x1C579BLu}));
Console.Write(new [] {0x012345, 0x6789AB, 0xCDEFab, 0xcdef01, 0X123456, 0x12579B, 0x13579B, 0x14579BL, 0x15579BL, 0x16579BL, 0x17579BL, 0x18579BL, 0x19579BL, 0x1A579BL, 0x1B579BL, 0x1C579BL, 0x1C579BL}.SequenceEqual(
new long[] {0x012345, 0x6789AB, 0xCDEFab, 0xcdef01, 0X123456, 0x12579B, 0x13579B, 0x14579BL, 0x15579BL, 0x16579BL, 0x17579BL, 0x18579BL, 0x19579BL, 0x1A579BL, 0x1B579BL, 0x1C579BL, 0x1C579BL}));
Console.Write(new [] {0123456789F, 1234567890f, 2345678901D, 3456789012d, 3.2, 3.3F, 3.4e5, 3.5E5, 3.6E+5, 3.7E-5, 3.8e+5, 3.9e-5, 3.22E5D, .234, .23456D, .245e3, .2334e7D, 3E5, 3E-5, 3E+6, 4E4D}.SequenceEqual(
new double[] {0123456789F, 1234567890f, 2345678901D, 3456789012d, 3.2, 3.3F, 3.4e5, 3.5E5, 3.6E+5, 3.7E-5, 3.8e+5, 3.9e-5, 3.22E5D, .234, .23456D, .245e3, .2334e7D, 3E5, 3E-5, 3E+6, 4E4D})) ;
Console.Write(new [] {0123456789M, 1234567890m, 3.3M, 3.22E5M, 3.2E+4M, 3.3E-4M, .234M, .245e3M, .2334e+7M, .24e-3M, 3E5M, 3E-5M, 3E+6M}.SequenceEqual(
new decimal[] {0123456789M, 1234567890m, 3.3M, 3.22E5M, 3.2E+4M, 3.3E-4M, .234M, .245e3M, .2334e+7M, .24e-3M, 3E5M, 3E-5M, 3E+6M}));
Console.Write(new [] {0123456789, 5678901234UL, 2345678901D, 3.2, 3.4E5, 3.6E+5, 3.7E-5, 3.22E5D, .234, .23456D, .245E3, 3E5, 4E4D}.SequenceEqual(
new double[] {0123456789, 5678901234UL, 2345678901D, 3.2, 3.4E5, 3.6E+5, 3.7E-5, 3.22E5D, .234, .23456D, .245E3, 3E5, 4E4D}));
Console.Write(new [] {0123456789, 5678901234UL, 2345678901M, 3.2M, 3.4E5M, 3.6E+5M, 3.7E-5M, .234M, .245E3M, 3E5M}.SequenceEqual(
new decimal[] {0123456789, 5678901234UL, 2345678901M, 3.2M, 3.4E5M, 3.6E+5M, 3.7E-5M, .234M, .245E3M, 3E5M}));
}
}
";
CompileAndVerify(
source,
expectedOutput: "TrueTrueTrueTrueTrueTrueTrueTrueTrue");
}
#endregion
#region "Error tests"
[Fact]
public void Error_NonArrayInitExpr()
{
var testSrc = @"
namespace Test
{
public class Program
{
public void Goo()
{
var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
}
}
}
";
var comp = CreateCompilation(testSrc);
comp.VerifyDiagnostics(
// (8,46): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "3").WithLocation(8, 46),
// (8,49): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "4").WithLocation(8, 49));
}
[Fact]
public void Error_NonArrayInitExpr_02()
{
var testSrc = @"
namespace Test
{
public class Program
{
public void Goo()
{
var a3 = new[,,] { { { 3, 4 } }, x, 4 };
}
}
}
";
var comp = CreateCompilation(testSrc);
comp.VerifyDiagnostics(
// (8,46): error CS0103: The name 'x' does not exist in the current context
// var a3 = new[,,] { { { 3, 4 } }, x, 4 };
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(8, 46),
// (8,49): error CS0846: A nested array initializer is expected
// var a3 = new[,,] { { { 3, 4 } }, x, 4 };
Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "4").WithLocation(8, 49));
}
[WorkItem(543571, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543571")]
[Fact]
public void CS0826ERR_ImplicitlyTypedArrayNoBestType()
{
var text = @"
using System;
namespace Test
{
public class Program
{
enum E
{
Zero,
FortyTwo = 42
};
public static void Main()
{
E[] a = new[] { E.FortyTwo, 0 }; // Dev10 error CS0826
Console.WriteLine(String.Format(""Type={0}, a[0]={1}, a[1]={2}"", a.GetType(), a[0], a[1]));
}
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (16,21): error CS0826: No best type found for implicitly-typed array
// E[] a = new[] { E.FortyTwo, 0 }; // Dev10 error CS0826
Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { E.FortyTwo, 0 }").WithLocation(16, 21));
}
#endregion
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Roslyn.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer,
Microsoft.CodeAnalysis.CSharp.ImplementInterface.CSharpImplementInterfaceCodeFixProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface
{
public class ImplementInterfaceTests
{
private readonly NamingStylesTestOptionSets _options = new NamingStylesTestOptionSets(LanguageNames.CSharp);
private static OptionsCollection AllOptionsOff
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
};
private static OptionsCollection AllOptionsOn
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
};
private static OptionsCollection AccessorOptionsOn
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
};
internal static async Task TestWithAllCodeStyleOptionsOffAsync(
string initialMarkup, string expectedMarkup,
(string equivalenceKey, int index)? codeAction = null)
{
await new VerifyCS.Test
{
TestCode = initialMarkup,
FixedCode = expectedMarkup,
Options = { AllOptionsOff },
CodeActionEquivalenceKey = codeAction?.equivalenceKey,
CodeActionIndex = codeAction?.index,
}.RunAsync();
}
internal static async Task TestWithAllCodeStyleOptionsOnAsync(string initialMarkup, string expectedMarkup)
{
await new VerifyCS.Test
{
TestCode = initialMarkup,
FixedCode = expectedMarkup,
Options = { AllOptionsOn },
}.RunAsync();
}
internal static async Task TestWithAccessorCodeStyleOptionsOnAsync(string initialMarkup, string expectedMarkup)
{
await new VerifyCS.Test
{
TestCode = initialMarkup,
FixedCode = expectedMarkup,
Options = { AccessorOptionsOn },
}.RunAsync();
}
private static async Task TestInRegularAndScriptAsync(
string initialMarkup,
string expectedMarkup,
(string equivalenceKey, int index)? codeAction = null)
{
await new VerifyCS.Test
{
TestCode = initialMarkup,
FixedCode = expectedMarkup,
CodeActionEquivalenceKey = codeAction?.equivalenceKey,
CodeActionIndex = codeAction?.index,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethod()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
void Method1();
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
void Method1();
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethodInRecord()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.Preview,
TestCode = @"interface IInterface
{
void Method1();
}
record Record : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
}
record Record : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
[WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")]
public async Task TestMethodWithNativeIntegers()
{
var nativeIntegerAttributeDefinition = @"
namespace System.Runtime.CompilerServices
{
[System.AttributeUsage(AttributeTargets.All)]
public sealed class NativeIntegerAttribute : System.Attribute
{
public NativeIntegerAttribute()
{
}
public NativeIntegerAttribute(bool[] flags)
{
}
}
}";
// Note: we're putting the attribute by hand to simulate metadata
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"interface IInterface
{
[return: {|CS8335:System.Runtime.CompilerServices.NativeInteger(new[] { true, true })|}]
(nint, nuint) Method(nint x, nuint x2);
}
class Class : {|CS0535:IInterface|}
{
}" + nativeIntegerAttributeDefinition,
FixedCode = @"interface IInterface
{
[return: {|CS8335:System.Runtime.CompilerServices.NativeInteger(new[] { true, true })|}]
(nint, nuint) Method(nint x, nuint x2);
}
class Class : IInterface
{
public (nint, nuint) Method(nint x, nuint x2)
{
throw new System.NotImplementedException();
}
}" + nativeIntegerAttributeDefinition,
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethodWithTuple()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
(int, int) Method((string, string) x);
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
(int, int) Method((string, string) x);
}
class Class : IInterface
{
public (int, int) Method((string, string) x)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(16793, "https://github.com/dotnet/roslyn/issues/16793")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethodWithValueTupleArity1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"
using System;
interface I
{
ValueTuple<object> F();
}
class C : {|CS0535:I|}
{
}",
@"
using System;
interface I
{
ValueTuple<object> F();
}
class C : I
{
public ValueTuple<object> F()
{
throw new NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExpressionBodiedMethod1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"interface IInterface
{
void Method1();
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
void Method1();
}
class Class : IInterface
{
public void Method1() => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)]
public async Task TupleWithNamesInMethod()
{
// Note: we're putting the attribute by hand to simulate metadata
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
[return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Method1((int c, string) x);
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
[return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Method1((int c, string) x);
}
class Class : IInterface
{
public (int a, int b)[] Method1((int c, string) x)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)]
public async Task TupleWithNamesInMethod_Explicitly()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
[return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Method1((int c, string) x);
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
[return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Method1((int c, string) x);
}
class Class : IInterface
{
(int a, int b)[] IInterface.Method1((int c, string) x)
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)]
public async Task TupleWithNamesInProperty()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
[{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Property1 { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] get; [param: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] set; }
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
[{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Property1 { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] get; [param: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] set; }
}
class Class : IInterface
{
public (int a, int b)[] Property1
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)]
public async Task TupleWithNamesInEvent()
{
await new VerifyCS.Test
{
TestCode = @"interface IInterface
{
[{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
event System.Func<(int a, int b)> Event1;
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"using System;
interface IInterface
{
[{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
event System.Func<(int a, int b)> Event1;
}
class Class : IInterface
{
public event Func<(int a, int b)> Event1;
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task NoDynamicAttributeInMethod()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
[return: {|CS1970:System.Runtime.CompilerServices.DynamicAttribute()|}]
object Method1();
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
[return: {|CS1970:System.Runtime.CompilerServices.DynamicAttribute()|}]
object Method1();
}
class Class : IInterface
{
public object Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task NoNullableAttributesInMethodFromMetadata()
{
var test = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
#nullable enable
using System;
class C : {|CS0535:{|CS0535:IInterface|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"
#nullable enable
public interface IInterface
{
void M(string? s1, string s2);
string this[string? s1, string s2] { get; set; }
}"
},
},
},
AdditionalProjectReferences =
{
"Assembly1",
},
},
FixedState =
{
Sources =
{
@"
#nullable enable
using System;
class C : IInterface
{
public string this[string? s1, string s2]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void M(string? s1, string s2)
{
throw new NotImplementedException();
}
}",
},
},
CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethodWhenClassBracesAreMissing()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
void Method1();
}
class Class : {|CS0535:IInterface|}{|CS1513:|}{|CS1514:|}",
@"interface IInterface
{
void Method1();
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInheritance1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
}
class Class : {|CS0535:IInterface2|}
{
}",
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
}
class Class : IInterface2
{
public void Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInheritance2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
}
interface IInterface2 : IInterface1
{
void Method1();
}
class Class : {|CS0535:IInterface2|}
{
}",
@"interface IInterface1
{
}
interface IInterface2 : IInterface1
{
void Method1();
}
class Class : IInterface2
{
public void Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInheritance3()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
void Method2();
}
class Class : {|CS0535:{|CS0535:IInterface2|}|}
{
}",
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
void Method2();
}
class Class : IInterface2
{
public void Method1()
{
throw new System.NotImplementedException();
}
public void Method2()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInheritanceMatchingMethod()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
void Method1();
}
class Class : {|CS0535:{|CS0535:IInterface2|}|}
{
}",
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
void Method1();
}
class Class : IInterface2
{
public void Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExistingConflictingMethodReturnType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
void Method1();
}
class Class : {|CS0738:IInterface1|}
{
public int Method1()
{
return 0;
}
}",
@"interface IInterface1
{
void Method1();
}
class Class : IInterface1
{
public int Method1()
{
return 0;
}
void IInterface1.Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExistingConflictingMethodParameters()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
void Method1(int i);
}
class Class : {|CS0535:IInterface1|}
{
public void Method1(string i)
{
}
}",
@"interface IInterface1
{
void Method1(int i);
}
class Class : IInterface1
{
public void Method1(string i)
{
}
public void Method1(int i)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementGenericType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1<T>
{
void Method1(T t);
}
class Class : {|CS0535:IInterface1<int>|}
{
}",
@"interface IInterface1<T>
{
void Method1(T t);
}
class Class : IInterface1<int>
{
public void Method1(int t)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementGenericTypeWithGenericMethod()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1<T>
{
void Method1<U>(T t, U u);
}
class Class : {|CS0535:IInterface1<int>|}
{
}",
@"interface IInterface1<T>
{
void Method1<U>(T t, U u);
}
class Class : IInterface1<int>
{
public void Method1<U>(int t, U u)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementGenericTypeWithGenericMethodWithNaturalConstraint()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections.Generic;
interface IInterface1<T>
{
void Method1<U>(T t, U u) where U : IList<T>;
}
class Class : {|CS0535:IInterface1<int>|}
{
}",
@"using System.Collections.Generic;
interface IInterface1<T>
{
void Method1<U>(T t, U u) where U : IList<T>;
}
class Class : IInterface1<int>
{
public void Method1<U>(int t, U u) where U : IList<int>
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementGenericTypeWithGenericMethodWithUnexpressibleConstraint()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1<T>
{
void Method1<U>(T t, U u) where U : T;
}
class Class : {|CS0535:IInterface1<int>|}
{
}",
@"interface IInterface1<T>
{
void Method1<U>(T t, U u) where U : T;
}
class Class : IInterface1<int>
{
void IInterface1<int>.Method1<U>(int t, U u)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestArrayType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
string[] M();
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
string[] M();
}
class C : I
{
public string[] M()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMember()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Method1();
}
class C : {|CS0535:I|}
{
I i;
}",
@"interface I
{
void Method1();
}
class C : I
{
I i;
public void Method1()
{
i.Method1();
}
}",
codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMember_FixAll_SameMemberInDifferentType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Method1();
}
class C : {|CS0535:I|}
{
I i;
}
class D : {|CS0535:I|}
{
I i;
}",
@"interface I
{
void Method1();
}
class C : I
{
I i;
public void Method1()
{
i.Method1();
}
}
class D : I
{
I i;
public void Method1()
{
i.Method1();
}
}",
codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMember_FixAll_FieldInOnePropInAnother()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Method1();
}
class C : {|CS0535:I|}
{
I i;
}
class D : {|CS0535:I|}
{
I i { get; }
}",
@"interface I
{
void Method1();
}
class C : I
{
I i;
public void Method1()
{
i.Method1();
}
}
class D : I
{
I i { get; }
public void Method1()
{
i.Method1();
}
}",
codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMember_FixAll_FieldInOneNonViableInAnother()
{
var test = new VerifyCS.Test
{
TestCode = @"interface I
{
void Method1();
}
class C : {|CS0535:I|}
{
I i;
}
class D : {|CS0535:I|}
{
int i;
}",
FixedState =
{
Sources =
{
@"interface I
{
void Method1();
}
class C : I
{
I i;
public void Method1()
{
i.Method1();
}
}
class D : {|CS0535:I|}
{
int i;
}",
},
MarkupHandling = MarkupMode.Allow,
},
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i",
CodeActionIndex = 1,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMemberInterfaceWithIndexer()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
int this[int x] { get; set; }
}
class Goo : {|CS0535:IGoo|}
{
IGoo f;
}",
@"interface IGoo
{
int this[int x] { get; set; }
}
class Goo : IGoo
{
IGoo f;
public int this[int x]
{
get
{
return f[x];
}
set
{
f[x] = value;
}
}
}",
codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;f", 1));
}
[WorkItem(472, "https://github.com/dotnet/roslyn/issues/472")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMemberRemoveUnnecessaryCast()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections;
sealed class X : {|CS0535:IComparer|}
{
X x;
}",
@"using System.Collections;
sealed class X : IComparer
{
X x;
public int Compare(object x, object y)
{
return ((IComparer)this.x).Compare(x, y);
}
}",
codeAction: ("False;False;False:global::System.Collections.IComparer;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;x", 1));
}
[WorkItem(472, "https://github.com/dotnet/roslyn/issues/472")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMemberRemoveUnnecessaryCastAndThis()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections;
sealed class X : {|CS0535:IComparer|}
{
X a;
}",
@"using System.Collections;
sealed class X : IComparer
{
X a;
public int Compare(object x, object y)
{
return ((IComparer)a).Compare(x, y);
}
}",
codeAction: ("False;False;False:global::System.Collections.IComparer;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementAbstract()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Method1();
}
abstract class C : {|CS0535:I|}
{
}",
@"interface I
{
void Method1();
}
abstract class C : I
{
public abstract void Method1();
}",
codeAction: ("False;True;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceWithRefOutParameters()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class C : {|CS0535:{|CS0535:I|}|}
{
I goo;
}
interface I
{
void Method1(ref int x, out int y, int z);
int Method2();
}",
@"class C : I
{
I goo;
public void Method1(ref int x, out int y, int z)
{
goo.Method1(ref x, out y, z);
}
public int Method2()
{
return goo.Method2();
}
}
interface I
{
void Method1(ref int x, out int y, int z);
int Method2();
}",
codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConflictingMethods1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class B
{
public int Method1()
{
return 0;
}
}
class C : B, {|CS0738:I|}
{
}
interface I
{
void Method1();
}",
@"class B
{
public int Method1()
{
return 0;
}
}
class C : B, I
{
void I.Method1()
{
throw new System.NotImplementedException();
}
}
interface I
{
void Method1();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConflictingProperties()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class Test : {|CS0737:I1|}
{
int Prop { get; set; }
}
interface I1
{
int Prop { get; set; }
}",
@"class Test : I1
{
int Prop { get; set; }
int I1.Prop
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}
interface I1
{
int Prop { get; set; }
}");
}
[WorkItem(539043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExplicitProperties()
{
var code =
@"interface I2
{
decimal Calc { get; }
}
class C : I2
{
protected decimal pay;
decimal I2.Calc
{
get
{
return pay;
}
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedMethodName()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
void @M();
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
void @M();
}
class Class : IInterface
{
public void M()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedMethodKeyword()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
void @int();
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
void @int();
}
class Class : IInterface
{
public void @int()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedInterfaceName1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface @IInterface
{
void M();
}
class Class : {|CS0737:@IInterface|}
{
string M() => """";
}",
@"interface @IInterface
{
void M();
}
class Class : @IInterface
{
string M() => """";
void IInterface.M()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedInterfaceName2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface @IInterface
{
void @M();
}
class Class : {|CS0737:@IInterface|}
{
string M() => """";
}",
@"interface @IInterface
{
void @M();
}
class Class : @IInterface
{
string M() => """";
void IInterface.M()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedInterfaceKeyword1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface @int
{
void M();
}
class Class : {|CS0737:@int|}
{
string M() => """";
}",
@"interface @int
{
void M();
}
class Class : @int
{
string M() => """";
void @int.M()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedInterfaceKeyword2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface @int
{
void @bool();
}
class Class : {|CS0737:@int|}
{
string @bool() => """";
}",
@"interface @int
{
void @bool();
}
class Class : @int
{
string @bool() => """";
void @int.@bool()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestPropertyFormatting()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface DD
{
int Prop { get; set; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; set; }
}
public class A : DD
{
public int Prop
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestProperty_PropertyCodeStyleOn1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int Prop { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; }
}
public class A : DD
{
public int Prop => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestProperty_AccessorCodeStyleOn1()
{
await TestWithAccessorCodeStyleOptionsOnAsync(
@"public interface DD
{
int Prop { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; }
}
public class A : DD
{
public int Prop { get => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexer_IndexerCodeStyleOn1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; }
}
public class A : DD
{
public int this[int i] => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexer_AccessorCodeStyleOn1()
{
await TestWithAccessorCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; }
}
public class A : DD
{
public int this[int i] { get => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethod_AllCodeStyleOn1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int M();
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int M();
}
public class A : DD
{
public int M() => throw new System.NotImplementedException();
}");
}
[WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestReadonlyPropertyExpressionBodyYes1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int Prop { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; }
}
public class A : DD
{
public int Prop => throw new System.NotImplementedException();
}");
}
[WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestReadonlyPropertyAccessorBodyYes1()
{
await TestWithAccessorCodeStyleOptionsOnAsync(
@"public interface DD
{
int Prop { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; }
}
public class A : DD
{
public int Prop { get => throw new System.NotImplementedException(); }
}");
}
[WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestReadonlyPropertyAccessorBodyYes2()
{
await TestWithAccessorCodeStyleOptionsOnAsync(
@"public interface DD
{
int Prop { get; set; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; set; }
}
public class A : DD
{
public int Prop { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
}");
}
[WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestReadonlyPropertyExpressionBodyNo1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface DD
{
int Prop { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; }
}
public class A : DD
{
public int Prop
{
get
{
throw new System.NotImplementedException();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexerExpressionBodyYes1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; }
}
public class A : DD
{
public int this[int i] => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexerExpressionBodyNo1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; set; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; set; }
}
public class A : DD
{
public int this[int i] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexerAccessorExpressionBodyYes1()
{
await TestWithAccessorCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; }
}
public class A : DD
{
public int this[int i] { get => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexerAccessorExpressionBodyYes2()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; set; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; set; }
}
public class A : DD
{
public int this[int i] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCommentPlacement()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface DD
{
void Goo();
}
public class A : {|CS0535:DD|}
{
//comments
}",
@"public interface DD
{
void Goo();
}
public class A : DD
{
//comments
public void Goo()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539991")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestBracePlacement()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IServiceProvider
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(540318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMissingWithIncompleteMember()
{
var code =
@"interface ITest
{
void Method();
}
class Test : ITest
{
p {|CS1585:public|} void Method()
{
throw new System.NotImplementedException();
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[WorkItem(541380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541380")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExplicitProperty()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface i1
{
int p { get; set; }
}
class c1 : {|CS0535:i1|}
{
}",
@"interface i1
{
int p { get; set; }
}
class c1 : i1
{
int i1.p
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}",
codeAction: ("True;False;False:global::i1;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(541981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541981")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoDelegateThroughField1()
{
var code =
@"interface I
{
void Method1();
}
class C : {|CS0535:I|}
{
I i { get; set; }
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = @"interface I
{
void Method1();
}
class C : I
{
I i { get; set; }
public void Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
CodeActionEquivalenceKey = "False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
await new VerifyCS.Test
{
TestCode = code,
FixedCode = @"interface I
{
void Method1();
}
class C : I
{
I i { get; set; }
public void Method1()
{
i.Method1();
}
}",
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i",
CodeActionIndex = 1,
}.RunAsync();
await new VerifyCS.Test
{
TestCode = code,
FixedCode = @"interface I
{
void Method1();
}
class C : I
{
I i { get; set; }
void I.Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
CodeActionEquivalenceKey = "True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 2,
}.RunAsync();
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIReadOnlyListThroughField()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections.Generic;
class A : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IReadOnlyList<int>|}|}|}|}
{
int[] field;
}",
@"using System.Collections;
using System.Collections.Generic;
class A : IReadOnlyList<int>
{
int[] field;
public int this[int index]
{
get
{
return ((IReadOnlyList<int>)field)[index];
}
}
public int Count
{
get
{
return ((IReadOnlyCollection<int>)field).Count;
}
}
public IEnumerator<int> GetEnumerator()
{
return ((IEnumerable<int>)field).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return field.GetEnumerator();
}
}",
codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList<int>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1));
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIReadOnlyListThroughProperty()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections.Generic;
class A : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IReadOnlyList<int>|}|}|}|}
{
int[] field { get; set; }
}",
@"using System.Collections;
using System.Collections.Generic;
class A : IReadOnlyList<int>
{
public int this[int index]
{
get
{
return ((IReadOnlyList<int>)field)[index];
}
}
public int Count
{
get
{
return ((IReadOnlyCollection<int>)field).Count;
}
}
int[] field { get; set; }
public IEnumerator<int> GetEnumerator()
{
return ((IEnumerable<int>)field).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return field.GetEnumerator();
}
}",
codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList<int>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1));
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughField()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A a;
}",
@"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I
{
A a;
public int M()
{
return ((I)a).M();
}
}",
codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1));
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughField_FieldImplementsMultipleInterfaces()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I, I2
{
int I.M()
{
return 0;
}
int I2.M2()
{
return 0;
}
}
class B : {|CS0535:I|}, {|CS0535:I2|}
{
A a;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I, I2
{
int I.M()
{
return 0;
}
int I2.M2()
{
return 0;
}
}
class B : I, {|CS0535:I2|}
{
A a;
public int M()
{
return ((I)a).M();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
DiagnosticSelector = diagnostics => diagnostics[0],
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a",
CodeActionIndex = 1,
}.RunAsync();
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I, I2
{
int I.M()
{
return 0;
}
int I2.M2()
{
return 0;
}
}
class B : {|CS0535:I|}, {|CS0535:I2|}
{
A a;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I, I2
{
int I.M()
{
return 0;
}
int I2.M2()
{
return 0;
}
}
class B : {|CS0535:I|}, I2
{
A a;
public int M2()
{
return ((I2)a).M2();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
DiagnosticSelector = diagnostics => diagnostics[1],
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "False;False;False:global::I2;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughField_MultipleFieldsCanImplementInterface()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A a;
A aa;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I
{
A a;
A aa;
public int M()
{
return ((I)a).M();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(4, codeActions.Length),
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a",
CodeActionIndex = 1,
}.RunAsync();
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A a;
A aa;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I
{
A a;
A aa;
public int M()
{
return ((I)aa).M();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(4, codeActions.Length),
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;aa",
CodeActionIndex = 2,
}.RunAsync();
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughField_MultipleFieldsForMultipleInterfaces()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I2
{
int I2.M2()
{
return 0;
}
}
class C : {|CS0535:I|}, {|CS0535:I2|}
{
A a;
B b;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I2
{
int I2.M2()
{
return 0;
}
}
class C : I, {|CS0535:I2|}
{
A a;
B b;
public int M()
{
return ((I)a).M();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
DiagnosticSelector = diagnostics => diagnostics[0],
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a",
CodeActionIndex = 1,
}.RunAsync();
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I2
{
int I2.M2()
{
return 0;
}
}
class C : {|CS0535:I|}, {|CS0535:I2|}
{
A a;
B b;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I2
{
int I2.M2()
{
return 0;
}
}
class C : {|CS0535:I|}, I2
{
A a;
B b;
public int M2()
{
return ((I2)b).M2();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
DiagnosticSelector = diagnostics => diagnostics[1],
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "False;False;False:global::I2;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;b",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(18556, "https://github.com/dotnet/roslyn/issues/18556")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughExplicitProperty()
{
await new VerifyCS.Test
{
TestCode = @"interface IA
{
IB B { get; }
}
interface IB
{
int M();
}
class AB : IA, {|CS0535:IB|}
{
IB IA.B => null;
}",
FixedCode = @"interface IA
{
IB B { get; }
}
interface IB
{
int M();
}
class AB : IA, IB
{
IB IA.B => null;
public int M()
{
return ((IA)this).B.M();
}
}",
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
CodeActionEquivalenceKey = "False;False;False:global::IB;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;IA.B",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoImplementThroughIndexer()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A this[int index]
{
get
{
return null;
}
}
}",
FixedCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I
{
A this[int index]
{
get
{
return null;
}
}
public int M()
{
throw new System.NotImplementedException();
}
}",
CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length),
}.RunAsync();
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoImplementThroughWriteOnlyProperty()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A a
{
set
{
}
}
}",
FixedCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A a
{
set
{
}
}
public int M()
{
throw new System.NotImplementedException();
}
}",
CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementEventThroughMember()
{
await TestInRegularAndScriptAsync(@"
interface IGoo
{
event System.EventHandler E;
}
class CanGoo : IGoo
{
public event System.EventHandler E;
}
class HasCanGoo : {|CS0535:IGoo|}
{
CanGoo canGoo;
}",
@"
using System;
interface IGoo
{
event System.EventHandler E;
}
class CanGoo : IGoo
{
public event System.EventHandler E;
}
class HasCanGoo : IGoo
{
CanGoo canGoo;
public event EventHandler E
{
add
{
((IGoo)canGoo).E += value;
}
remove
{
((IGoo)canGoo).E -= value;
}
}
}", codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;canGoo", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementEventThroughExplicitMember()
{
await TestInRegularAndScriptAsync(
@"interface IGoo { event System . EventHandler E ; } class CanGoo : IGoo { event System.EventHandler IGoo.E { add { } remove { } } } class HasCanGoo : {|CS0535:IGoo|} { CanGoo canGoo; } ",
@"using System;
interface IGoo { event System . EventHandler E ; } class CanGoo : IGoo { event System.EventHandler IGoo.E { add { } remove { } } } class HasCanGoo : IGoo { CanGoo canGoo;
public event EventHandler E
{
add
{
((IGoo)canGoo).E += value;
}
remove
{
((IGoo)canGoo).E -= value;
}
}
} ",
codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;canGoo", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementEvent()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : {|CS0535:IGoo|}
{
}",
@"using System;
interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : IGoo
{
public event EventHandler E;
}",
codeAction: ("False;False;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementEventAbstractly()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : {|CS0535:IGoo|}
{
}",
@"using System;
interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : IGoo
{
public abstract event EventHandler E;
}",
codeAction: ("False;True;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementEventExplicitly()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : {|CS0535:IGoo|}
{
}",
@"using System;
interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : IGoo
{
event EventHandler IGoo.E
{
add
{
throw new NotImplementedException();
}
remove
{
throw new NotImplementedException();
}
}
}",
codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestFaultToleranceInStaticMembers_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IFoo
{
static string Name { set; get; }
static int {|CS0501:Foo|}(string s);
}
class Program : IFoo
{
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestFaultToleranceInStaticMembers_02()
{
var test = new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IFoo
{
string Name { set; get; }
static int {|CS0501:Foo|}(string s);
}
class Program : {|CS0535:IFoo|}
{
}",
FixedCode = @"interface IFoo
{
string Name { set; get; }
static int {|CS0501:Foo|}(string s);
}
class Program : IFoo
{
public string Name
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}",
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestFaultToleranceInStaticMembers_03()
{
var test = new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IGoo
{
static string Name { set; get; }
int Goo(string s);
}
class Program : {|CS0535:IGoo|}
{
}",
FixedCode = @"interface IGoo
{
static string Name { set; get; }
int Goo(string s);
}
class Program : IGoo
{
public int Goo(string s)
{
throw new System.NotImplementedException();
}
}",
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexers()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface ISomeInterface
{
int this[int index] { get; set; }
}
class IndexerClass : {|CS0535:ISomeInterface|}
{
}",
@"public interface ISomeInterface
{
int this[int index] { get; set; }
}
class IndexerClass : ISomeInterface
{
public int this[int index]
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexersExplicit()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface ISomeInterface
{
int this[int index] { get; set; }
}
class IndexerClass : {|CS0535:ISomeInterface|}
{
}",
@"public interface ISomeInterface
{
int this[int index] { get; set; }
}
class IndexerClass : ISomeInterface
{
int ISomeInterface.this[int index]
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}",
codeAction: ("True;False;False:global::ISomeInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexersWithASingleAccessor()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface ISomeInterface
{
int this[int index] { get; }
}
class IndexerClass : {|CS0535:ISomeInterface|}
{
}",
@"public interface ISomeInterface
{
int this[int index] { get; }
}
class IndexerClass : ISomeInterface
{
public int this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConstraints1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo<T>() where T : class;
}
class A : {|CS0535:I|}
{
}",
@"interface I
{
void Goo<T>() where T : class;
}
class A : I
{
public void Goo<T>() where T : class
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConstraintsExplicit()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo<T>() where T : class;
}
class A : {|CS0535:I|}
{
}",
@"interface I
{
void Goo<T>() where T : class;
}
class A : I
{
void I.Goo<T>()
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUsingAddedForConstraint()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo<T>() where T : System.Attribute;
}
class A : {|CS0535:I|}
{
}",
@"using System;
interface I
{
void Goo<T>() where T : System.Attribute;
}
class A : I
{
public void Goo<T>() where T : Attribute
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542379")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexer()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
int this[int x] { get; set; }
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
int this[int x] { get; set; }
}
class C : I
{
public int this[int x]
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(542588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542588")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRecursiveConstraint1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void Goo<T>() where T : IComparable<T>;
}
class C : {|CS0535:I|}
{
}",
@"using System;
interface I
{
void Goo<T>() where T : IComparable<T>;
}
class C : I
{
public void Goo<T>() where T : IComparable<T>
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542588")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRecursiveConstraint2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void Goo<T>() where T : IComparable<T>;
}
class C : {|CS0535:I|}
{
}",
@"using System;
interface I
{
void Goo<T>() where T : IComparable<T>;
}
class C : I
{
void I.Goo<T>()
{
throw new NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<string>|}
{
}",
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<string>
{
void I<string>.Goo<T>()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<object>|}
{
}",
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<object>
{
public void Goo<T>() where T : class
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint3()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<object>|}
{
}",
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<object>
{
void I<object>.Goo<T>()
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I<object>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint4()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<Delegate>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<Delegate>
{
void I<Delegate>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint5()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<MulticastDelegate>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<MulticastDelegate>
{
void I<MulticastDelegate>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint6()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
delegate void Bar();
class A : {|CS0535:I<Bar>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
delegate void Bar();
class A : I<Bar>
{
void I<Bar>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint7()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<Enum>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<Enum>
{
void I<Enum>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint8()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<int[]>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<int[]>
{
void I<int[]>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint9()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
enum E
{
}
class A : {|CS0535:I<E>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
enum E
{
}
class A : I<E>
{
void I<E>.Goo<{|CS0455:T|}>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542621")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint10()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : S;
}
class A : {|CS0535:I<ValueType>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : S;
}
class A : I<ValueType>
{
void I<ValueType>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542669")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestArrayConstraint()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : S;
}
class C : {|CS0535:I<Array>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : S;
}
class C : I<Array>
{
void I<Array>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542743")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMultipleClassConstraints()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : Exception, S;
}
class C : {|CS0535:I<Attribute>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : Exception, S;
}
class C : I<Attribute>
{
void I<Attribute>.Goo<{|CS0455:T|}>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542751")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestClassConstraintAndRefConstraint()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class C : {|CS0535:I<Exception>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class C : I<Exception>
{
void I<Exception>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRenameConflictingTypeParameters1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Collections.Generic;
interface I<T>
{
void Goo<S>(T x, IList<S> list) where S : T;
}
class A<S> : {|CS0535:I<S>|}
{
}",
@"using System;
using System.Collections.Generic;
interface I<T>
{
void Goo<S>(T x, IList<S> list) where S : T;
}
class A<S> : I<S>
{
public void Goo<S1>(S x, IList<S1> list) where S1 : S
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRenameConflictingTypeParameters2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Collections.Generic;
interface I<T>
{
void Goo<S>(T x, IList<S> list) where S : T;
}
class A<S> : {|CS0535:I<S>|}
{
}",
@"using System;
using System.Collections.Generic;
interface I<T>
{
void Goo<S>(T x, IList<S> list) where S : T;
}
class A<S> : I<S>
{
void I<S>.Goo<S1>(S x, IList<S1> list)
{
throw new NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I<S>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRenameConflictingTypeParameters3()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Collections.Generic;
interface I<X, Y>
{
void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2)
where A : IList<B>
where B : IList<A>;
}
class C<A, B> : {|CS0535:I<A, B>|}
{
}",
@"using System;
using System.Collections.Generic;
interface I<X, Y>
{
void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2)
where A : IList<B>
where B : IList<A>;
}
class C<A, B> : I<A, B>
{
public void Goo<A1, B1>(A x, B y, IList<A1> list1, IList<B1> list2)
where A1 : IList<B1>
where B1 : IList<A1>
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRenameConflictingTypeParameters4()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Collections.Generic;
interface I<X, Y>
{
void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2)
where A : IList<B>
where B : IList<A>;
}
class C<A, B> : {|CS0535:I<A, B>|}
{
}",
@"using System;
using System.Collections.Generic;
interface I<X, Y>
{
void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2)
where A : IList<B>
where B : IList<A>;
}
class C<A, B> : I<A, B>
{
void I<A, B>.Goo<A1, B1>(A x, B y, IList<A1> list1, IList<B1> list2)
{
throw new NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I<A, B>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNameSimplification()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class A<T>
{
class B
{
}
interface I
{
void Goo(B x);
}
class C<U> : {|CS0535:I|}
{
}
}",
@"using System;
class A<T>
{
class B
{
}
interface I
{
void Goo(B x);
}
class C<U> : I
{
public void Goo(B x)
{
throw new NotImplementedException();
}
}
}");
}
[WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNameSimplification2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class A<T>
{
class B
{
}
interface I
{
void Goo(B[] x);
}
class C<U> : {|CS0535:I|}
{
}
}",
@"class A<T>
{
class B
{
}
interface I
{
void Goo(B[] x);
}
class C<U> : I
{
public void Goo(B[] x)
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNameSimplification3()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class A<T>
{
class B
{
}
interface I
{
void Goo(B[][,][,,][,,,] x);
}
class C<U> : {|CS0535:I|}
{
}
}",
@"class A<T>
{
class B
{
}
interface I
{
void Goo(B[][,][,,][,,,] x);
}
class C<U> : I
{
public void Goo(B[][,][,,][,,,] x)
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(544166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544166")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementAbstractProperty()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
int Gibberish { get; set; }
}
abstract class Goo : {|CS0535:IGoo|}
{
}",
@"interface IGoo
{
int Gibberish { get; set; }
}
abstract class Goo : IGoo
{
public abstract int Gibberish { get; set; }
}",
codeAction: ("False;True;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(544210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544210")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMissingOnWrongArity()
{
var code =
@"interface I1<T>
{
int X { get; set; }
}
class C : {|CS0305:I1|}
{
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[WorkItem(544281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544281")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplicitDefaultValue()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IOptional
{
int Goo(int g = 0);
}
class Opt : {|CS0535:IOptional|}
{
}",
@"interface IOptional
{
int Goo(int g = 0);
}
class Opt : IOptional
{
public int Goo(int g = 0)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(544281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544281")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExplicitDefaultValue()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IOptional
{
int Goo(int g = 0);
}
class Opt : {|CS0535:IOptional|}
{
}",
@"interface IOptional
{
int Goo(int g = 0);
}
class Opt : IOptional
{
int IOptional.Goo(int g)
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::IOptional;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMissingInHiddenType()
{
var code =
@"using System;
class Program : {|CS0535:IComparable|}
{
#line hidden
}
#line default";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestGenerateIntoVisiblePart()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"#line default
using System;
partial class Program : {|CS0535:IComparable|}
{
void Goo()
{
#line hidden
}
}
#line default",
@"#line default
using System;
partial class Program : IComparable
{
public int CompareTo(object obj)
{
throw new NotImplementedException();
}
void Goo()
{
#line hidden
}
}
#line default");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestGenerateIfAvailableRegionExists()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
partial class Program : {|CS0535:IComparable|}
{
#line hidden
}
#line default
partial class Program
{
}",
@"using System;
partial class Program : IComparable
{
#line hidden
}
#line default
partial class Program
{
public int CompareTo(object obj)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(545334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545334")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoGenerateInVenusCase1()
{
var code =
@"using System;
#line 1 ""Bar""
class Goo : {|CS0535:IComparable|}{|CS1513:|}{|CS1514:|}
#line default
#line hidden
// stuff";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[WorkItem(545476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545476")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalDateTime1()
{
await new VerifyCS.Test
{
TestCode = @"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo([Optional][DateTimeConstant(100)] DateTime x);
}
public class C : {|CS0535:IGoo|}
{
}",
FixedCode = @"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo([Optional][DateTimeConstant(100)] DateTime x);
}
public class C : IGoo
{
public void Goo([DateTimeConstant(100), Optional] DateTime x)
{
throw new NotImplementedException();
}
}",
Options = { AllOptionsOff },
// 🐛 one value is generated with 0L instead of 0
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(545476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545476")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalDateTime2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo([Optional][DateTimeConstant(100)] DateTime x);
}
public class C : {|CS0535:IGoo|}
{
}",
@"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo([Optional][DateTimeConstant(100)] DateTime x);
}
public class C : IGoo
{
void IGoo.Goo(DateTime x)
{
throw new NotImplementedException();
}
}",
codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(545477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545477")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIUnknownIDispatchAttributes1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo1([Optional][IUnknownConstant] object x);
void Goo2([Optional][IDispatchConstant] object x);
}
public class C : {|CS0535:{|CS0535:IGoo|}|}
{
}",
@"using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo1([Optional][IUnknownConstant] object x);
void Goo2([Optional][IDispatchConstant] object x);
}
public class C : IGoo
{
public void Goo1([IUnknownConstant, Optional] object x)
{
throw new System.NotImplementedException();
}
public void Goo2([IDispatchConstant, Optional] object x)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545477")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIUnknownIDispatchAttributes2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo1([Optional][IUnknownConstant] object x);
void Goo2([Optional][IDispatchConstant] object x);
}
public class C : {|CS0535:{|CS0535:IGoo|}|}
{
}",
@"using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo1([Optional][IUnknownConstant] object x);
void Goo2([Optional][IDispatchConstant] object x);
}
public class C : IGoo
{
void IGoo.Goo1(object x)
{
throw new System.NotImplementedException();
}
void IGoo.Goo2(object x)
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(545464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545464")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestTypeNameConflict()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
void Goo();
}
public class Goo : {|CS0535:IGoo|}
{
}",
@"interface IGoo
{
void Goo();
}
public class Goo : IGoo
{
void IGoo.Goo()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStringLiteral()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo { void Goo ( string s = ""\"""" ) ; } class B : {|CS0535:IGoo|} { } ",
@"interface IGoo { void Goo ( string s = ""\"""" ) ; }
class B : IGoo
{
public void Goo(string s = ""\"""")
{
throw new System.NotImplementedException();
}
} ");
}
[WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalNullableStructParameter1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"struct b
{
}
interface d
{
void m(b? x = null, b? y = default(b?));
}
class c : {|CS0535:d|}
{
}",
@"struct b
{
}
interface d
{
void m(b? x = null, b? y = default(b?));
}
class c : d
{
public void m(b? x = null, b? y = null)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalNullableStructParameter2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"struct b
{
}
interface d
{
void m(b? x = null, b? y = default(b?));
}
class c : {|CS0535:d|}
{
}",
@"struct b
{
}
interface d
{
void m(b? x = null, b? y = default(b?));
}
class c : d
{
void d.m(b? x, b? y)
{
throw new System.NotImplementedException();
}
}", codeAction: ("True;False;False:global::d;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalNullableIntParameter()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface d
{
void m(int? x = 5, int? y = null);
}
class c : {|CS0535:d|}
{
}",
@"interface d
{
void m(int? x = 5, int? y = null);
}
class c : d
{
public void m(int? x = 5, int? y = null)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545613")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalWithNoDefaultValue()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional] I o);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional] I o);
}
class C : I
{
public void Goo([Optional] I o)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIntegralAndFloatLiterals()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
void M01(short s = short.MinValue);
void M02(short s = -1);
void M03(short s = short.MaxValue);
void M04(ushort s = ushort.MinValue);
void M05(ushort s = 1);
void M06(ushort s = ushort.MaxValue);
void M07(int s = int.MinValue);
void M08(int s = -1);
void M09(int s = int.MaxValue);
void M10(uint s = uint.MinValue);
void M11(uint s = 1);
void M12(uint s = uint.MaxValue);
void M13(long s = long.MinValue);
void M14(long s = -1);
void M15(long s = long.MaxValue);
void M16(ulong s = ulong.MinValue);
void M17(ulong s = 1);
void M18(ulong s = ulong.MaxValue);
void M19(float s = float.MinValue);
void M20(float s = 1);
void M21(float s = float.MaxValue);
void M22(double s = double.MinValue);
void M23(double s = 1);
void M24(double s = double.MaxValue);
}
class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}
{
}",
FixedCode = @"interface I
{
void M01(short s = short.MinValue);
void M02(short s = -1);
void M03(short s = short.MaxValue);
void M04(ushort s = ushort.MinValue);
void M05(ushort s = 1);
void M06(ushort s = ushort.MaxValue);
void M07(int s = int.MinValue);
void M08(int s = -1);
void M09(int s = int.MaxValue);
void M10(uint s = uint.MinValue);
void M11(uint s = 1);
void M12(uint s = uint.MaxValue);
void M13(long s = long.MinValue);
void M14(long s = -1);
void M15(long s = long.MaxValue);
void M16(ulong s = ulong.MinValue);
void M17(ulong s = 1);
void M18(ulong s = ulong.MaxValue);
void M19(float s = float.MinValue);
void M20(float s = 1);
void M21(float s = float.MaxValue);
void M22(double s = double.MinValue);
void M23(double s = 1);
void M24(double s = double.MaxValue);
}
class C : I
{
public void M01(short s = short.MinValue)
{
throw new System.NotImplementedException();
}
public void M02(short s = -1)
{
throw new System.NotImplementedException();
}
public void M03(short s = short.MaxValue)
{
throw new System.NotImplementedException();
}
public void M04(ushort s = 0)
{
throw new System.NotImplementedException();
}
public void M05(ushort s = 1)
{
throw new System.NotImplementedException();
}
public void M06(ushort s = ushort.MaxValue)
{
throw new System.NotImplementedException();
}
public void M07(int s = int.MinValue)
{
throw new System.NotImplementedException();
}
public void M08(int s = -1)
{
throw new System.NotImplementedException();
}
public void M09(int s = int.MaxValue)
{
throw new System.NotImplementedException();
}
public void M10(uint s = 0)
{
throw new System.NotImplementedException();
}
public void M11(uint s = 1)
{
throw new System.NotImplementedException();
}
public void M12(uint s = uint.MaxValue)
{
throw new System.NotImplementedException();
}
public void M13(long s = long.MinValue)
{
throw new System.NotImplementedException();
}
public void M14(long s = -1)
{
throw new System.NotImplementedException();
}
public void M15(long s = long.MaxValue)
{
throw new System.NotImplementedException();
}
public void M16(ulong s = 0)
{
throw new System.NotImplementedException();
}
public void M17(ulong s = 1)
{
throw new System.NotImplementedException();
}
public void M18(ulong s = ulong.MaxValue)
{
throw new System.NotImplementedException();
}
public void M19(float s = float.MinValue)
{
throw new System.NotImplementedException();
}
public void M20(float s = 1)
{
throw new System.NotImplementedException();
}
public void M21(float s = float.MaxValue)
{
throw new System.NotImplementedException();
}
public void M22(double s = double.MinValue)
{
throw new System.NotImplementedException();
}
public void M23(double s = 1)
{
throw new System.NotImplementedException();
}
public void M24(double s = double.MaxValue)
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
// 🐛 one value is generated with 0U instead of 0
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEnumLiterals()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
enum E
{
A = 1,
B = 2
}
[FlagsAttribute]
enum FlagE
{
A = 1,
B = 2
}
interface I
{
void M1(E e = E.A | E.B);
void M2(FlagE e = FlagE.A | FlagE.B);
}
class C : {|CS0535:{|CS0535:I|}|}
{
}",
@"using System;
enum E
{
A = 1,
B = 2
}
[FlagsAttribute]
enum FlagE
{
A = 1,
B = 2
}
interface I
{
void M1(E e = E.A | E.B);
void M2(FlagE e = FlagE.A | FlagE.B);
}
class C : I
{
public void M1(E e = (E)3)
{
throw new NotImplementedException();
}
public void M2(FlagE e = FlagE.A | FlagE.B)
{
throw new NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCharLiterals()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void M01(char c = '\0');
void M02(char c = '\r');
void M03(char c = '\n');
void M04(char c = '\t');
void M05(char c = '\b');
void M06(char c = '\v');
void M07(char c = '\'');
void M08(char c = '“');
void M09(char c = 'a');
void M10(char c = '""');
void M11(char c = '\u2029');
}
class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|}|}|}|}|}|}|}|}
{
}",
@"using System;
interface I
{
void M01(char c = '\0');
void M02(char c = '\r');
void M03(char c = '\n');
void M04(char c = '\t');
void M05(char c = '\b');
void M06(char c = '\v');
void M07(char c = '\'');
void M08(char c = '“');
void M09(char c = 'a');
void M10(char c = '""');
void M11(char c = '\u2029');
}
class C : I
{
public void M01(char c = '\0')
{
throw new NotImplementedException();
}
public void M02(char c = '\r')
{
throw new NotImplementedException();
}
public void M03(char c = '\n')
{
throw new NotImplementedException();
}
public void M04(char c = '\t')
{
throw new NotImplementedException();
}
public void M05(char c = '\b')
{
throw new NotImplementedException();
}
public void M06(char c = '\v')
{
throw new NotImplementedException();
}
public void M07(char c = '\'')
{
throw new NotImplementedException();
}
public void M08(char c = '“')
{
throw new NotImplementedException();
}
public void M09(char c = 'a')
{
throw new NotImplementedException();
}
public void M10(char c = '""')
{
throw new NotImplementedException();
}
public void M11(char c = '\u2029')
{
throw new NotImplementedException();
}
}");
}
[WorkItem(545695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545695")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRemoveParenthesesAroundTypeReference1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void Goo(DayOfWeek x = DayOfWeek.Friday);
}
class C : {|CS0535:I|}
{
DayOfWeek DayOfWeek { get; set; }
}",
@"using System;
interface I
{
void Goo(DayOfWeek x = DayOfWeek.Friday);
}
class C : I
{
DayOfWeek DayOfWeek { get; set; }
public void Goo(DayOfWeek x = DayOfWeek.Friday)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(545696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545696")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDecimalConstants1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo(decimal x = decimal.MaxValue);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void Goo(decimal x = decimal.MaxValue);
}
class C : I
{
public void Goo(decimal x = decimal.MaxValue)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545711")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNullablePrimitiveLiteral()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo(decimal? x = decimal.MaxValue);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void Goo(decimal? x = decimal.MaxValue);
}
class C : I
{
public void Goo(decimal? x = decimal.MaxValue)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545715")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNullableEnumType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void Goo(DayOfWeek? x = DayOfWeek.Friday);
}
class C : {|CS0535:I|}
{
}",
@"using System;
interface I
{
void Goo(DayOfWeek? x = DayOfWeek.Friday);
}
class C : I
{
public void Goo(DayOfWeek? x = DayOfWeek.Friday)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(545752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545752")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestByteLiterals()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo(byte x = 1);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void Goo(byte x = 1);
}
class C : I
{
public void Goo(byte x = 1)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545736")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCastedOptionalParameter1()
{
const string code = @"
using System;
interface I
{
void Goo(ConsoleColor x = (ConsoleColor)(-1));
}
class C : {|CS0535:I|}
{
}";
const string expected = @"
using System;
interface I
{
void Goo(ConsoleColor x = (ConsoleColor)(-1));
}
class C : I
{
public void Goo(ConsoleColor x = (ConsoleColor)(-1))
{
throw new NotImplementedException();
}
}";
await TestWithAllCodeStyleOptionsOffAsync(code, expected);
}
[WorkItem(545737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545737")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCastedEnumValue()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue);
}
class C : {|CS0535:I|}
{
}",
@"using System;
interface I
{
void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue);
}
class C : I
{
public void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(545785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545785")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoCastFromZeroToEnum()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"enum E
{
A = 1,
}
interface I
{
void Goo(E x = 0);
}
class C : {|CS0535:I|}
{
}",
@"enum E
{
A = 1,
}
interface I
{
void Goo(E x = 0);
}
class C : I
{
public void Goo(E x = 0)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545793")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMultiDimArray()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional][DefaultParameterValue(1)] int x, int[,] y);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional][DefaultParameterValue(1)] int x, int[,] y);
}
class C : I
{
public void Goo([{|CS1745:DefaultParameterValue|}(1), {|CS1745:Optional|}] int x = {|CS8017:1|}, int[,] y = null)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545794")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestParametersAfterOptionalParameter()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional, DefaultParameterValue(1)] int x, int[] y, int[] z);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional, DefaultParameterValue(1)] int x, int[] y, int[] z);
}
class C : I
{
public void Goo([{|CS1745:DefaultParameterValue|}(1), {|CS1745:Optional|}] int x = {|CS8017:1|}, int[] y = null, int[] z = null)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545605")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestAttributeInParameter()
{
var test = new VerifyCS.Test
{
TestCode =
@"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface I
{
void Goo([Optional][DateTimeConstant(100)] DateTime d1, [Optional][IUnknownConstant] object d2);
}
class C : {|CS0535:I|}
{
}
",
FixedCode =
@"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface I
{
void Goo([Optional][DateTimeConstant(100)] DateTime d1, [Optional][IUnknownConstant] object d2);
}
class C : I
{
public void Goo([DateTimeConstant(100), Optional] DateTime d1, [IUnknownConstant, Optional] object d2)
{
throw new NotImplementedException();
}
}
",
// 🐛 the DateTimeConstant attribute is generated with 100L instead of 100
CodeActionValidationMode = CodeActionValidationMode.None,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[WorkItem(545897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545897")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNameConflictBetweenMethodAndTypeParameter()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<S>
{
void T1<T>(S x, T y);
}
class C<T> : {|CS0535:I<T>|}
{
}",
@"interface I<S>
{
void T1<T>(S x, T y);
}
class C<T> : I<T>
{
public void T1<T2>(T x, T2 y)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545895")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestTypeParameterReplacementWithOuterType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections.Generic;
interface I<S>
{
void Goo<T>(S y, List<T>.Enumerator x);
}
class D<T> : {|CS0535:I<T>|}
{
}",
@"using System.Collections.Generic;
interface I<S>
{
void Goo<T>(S y, List<T>.Enumerator x);
}
class D<T> : I<T>
{
public void Goo<T1>(T y, List<T1>.Enumerator x)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545864")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestFloatConstant()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo(float x = 1E10F);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void Goo(float x = 1E10F);
}
class C : I
{
public void Goo(float x = 1E+10F)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(544640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544640")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestKeywordForTypeParameterName()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo<@class>();
}
class C : {|CS0535:I|}{|CS1513:|}{|CS1514:|}",
@"interface I
{
void Goo<@class>();
}
class C : I
{
public void Goo<@class>()
{
throw new System.NotImplementedException();
}
}
");
}
[WorkItem(545922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545922")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExtremeDecimals()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo1(decimal x = 1E28M);
void Goo2(decimal x = -1E28M);
}
class C : {|CS0535:{|CS0535:I|}|}
{
}",
@"interface I
{
void Goo1(decimal x = 1E28M);
void Goo2(decimal x = -1E28M);
}
class C : I
{
public void Goo1(decimal x = 10000000000000000000000000000M)
{
throw new System.NotImplementedException();
}
public void Goo2(decimal x = -10000000000000000000000000000M)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(544659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544659")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonZeroScaleDecimals()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo(decimal x = 0.1M);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void Goo(decimal x = 0.1M);
}
class C : I
{
public void Goo(decimal x = 0.1M)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(544639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544639")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnterminatedComment()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
// Implement interface
class C : {|CS0535:IServiceProvider|} {|CS1035:|}/*
{|CS1513:|}{|CS1514:|}",
@"using System;
// Implement interface
class C : IServiceProvider /*
*/
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(529920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529920")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNewLineBeforeDirective()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
// Implement interface
class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|}
#pragma warning disable
",
@"using System;
// Implement interface
class C : IServiceProvider
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
#pragma warning disable
");
}
[WorkItem(529947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529947")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCommentAfterInterfaceList1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|} // Implement interface
",
@"using System;
class C : IServiceProvider // Implement interface
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(529947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529947")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCommentAfterInterfaceList2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|}
// Implement interface
",
@"using System;
class C : IServiceProvider
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
// Implement interface
");
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposable_NoDisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0));
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposable_DisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
$@"using System;
class C : IDisposable
{{
private bool disposedValue;
{DisposePattern("protected virtual ", "C", "public void ")}
}}
", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1));
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableExplicitly_NoDisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IDisposable
{
void IDisposable.Dispose()
{
throw new NotImplementedException();
}
}
", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2));
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableExplicitly_DisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:System.IDisposable|}
{
class IDisposable
{
}
}",
$@"using System;
class C : System.IDisposable
{{
private bool disposedValue;
class IDisposable
{{
}}
{DisposePattern("protected virtual ", "C", "void System.IDisposable.")}
}}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3));
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableAbstractly_NoDisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
abstract class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
@"using System;
abstract class C : IDisposable
{
public abstract void Dispose();
}
", codeAction: ("False;True;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2));
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableThroughMember_NoDisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IDisposable|}
{
private IDisposable goo;
}",
@"using System;
class C : IDisposable
{
private IDisposable goo;
public void Dispose()
{
goo.Dispose();
}
}", codeAction: ("False;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 2));
}
[WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableExplicitly_NoNamespaceImportForSystem()
{
await new VerifyCS.Test
{
TestCode = @"class C : {|CS0535:System.IDisposable|}{|CS1513:|}{|CS1514:|}",
FixedCode = $@"class C : System.IDisposable
{{
private bool disposedValue;
{DisposePattern("protected virtual ", "C", "void System.IDisposable.", gcPrefix: "System.")}
}}
",
CodeActionEquivalenceKey = "True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;",
CodeActionIndex = 3,
// 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableViaBaseInterface_NoDisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I : IDisposable
{
void F();
}
class C : {|CS0535:{|CS0535:I|}|}
{
}",
@"using System;
interface I : IDisposable
{
void F();
}
class C : I
{
public void Dispose()
{
throw new NotImplementedException();
}
public void F()
{
throw new NotImplementedException();
}
}", codeAction: ("False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0));
}
[WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableViaBaseInterface()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I : IDisposable
{
void F();
}
class C : {|CS0535:{|CS0535:I|}|}
{
}",
$@"using System;
interface I : IDisposable
{{
void F();
}}
class C : I
{{
private bool disposedValue;
public void F()
{{
throw new NotImplementedException();
}}
{DisposePattern("protected virtual ", "C", "public void ")}
}}", codeAction: ("False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1));
}
[WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableExplicitlyViaBaseInterface()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I : IDisposable
{
void F();
}
class C : {|CS0535:{|CS0535:I|}|}
{
}",
$@"using System;
interface I : IDisposable
{{
void F();
}}
class C : I
{{
private bool disposedValue;
void I.F()
{{
throw new NotImplementedException();
}}
{DisposePattern("protected virtual ", "C", "void IDisposable.")}
}}", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3));
}
[WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDontImplementDisposePatternForLocallyDefinedIDisposable()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"namespace System
{
interface IDisposable
{
void Dispose();
}
class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}
}",
@"namespace System
{
interface IDisposable
{
void Dispose();
}
class C : IDisposable
{
void IDisposable.Dispose()
{
throw new NotImplementedException();
}
}
}", codeAction: ("True;False;False:global::System.IDisposable;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDontImplementDisposePatternForStructures1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
struct S : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
@"using System;
struct S : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDontImplementDisposePatternForStructures2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
struct S : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
@"using System;
struct S : IDisposable
{
void IDisposable.Dispose()
{
throw new NotImplementedException();
}
}
", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(545924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545924")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEnumNestedInGeneric()
{
var test = new VerifyCS.Test()
{
TestCode = @"class C<T>
{
public enum E
{
X
}
}
interface I
{
void Goo<T>(C<T>.E x = C<T>.E.X);
}
class D : {|CS0535:I|}
{
}",
FixedCode = @"class C<T>
{
public enum E
{
X
}
}
interface I
{
void Goo<T>(C<T>.E x = C<T>.E.X);
}
class D : I
{
public void Goo<T>(C<T>.E x = C<T>.E.X)
{
throw new System.NotImplementedException();
}
}",
// 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected
CodeActionValidationMode = CodeActionValidationMode.None,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnterminatedString1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|} {|CS1039:|}@""{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IServiceProvider {|CS1003:@""""|}{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnterminatedString2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|} {|CS1010:|}""{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IServiceProvider {|CS1003:""""|}{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnterminatedString3()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|} {|CS1039:|}@""{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IServiceProvider {|CS1003:@""""|}{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnterminatedString4()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|} {|CS1010:|}""{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IServiceProvider {|CS1003:""""|}{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(545940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545940")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDecimalENotation()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo1(decimal x = 1E-25M);
void Goo2(decimal x = -1E-25M);
void Goo3(decimal x = 1E-24M);
void Goo4(decimal x = -1E-24M);
}
class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|}
{
}",
@"interface I
{
void Goo1(decimal x = 1E-25M);
void Goo2(decimal x = -1E-25M);
void Goo3(decimal x = 1E-24M);
void Goo4(decimal x = -1E-24M);
}
class C : I
{
public void Goo1(decimal x = 0.0000000000000000000000001M)
{
throw new System.NotImplementedException();
}
public void Goo2(decimal x = -0.0000000000000000000000001M)
{
throw new System.NotImplementedException();
}
public void Goo3(decimal x = 0.000000000000000000000001M)
{
throw new System.NotImplementedException();
}
public void Goo4(decimal x = -0.000000000000000000000001M)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545938")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestGenericEnumWithRenamedTypeParameters()
{
var test = new VerifyCS.Test
{
TestCode = @"class C<T>
{
public enum E
{
X
}
}
interface I<S>
{
void Goo<T>(S y, C<T>.E x = C<T>.E.X);
}
class D<T> : {|CS0535:I<T>|}
{
}",
FixedCode = @"class C<T>
{
public enum E
{
X
}
}
interface I<S>
{
void Goo<T>(S y, C<T>.E x = C<T>.E.X);
}
class D<T> : I<T>
{
public void Goo<T1>(T y, C<T1>.E x = C<T1>.E.X)
{
throw new System.NotImplementedException();
}
}",
// 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected
CodeActionValidationMode = CodeActionValidationMode.None,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[WorkItem(545919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545919")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDoNotRenameTypeParameterToParameterName()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<S>
{
void Goo<T>(S T1);
}
class C<T> : {|CS0535:I<T>|}
{
}",
@"interface I<S>
{
void Goo<T>(S T1);
}
class C<T> : I<T>
{
public void Goo<T2>(T T1)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(530265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530265")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestAttributes()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.U1)]
bool Goo([MarshalAs(UnmanagedType.U1)] bool x);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.U1)]
bool Goo([MarshalAs(UnmanagedType.U1)] bool x);
}
class C : I
{
[return: MarshalAs(UnmanagedType.U1)]
public bool Goo([MarshalAs(UnmanagedType.U1)] bool x)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(530265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530265")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestAttributesExplicit()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.U1)]
bool Goo([MarshalAs(UnmanagedType.U1)] bool x);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.U1)]
bool Goo([MarshalAs(UnmanagedType.U1)] bool x);
}
class C : I
{
bool I.Goo(bool x)
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(546443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546443")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestParameterNameWithTypeName()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface IGoo
{
void Bar(DateTime DateTime);
}
class C : {|CS0535:IGoo|}
{
}",
@"using System;
interface IGoo
{
void Bar(DateTime DateTime);
}
class C : IGoo
{
public void Bar(DateTime DateTime)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(530521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530521")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnboundGeneric()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections.Generic;
using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))]
void Goo();
}
class C : {|CS0535:I|}
{
}",
@"using System.Collections.Generic;
using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))]
void Goo();
}
class C : I
{
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))]
public void Goo()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(752436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752436")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestQualifiedNameImplicitInterface()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"namespace N
{
public interface I
{
void M();
}
}
class C : {|CS0535:N.I|}
{
}",
@"namespace N
{
public interface I
{
void M();
}
}
class C : N.I
{
public void M()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(752436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752436")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestQualifiedNameExplicitInterface()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"namespace N
{
public interface I
{
void M();
}
}
class C : {|CS0535:N.I|}
{
}",
@"using N;
namespace N
{
public interface I
{
void M();
}
}
class C : N.I
{
void I.M()
{
throw new System.NotImplementedException();
}
}", codeAction: ("True;False;False:global::N.I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForPartialType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface I
{
void Goo();
}
partial class C
{
}
partial class C : {|CS0535:I|}
{
}",
@"public interface I
{
void Goo();
}
partial class C
{
}
partial class C : I
{
void I.Goo()
{
throw new System.NotImplementedException();
}
}", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForPartialType2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface I
{
void Goo();
}
partial class C : {|CS0535:I|}
{
}
partial class C
{
}",
@"public interface I
{
void Goo();
}
partial class C : I
{
void I.Goo()
{
throw new System.NotImplementedException();
}
}
partial class C
{
}", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForPartialType3()
{
await new VerifyCS.Test
{
TestCode = @"public interface I
{
void Goo();
}
public interface I2
{
void Goo2();
}
partial class C : {|CS0535:I|}
{
}
partial class C : {|CS0535:I2|}
{
}",
FixedState =
{
Sources =
{
@"public interface I
{
void Goo();
}
public interface I2
{
void Goo2();
}
partial class C : I
{
void I.Goo()
{
throw new System.NotImplementedException();
}
}
partial class C : {|CS0535:I2|}
{
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(752447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752447")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExplicitImplOfIndexedProperty()
{
var test = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class Test : {|CS0535:{|CS0535:IGoo|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1", LanguageNames.VisualBasic] =
{
Sources =
{
@"
Public Interface IGoo
Property IndexProp(ByVal p1 As Integer) As String
End Interface",
},
},
},
AdditionalProjectReferences =
{
"Assembly1",
},
},
FixedState =
{
Sources =
{
@"
public class Test : IGoo
{
string IGoo.get_IndexProp(int p1)
{
throw new System.NotImplementedException();
}
void IGoo.set_IndexProp(int p1, string Value)
{
throw new System.NotImplementedException();
}
}",
},
},
CodeActionEquivalenceKey = "True;False;False:global::IGoo;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[WorkItem(602475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602475")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplicitImplOfIndexedProperty()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"using System;
class C : {|CS0535:{|CS0535:I|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1", LanguageNames.VisualBasic] =
{
Sources =
{
@"Public Interface I
Property P(x As Integer)
End Interface",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"using System;
class C : I
{
public object get_P(int x)
{
throw new NotImplementedException();
}
public void set_P(int x, object Value)
{
throw new NotImplementedException();
}
}",
},
},
CodeActionEquivalenceKey = "False;False;True:global::I;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementationOfIndexerWithInaccessibleAttributes()
{
var test = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
using System;
class C : {|CS0535:I|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"
using System;
internal class ShouldBeRemovedAttribute : Attribute { }
public interface I
{
string this[[ShouldBeRemovedAttribute] int i] { get; set; }
}"
},
},
},
AdditionalProjectReferences =
{
"Assembly1",
},
},
FixedState =
{
Sources =
{
@"
using System;
class C : I
{
public string this[int i]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}",
},
},
CodeActionEquivalenceKey = "False;False;True:global::I;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
#if false
[WorkItem(13677)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoGenerateInVenusCase2()
{
await TestMissingAsync(
@"using System;
#line 1 ""Bar""
class Goo : [|IComparable|]
#line default
#line hidden");
}
#endif
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForImplicitIDisposable()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class Program : {|CS0535:IDisposable|}
{
}",
$@"using System;
class Program : IDisposable
{{
private bool disposedValue;
{DisposePattern("protected virtual ", "Program", "public void ")}
}}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForExplicitIDisposable()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class Program : {|CS0535:IDisposable|}
{
private bool DisposedValue;
}",
$@"using System;
class Program : IDisposable
{{
private bool DisposedValue;
private bool disposedValue;
{DisposePattern("protected virtual ", "Program", "void IDisposable.")}
}}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForIDisposableNonApplicable1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class Program : {|CS0535:IDisposable|}
{
private bool disposedValue;
}",
@"using System;
class Program : IDisposable
{
private bool disposedValue;
public void Dispose()
{
throw new NotImplementedException();
}
}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForIDisposableNonApplicable2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class Program : {|CS0535:IDisposable|}
{
public void Dispose(bool flag)
{
}
}",
@"using System;
class Program : IDisposable
{
public void Dispose(bool flag)
{
}
public void Dispose()
{
throw new NotImplementedException();
}
}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForExplicitIDisposableWithSealedClass()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
sealed class Program : {|CS0535:IDisposable|}
{
}",
$@"using System;
sealed class Program : IDisposable
{{
private bool disposedValue;
{DisposePattern("private ", "Program", "void IDisposable.")}
}}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3));
}
[WorkItem(9760, "https://github.com/dotnet/roslyn/issues/9760")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForExplicitIDisposableWithExistingField()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class Program : {|CS0535:IDisposable|}
{
private bool disposedValue;
}",
$@"using System;
class Program : IDisposable
{{
private bool disposedValue;
private bool disposedValue1;
{DisposePattern("protected virtual ", "Program", "public void ", disposeField: "disposedValue1")}
}}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1));
}
[WorkItem(9760, "https://github.com/dotnet/roslyn/issues/9760")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceUnderscoreNameForFields()
{
await new VerifyCS.Test
{
TestCode = @"using System;
class Program : {|CS0535:IDisposable|}
{
}",
FixedCode = $@"using System;
class Program : IDisposable
{{
private bool _disposedValue;
{DisposePattern("protected virtual ", "Program", "public void ", disposeField: "_disposedValue")}
}}",
Options =
{
_options.FieldNamesAreCamelCaseWithUnderscorePrefix,
},
CodeActionEquivalenceKey = "False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoComAliasNameAttributeOnMethodParameters()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void M([System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void M([System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p);
}
class C : I
{
public void M(int p)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoComAliasNameAttributeOnMethodReturnType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
[return: ComAliasName(""pAlias1"")]
long M([ComAliasName(""pAlias2"")] int p);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
[return: ComAliasName(""pAlias1"")]
long M([ComAliasName(""pAlias2"")] int p);
}
class C : I
{
public long M(int p)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoComAliasNameAttributeOnIndexerParameters()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
long this[[System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p] { get; }
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
long this[[System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p] { get; }
}
class C : I
{
public long this[int p]
{
get
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMissingOpenBrace()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"namespace Scenarios
{
public interface TestInterface
{
void M1();
}
struct TestStruct1 : {|CS0535:TestInterface|}{|CS1513:|}{|CS1514:|}
// Comment
}",
@"namespace Scenarios
{
public interface TestInterface
{
void M1();
}
struct TestStruct1 : TestInterface
{
public void M1()
{
throw new System.NotImplementedException();
}
}
// Comment
}");
}
[WorkItem(994328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced1()
{
//CSharpFeaturesResources.DisposePattern
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T
{
System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c);
System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT;
}
partial class C
{
}
partial class C : {|CS0535:{|CS0535:{|CS0535:I<System.Exception, System.AggregateException>|}|}|}, {|CS0535:System.IDisposable|}
{
}",
$@"using System;
using System.Collections.Generic;
interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T
{{
System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c);
System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT;
}}
partial class C
{{
}}
partial class C : I<System.Exception, System.AggregateException>, System.IDisposable
{{
private bool disposedValue;
public bool Equals(int other)
{{
throw new NotImplementedException();
}}
public List<AggregateException> M(Dictionary<Exception, List<AggregateException>> a, Exception b, AggregateException c)
{{
throw new NotImplementedException();
}}
public List<UU> M<TT, UU>(Dictionary<TT, List<UU>> a, TT b, UU c) where UU : TT
{{
throw new NotImplementedException();
}}
{DisposePattern("protected virtual ", "C", "public void ")}
}}", codeAction: ("False;False;True:global::I<global::System.Exception, global::System.AggregateException>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1));
}
[WorkItem(994328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T
{
System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c);
System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT;
}
partial class C : {|CS0535:{|CS0535:{|CS0535:I<System.Exception, System.AggregateException>|}|}|}, {|CS0535:System.IDisposable|}
{
}
partial class C
{
}",
$@"using System;
using System.Collections.Generic;
interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T
{{
System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c);
System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT;
}}
partial class C : I<System.Exception, System.AggregateException>, System.IDisposable
{{
private bool disposedValue;
bool IEquatable<int>.Equals(int other)
{{
throw new NotImplementedException();
}}
List<AggregateException> I<Exception, AggregateException>.M(Dictionary<Exception, List<AggregateException>> a, Exception b, AggregateException c)
{{
throw new NotImplementedException();
}}
List<UU> I<Exception, AggregateException>.M<TT, UU>(Dictionary<TT, List<UU>> a, TT b, UU c)
{{
throw new NotImplementedException();
}}
{DisposePattern("protected virtual ", "C", "void IDisposable.")}
}}
partial class C
{{
}}", codeAction: ("True;False;False:global::I<global::System.Exception, global::System.AggregateException>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3));
}
private static string DisposePattern(
string disposeVisibility,
string className,
string implementationVisibility,
string disposeField = "disposedValue",
string gcPrefix = "")
{
return $@" {disposeVisibility}void Dispose(bool disposing)
{{
if (!{disposeField})
{{
if (disposing)
{{
// {FeaturesResources.TODO_colon_dispose_managed_state_managed_objects}
}}
// {FeaturesResources.TODO_colon_free_unmanaged_resources_unmanaged_objects_and_override_finalizer}
// {FeaturesResources.TODO_colon_set_large_fields_to_null}
{disposeField} = true;
}}
}}
// // {string.Format(FeaturesResources.TODO_colon_override_finalizer_only_if_0_has_code_to_free_unmanaged_resources, "Dispose(bool disposing)")}
// ~{className}()
// {{
// // {string.Format(FeaturesResources.Do_not_change_this_code_Put_cleanup_code_in_0_method, "Dispose(bool disposing)")}
// Dispose(disposing: false);
// }}
{implementationVisibility}Dispose()
{{
// {string.Format(FeaturesResources.Do_not_change_this_code_Put_cleanup_code_in_0_method, "Dispose(bool disposing)")}
Dispose(disposing: true);
{gcPrefix}GC.SuppressFinalize(this);
}}";
}
[WorkItem(1132014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1132014")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleAttributes()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
public class Goo : {|CS0535:Holder.SomeInterface|}
{
}
public class Holder
{
public interface SomeInterface
{
void Something([SomeAttribute] string helloWorld);
}
private class SomeAttribute : Attribute
{
}
}",
@"using System;
public class Goo : Holder.SomeInterface
{
public void Something(string helloWorld)
{
throw new NotImplementedException();
}
}
public class Holder
{
public interface SomeInterface
{
void Something([SomeAttribute] string helloWorld);
}
private class SomeAttribute : Attribute
{
}
}");
}
[WorkItem(2785, "https://github.com/dotnet/roslyn/issues/2785")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughStaticMemberInGenericClass()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Issue2785<T> : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:IList<object>|}|}|}|}|}|}|}|}|}|}|}|}|}
{
private static List<object> innerList = new List<object>();
}",
@"using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Issue2785<T> : IList<object>
{
private static List<object> innerList = new List<object>();
public object this[int index]
{
get
{
return ((IList<object>)innerList)[index];
}
set
{
((IList<object>)innerList)[index] = value;
}
}
public int Count
{
get
{
return ((ICollection<object>)innerList).Count;
}
}
public bool IsReadOnly
{
get
{
return ((ICollection<object>)innerList).IsReadOnly;
}
}
public void Add(object item)
{
((ICollection<object>)innerList).Add(item);
}
public void Clear()
{
((ICollection<object>)innerList).Clear();
}
public bool Contains(object item)
{
return ((ICollection<object>)innerList).Contains(item);
}
public void CopyTo(object[] array, int arrayIndex)
{
((ICollection<object>)innerList).CopyTo(array, arrayIndex);
}
public IEnumerator<object> GetEnumerator()
{
return ((IEnumerable<object>)innerList).GetEnumerator();
}
public int IndexOf(object item)
{
return ((IList<object>)innerList).IndexOf(item);
}
public void Insert(int index, object item)
{
((IList<object>)innerList).Insert(index, item);
}
public bool Remove(object item)
{
return ((ICollection<object>)innerList).Remove(item);
}
public void RemoveAt(int index)
{
((IList<object>)innerList).RemoveAt(index);
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)innerList).GetEnumerator();
}
}",
codeAction: ("False;False;False:global::System.Collections.Generic.IList<object>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;innerList", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)]
public async Task LongTuple()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
(int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y);
}
class Class : {|CS0535:IInterface|}
{
(int, string) x;
}",
@"interface IInterface
{
(int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y);
}
class Class : IInterface
{
(int, string) x;
public (int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task LongTupleWithNames()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
(int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y);
}
class Class : {|CS0535:IInterface|}
{
(int, string) x;
}",
@"interface IInterface
{
(int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y);
}
class Class : IInterface
{
(int, string) x;
public (int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task GenericWithTuple()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface<TA, TB>
{
(TA, TB) Method1((TA, TB) y);
}
class Class : {|CS0535:IInterface<(int, string), int>|}
{
(int, string) x;
}",
@"interface IInterface<TA, TB>
{
(TA, TB) Method1((TA, TB) y);
}
class Class : IInterface<(int, string), int>
{
(int, string) x;
public ((int, string), int) Method1(((int, string), int) y)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task GenericWithTupleWithNamess()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface<TA, TB>
{
(TA a, TB b) Method1((TA a, TB b) y);
}
class Class : {|CS0535:IInterface<(int, string), int>|}
{
(int, string) x;
}",
@"interface IInterface<TA, TB>
{
(TA a, TB b) Method1((TA a, TB b) y);
}
class Class : IInterface<(int, string), int>
{
(int, string) x;
public ((int, string) a, int b) Method1(((int, string) a, int b) y)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithGroupingOff1()
{
await new VerifyCS.Test
{
TestCode = @"interface IInterface
{
int Prop { get; }
}
class Class : {|CS0535:IInterface|}
{
void M() { }
}",
FixedCode = @"interface IInterface
{
int Prop { get; }
}
class Class : IInterface
{
void M() { }
public int Prop => throw new System.NotImplementedException();
}",
Options =
{
{ ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd },
},
}.RunAsync();
}
[WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDoNotReorderComImportMembers_01()
{
await TestInRegularAndScriptAsync(
@"
using System.Runtime.InteropServices;
[ComImport]
[Guid(""00000000-0000-0000-0000-000000000000"")]
interface IComInterface
{
void MOverload();
void X();
void MOverload(int i);
int Prop { get; }
}
class Class : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IComInterface|}|}|}|}
{
}",
@"
using System.Runtime.InteropServices;
[ComImport]
[Guid(""00000000-0000-0000-0000-000000000000"")]
interface IComInterface
{
void MOverload();
void X();
void MOverload(int i);
int Prop { get; }
}
class Class : IComInterface
{
public void MOverload()
{
throw new System.NotImplementedException();
}
public void X()
{
throw new System.NotImplementedException();
}
public void MOverload(int i)
{
throw new System.NotImplementedException();
}
public int Prop => throw new System.NotImplementedException();
}");
}
[WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDoNotReorderComImportMembers_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode =
@"
using System.Runtime.InteropServices;
[ComImport]
[Guid(""00000000-0000-0000-0000-000000000000"")]
interface IComInterface
{
void MOverload() { }
void X() { }
void MOverload(int i) { }
int Prop { get; }
}
class Class : {|CS0535:IComInterface|}
{
}",
FixedCode =
@"
using System.Runtime.InteropServices;
[ComImport]
[Guid(""00000000-0000-0000-0000-000000000000"")]
interface IComInterface
{
void MOverload() { }
void X() { }
void MOverload(int i) { }
int Prop { get; }
}
class Class : IComInterface
{
public int Prop => throw new System.NotImplementedException();
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRefReturns()
{
await TestInRegularAndScriptAsync(
@"
using System;
interface I {
ref int IGoo();
ref int Goo { get; }
ref int this[int i] { get; }
}
class C : {|CS0535:{|CS0535:{|CS0535:I|}|}|}
{
}",
@"
using System;
interface I {
ref int IGoo();
ref int Goo { get; }
ref int this[int i] { get; }
}
class C : I
{
public ref int this[int i] => throw new NotImplementedException();
public ref int Goo => throw new NotImplementedException();
public ref int IGoo()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(13932, "https://github.com/dotnet/roslyn/issues/13932")]
[WorkItem(5898, "https://github.com/dotnet/roslyn/issues/5898")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestAutoProperties()
{
await new VerifyCS.Test()
{
TestCode = @"interface IInterface
{
int ReadOnlyProp { get; }
int ReadWriteProp { get; set; }
int WriteOnlyProp { set; }
}
class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
FixedCode = @"interface IInterface
{
int ReadOnlyProp { get; }
int ReadWriteProp { get; set; }
int WriteOnlyProp { set; }
}
class Class : IInterface
{
public int ReadOnlyProp { get; }
public int ReadWriteProp { get; set; }
public int WriteOnlyProp { set => throw new System.NotImplementedException(); }
}",
Options =
{
{ ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties },
},
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalParameterWithDefaultLiteral()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp7_1,
TestCode = @"
using System.Threading;
interface IInterface
{
void Method1(CancellationToken cancellationToken = default(CancellationToken));
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"
using System.Threading;
interface IInterface
{
void Method1(CancellationToken cancellationToken = default(CancellationToken));
}
class Class : IInterface
{
public void Method1(CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInWithMethod_Parameters()
{
await TestInRegularAndScriptAsync(
@"interface ITest
{
void Method(in int p);
}
public class Test : {|CS0535:ITest|}
{
}",
@"interface ITest
{
void Method(in int p);
}
public class Test : ITest
{
public void Method(in int p)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRefReadOnlyWithMethod_ReturnType()
{
await TestInRegularAndScriptAsync(
@"interface ITest
{
ref readonly int Method();
}
public class Test : {|CS0535:ITest|}
{
}",
@"interface ITest
{
ref readonly int Method();
}
public class Test : ITest
{
public ref readonly int Method()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRefReadOnlyWithProperty()
{
await TestInRegularAndScriptAsync(
@"interface ITest
{
ref readonly int Property { get; }
}
public class Test : {|CS0535:ITest|}
{
}",
@"interface ITest
{
ref readonly int Property { get; }
}
public class Test : ITest
{
public ref readonly int Property => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInWithIndexer_Parameters()
{
await TestInRegularAndScriptAsync(
@"interface ITest
{
int this[in int p] { set; }
}
public class Test : {|CS0535:ITest|}
{
}",
@"interface ITest
{
int this[in int p] { set; }
}
public class Test : ITest
{
public int this[in int p] { set => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRefReadOnlyWithIndexer_ReturnType()
{
await TestInRegularAndScriptAsync(
@"interface ITest
{
ref readonly int this[int p] { get; }
}
public class Test : {|CS0535:ITest|}
{
}",
@"interface ITest
{
ref readonly int this[int p] { get; }
}
public class Test : ITest
{
public ref readonly int this[int p] => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnmanagedConstraint()
{
await TestInRegularAndScriptAsync(
@"public interface ITest
{
void M<T>() where T : unmanaged;
}
public class Test : {|CS0535:ITest|}
{
}",
@"public interface ITest
{
void M<T>() where T : unmanaged;
}
public class Test : ITest
{
public void M<T>() where T : unmanaged
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestSealedMember_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestSealedMember_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
class Class : IInterface
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestSealedMember_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
abstract class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
abstract class Class : IInterface
{
public abstract void Method1();
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicMember_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
protected void M1();
protected int P1 {get;}
}
class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
void Method1();
protected void M1();
protected int P1 {get;}
}
class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;False;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicMember_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
protected void M1();
protected int P1 {get;}
}
class Class : {|CS0535:{|CS0535:IInterface|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
protected void M1();
protected int P1 {get;}
}
class Class : IInterface
{
int IInterface.P1
{
get
{
throw new System.NotImplementedException();
}
}
void IInterface.M1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
DiagnosticSelector = diagnostics => diagnostics[1],
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicMember_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
protected void M1();
protected int P1 {get;}
}
abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
void Method1();
protected void M1();
protected int P1 {get;}
}
abstract class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public abstract void Method1();
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicAccessor_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
int P1 {get; protected set;}
int P2 {protected get; set;}
}
class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
void Method1();
int P1 {get; protected set;}
int P2 {protected get; set;}
}
class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;False;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicAccessor_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
int P1 {get; protected set;}
int P2 {protected get; set;}
}
class Class : {|CS0535:{|CS0535:IInterface|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
int P1 {get; protected set;}
int P2 {protected get; set;}
}
class Class : IInterface
{
int IInterface.P1
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
int IInterface.P2
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicAccessor_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
int P1 {get; protected set;}
int P2 {protected get; set;}
}
abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
void Method1();
int P1 {get; protected set;}
int P2 {protected get; set;}
}
abstract class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public abstract void Method1();
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestPrivateAccessor_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestPrivateAccessor_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
class Class : IInterface
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestPrivateAccessor_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
abstract class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
abstract class Class : IInterface
{
public abstract void Method1();
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleMember_01()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
internal void M1();
internal int P1 {get;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
// Specify the code action by equivalence key only to avoid trying to implement the interface explicitly with a second code fix pass.
CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleMember_02()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
internal void M1();
internal int P1 {get;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:IInterface|}|}
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleMember_03()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
internal void M1();
internal int P1 {get;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"abstract class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public abstract void Method1();
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
// Specify the code action by equivalence key only to avoid trying to execute a second code fix pass with a different action
CodeActionEquivalenceKey = "False;True;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleAccessor_01()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
int P1 {get; internal set;}
int P2 {internal get; set;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
// Specify the code action by equivalence key only to avoid trying to implement the interface explicitly with a second code fix pass.
CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleAccessor_02()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
int P1 {get; internal set;}
int P2 {internal get; set;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:IInterface|}|}
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleAccessor_03()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
int P1 {get; internal set;}
int P2 {internal get; set;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"abstract class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public abstract void Method1();
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
// Specify the code action by equivalence key only to avoid trying to execute a second code fix pass with a different action
CodeActionEquivalenceKey = "False;True;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestVirtualMember_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestVirtualMember_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
class Class : IInterface
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestVirtualMember_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
abstract class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
abstract class Class : IInterface
{
public abstract void Method1();
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticMember_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticMember_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
class Class : IInterface
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticMember_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
abstract class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
abstract class Class : IInterface
{
public abstract void Method1();
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNotNullConstraint()
{
await TestInRegularAndScriptAsync(
@"public interface ITest
{
void M<T>() where T : notnull;
}
public class Test : {|CS0535:ITest|}
{
}",
@"public interface ITest
{
void M<T>() where T : notnull;
}
public class Test : ITest
{
public void M<T>() where T : notnull
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullableProperty()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
public interface ITest
{
string? P { get; }
}
public class Test : {|CS0535:ITest|}
{
}",
@"#nullable enable
public interface ITest
{
string? P { get; }
}
public class Test : ITest
{
public string? P => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullablePropertyAlreadyImplemented()
{
var code =
@"#nullable enable
public interface ITest
{
string? P { get; }
}
public class Test : ITest
{
public string? P => throw new System.NotImplementedException();
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullableMethod()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
public interface ITest
{
string? P();
}
public class Test : {|CS0535:ITest|}
{
}",
@"#nullable enable
public interface ITest
{
string? P();
}
public class Test : ITest
{
public string? P()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullableEvent()
{
// Question whether this is needed,
// see https://github.com/dotnet/roslyn/issues/36673
await TestInRegularAndScriptAsync(
@"#nullable enable
using System;
public interface ITest
{
event EventHandler? SomeEvent;
}
public class Test : {|CS0535:ITest|}
{
}",
@"#nullable enable
using System;
public interface ITest
{
event EventHandler? SomeEvent;
}
public class Test : ITest
{
public event EventHandler? SomeEvent;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullableDisabled()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
public interface ITest
{
string? P { get; }
}
#nullable disable
public class Test : {|CS0535:ITest|}
{
}",
@"#nullable enable
public interface ITest
{
string? P { get; }
}
#nullable disable
public class Test : ITest
{
public string P => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task GenericInterfaceNotNull1()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"#nullable enable
using System.Diagnostics.CodeAnalysis;
interface IFoo<T>
{
[return: NotNull]
T Bar([DisallowNull] T bar);
[return: MaybeNull]
T Baz([AllowNull] T bar);
}
class A : {|CS0535:{|CS0535:IFoo<int>|}|}
{
}",
FixedCode = @"#nullable enable
using System.Diagnostics.CodeAnalysis;
interface IFoo<T>
{
[return: NotNull]
T Bar([DisallowNull] T bar);
[return: MaybeNull]
T Baz([AllowNull] T bar);
}
class A : IFoo<int>
{
[return: NotNull]
public int Bar([DisallowNull] int bar)
{
throw new System.NotImplementedException();
}
[return: MaybeNull]
public int Baz([AllowNull] int bar)
{
throw new System.NotImplementedException();
}
}",
}.RunAsync();
}
[WorkItem(13427, "https://github.com/dotnet/roslyn/issues/13427")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDoNotAddNewWithGenericAndNonGenericMethods()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class B
{
public void M<T>() { }
}
interface I
{
void M();
}
class D : B, {|CS0535:I|}
{
}",
@"class B
{
public void M<T>() { }
}
interface I
{
void M();
}
class D : B, I
{
public void M()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task ImplementRemainingExplicitlyWhenPartiallyImplemented()
{
await TestInRegularAndScriptAsync(@"
interface I
{
void M1();
void M2();
}
class C : {|CS0535:I|}
{
public void M1(){}
}",
@"
interface I
{
void M1();
void M2();
}
class C : {|CS0535:I|}
{
public void M1(){}
void I.M2()
{
throw new System.NotImplementedException();
}
}", codeAction: ("True;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task ImplementInitOnlyProperty()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"
interface I
{
int Property { get; init; }
}
class C : {|CS0535:I|}
{
}",
FixedCode = @"
interface I
{
int Property { get; init; }
}
class C : I
{
public int Property { get => throw new System.NotImplementedException(); init => throw new System.NotImplementedException(); }
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task ImplementRemainingExplicitlyMissingWhenAllImplemented()
{
var code = @"
interface I
{
void M1();
void M2();
}
class C : I
{
public void M1(){}
public void M2(){}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task ImplementRemainingExplicitlyMissingWhenAllImplementedAreExplicit()
{
var code = @"
interface I
{
void M1();
void M2();
}
class C : {|CS0535:I|}
{
void I.M1(){}
}";
var fixedCode = @"
interface I
{
void M1();
void M2();
}
class C : I
{
public void M2()
{
throw new System.NotImplementedException();
}
void I.M1(){}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementRemainingExplicitlyNonPublicMember()
{
await TestInRegularAndScriptAsync(@"
interface I
{
void M1();
internal void M2();
}
class C : {|CS0535:I|}
{
public void M1(){}
}",
@"
interface I
{
void M1();
internal void M2();
}
class C : {|CS0535:I|}
{
public void M1(){}
void I.M2()
{
throw new System.NotImplementedException();
}
}", codeAction: ("True;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementOnRecord_WithSemiColon()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface I
{
void M1();
}
record C : {|CS0535:I|};
",
FixedCode = @"
interface I
{
void M1();
}
record C : {|CS0535:I|}
{
public void M1()
{
throw new System.NotImplementedException();
}
}
",
}.RunAsync();
}
[WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementOnRecord_WithBracesAndTrivia()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface I
{
void M1();
}
record C : {|CS0535:I|} { } // hello
",
FixedCode = @"
interface I
{
void M1();
}
record C : {|CS0535:I|}
{
public void M1()
{
throw new System.NotImplementedException();
}
} // hello
",
}.RunAsync();
}
[WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
[InlineData("record")]
[InlineData("record class")]
[InlineData("record struct")]
public async Task TestImplementOnRecord_WithSemiColonAndTrivia(string record)
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = $@"
interface I
{{
void M1();
}}
{record} C : {{|CS0535:I|}}; // hello
",
FixedCode = $@"
interface I
{{
void M1();
}}
{record} C : {{|CS0535:I|}} // hello
{{
public void M1()
{{
throw new System.NotImplementedException();
}}
}}
",
}.RunAsync();
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnconstrainedGenericInstantiatedWithValueType()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"#nullable enable
interface IGoo<T>
{
void Bar(T? x);
}
class C : {|CS0535:IGoo<int>|}
{
}
",
FixedCode = @"#nullable enable
interface IGoo<T>
{
void Bar(T? x);
}
class C : IGoo<int>
{
public void Bar(int x)
{
throw new System.NotImplementedException();
}
}
",
}.RunAsync();
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConstrainedGenericInstantiatedWithValueType()
{
await TestInRegularAndScriptAsync(@"
interface IGoo<T> where T : struct
{
void Bar(T? x);
}
class C : {|CS0535:IGoo<int>|}
{
}
",
@"
interface IGoo<T> where T : struct
{
void Bar(T? x);
}
class C : IGoo<int>
{
public void Bar(int? x)
{
throw new System.NotImplementedException();
}
}
");
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnconstrainedGenericInstantiatedWithReferenceType()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"
interface IGoo<T>
{
#nullable enable
void Bar(T? x);
#nullable restore
}
class C : {|CS0535:IGoo<string>|}
{
}
",
FixedCode = @"
interface IGoo<T>
{
#nullable enable
void Bar(T? x);
#nullable restore
}
class C : IGoo<string>
{
public void Bar(string x)
{
throw new System.NotImplementedException();
}
}
",
}.RunAsync();
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnconstrainedGenericInstantiatedWithReferenceType_NullableEnable()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"
#nullable enable
interface IGoo<T>
{
void Bar(T? x);
}
class C : {|CS0535:IGoo<string>|}
{
}
",
FixedCode = @"
#nullable enable
interface IGoo<T>
{
void Bar(T? x);
}
class C : IGoo<string>
{
public void Bar(string? x)
{
throw new System.NotImplementedException();
}
}
",
}.RunAsync();
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConstrainedGenericInstantiatedWithReferenceType()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"
#nullable enable
interface IGoo<T> where T : class
{
void Bar(T? x);
}
class C : {|CS0535:IGoo<string>|}
{
}
",
FixedCode = @"
#nullable enable
interface IGoo<T> where T : class
{
void Bar(T? x);
}
class C : IGoo<string>
{
public void Bar(string? x)
{
throw new System.NotImplementedException();
}
}
",
}.RunAsync();
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConstrainedGenericInstantiatedWithReferenceType_NullableEnable()
{
await TestInRegularAndScriptAsync(@"
#nullable enable
interface IGoo<T> where T : class
{
void Bar(T? x);
}
class C : {|CS0535:IGoo<string>|}
{
}
",
@"
#nullable enable
interface IGoo<T> where T : class
{
void Bar(T? x);
}
class C : IGoo<string>
{
public void Bar(string? x)
{
throw new System.NotImplementedException();
}
}
");
}
[WorkItem(51779, "https://github.com/dotnet/roslyn/issues/51779")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementTwoPropertiesOfCSharp5()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp5,
TestCode = @"
interface ITest
{
int Bar { get; }
int Foo { get; }
}
class Program : {|CS0535:{|CS0535:ITest|}|}
{
}
",
FixedCode = @"
interface ITest
{
int Bar { get; }
int Foo { get; }
}
class Program : ITest
{
public int Bar
{
get
{
throw new System.NotImplementedException();
}
}
public int Foo
{
get
{
throw new System.NotImplementedException();
}
}
}
",
}.RunAsync();
}
[WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceMember()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract void M1();
}
class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract void M1();
}
class C : ITest
{
public static void M1()
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title),
CodeActionEquivalenceKey = "False;False;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceMemberExplicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract void M1();
}
class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract void M1();
}
class C : ITest
{
static void ITest.M1()
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title),
CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceMember_ImplementAbstractly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract void M1();
}
abstract class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract void M1();
}
abstract class C : ITest
{
public static void M1()
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title),
CodeActionEquivalenceKey = "False;True;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceOperator_OnlyExplicitlyImplementable()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract int operator -(ITest x);
}
class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract int operator -(ITest x);
}
class C : ITest
{
static int ITest.operator -(ITest x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title),
CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceOperator_ImplementImplicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
static abstract int operator -(T x, int y);
}
class C : {|CS0535:{|CS0535:ITest<C>|}|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
static abstract int operator -(T x, int y);
}
class C : ITest<C>
{
public static int operator -(C x)
{
throw new System.NotImplementedException();
}
public static int operator -(C x, int y)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title),
CodeActionEquivalenceKey = "False;False;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceOperator_ImplementExplicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
}
class C : {|CS0535:ITest<C>|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
}
class C : ITest<C>
{
static int ITest<C>.operator -(C x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title),
CodeActionEquivalenceKey = "True;False;False:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceOperator_ImplementAbstractly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
}
abstract class C : {|CS0535:ITest<C>|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
}
abstract class C : ITest<C>
{
public static int operator -(C x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title),
CodeActionEquivalenceKey = "False;True;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterface_Explicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract int M(ITest x);
}
class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract int M(ITest x);
}
class C : ITest
{
static int ITest.M(ITest x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title),
CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterface_Implicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract int M(ITest x);
}
class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract int M(ITest x);
}
class C : ITest
{
public static int M(ITest x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title),
CodeActionEquivalenceKey = "False;False;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterface_ImplementImplicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
class C : {|CS0535:ITest<C>|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
class C : ITest<C>
{
public static int M(C x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title),
CodeActionEquivalenceKey = "False;False;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterface_ImplementExplicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
class C : {|CS0535:ITest<C>|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
class C : ITest<C>
{
static int ITest<C>.M(C x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title),
CodeActionEquivalenceKey = "True;False;False:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterface_ImplementAbstractly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
abstract class C : {|CS0535:ITest<C>|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
abstract class C : ITest<C>
{
public static int M(C x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title),
CodeActionEquivalenceKey = "False;True;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles;
using Microsoft.CodeAnalysis.ImplementType;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Roslyn.Test.Utilities;
using Xunit;
using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer,
Microsoft.CodeAnalysis.CSharp.ImplementInterface.CSharpImplementInterfaceCodeFixProvider>;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface
{
public class ImplementInterfaceTests
{
private readonly NamingStylesTestOptionSets _options = new NamingStylesTestOptionSets(LanguageNames.CSharp);
private static OptionsCollection AllOptionsOff
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
};
private static OptionsCollection AllOptionsOn
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
};
private static OptionsCollection AccessorOptionsOn
=> new OptionsCollection(LanguageNames.CSharp)
{
{ CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
{ CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement },
};
internal static async Task TestWithAllCodeStyleOptionsOffAsync(
string initialMarkup, string expectedMarkup,
(string equivalenceKey, int index)? codeAction = null)
{
await new VerifyCS.Test
{
TestCode = initialMarkup,
FixedCode = expectedMarkup,
Options = { AllOptionsOff },
CodeActionEquivalenceKey = codeAction?.equivalenceKey,
CodeActionIndex = codeAction?.index,
}.RunAsync();
}
internal static async Task TestWithAllCodeStyleOptionsOnAsync(string initialMarkup, string expectedMarkup)
{
await new VerifyCS.Test
{
TestCode = initialMarkup,
FixedCode = expectedMarkup,
Options = { AllOptionsOn },
}.RunAsync();
}
internal static async Task TestWithAccessorCodeStyleOptionsOnAsync(string initialMarkup, string expectedMarkup)
{
await new VerifyCS.Test
{
TestCode = initialMarkup,
FixedCode = expectedMarkup,
Options = { AccessorOptionsOn },
}.RunAsync();
}
private static async Task TestInRegularAndScriptAsync(
string initialMarkup,
string expectedMarkup,
(string equivalenceKey, int index)? codeAction = null)
{
await new VerifyCS.Test
{
TestCode = initialMarkup,
FixedCode = expectedMarkup,
CodeActionEquivalenceKey = codeAction?.equivalenceKey,
CodeActionIndex = codeAction?.index,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethod()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
void Method1();
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
void Method1();
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethodInRecord()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.Preview,
TestCode = @"interface IInterface
{
void Method1();
}
record Record : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
}
record Record : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
[WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")]
public async Task TestMethodWithNativeIntegers()
{
var nativeIntegerAttributeDefinition = @"
namespace System.Runtime.CompilerServices
{
[System.AttributeUsage(AttributeTargets.All)]
public sealed class NativeIntegerAttribute : System.Attribute
{
public NativeIntegerAttribute()
{
}
public NativeIntegerAttribute(bool[] flags)
{
}
}
}";
// Note: we're putting the attribute by hand to simulate metadata
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"interface IInterface
{
[return: {|CS8335:System.Runtime.CompilerServices.NativeInteger(new[] { true, true })|}]
(nint, nuint) Method(nint x, nuint x2);
}
class Class : {|CS0535:IInterface|}
{
}" + nativeIntegerAttributeDefinition,
FixedCode = @"interface IInterface
{
[return: {|CS8335:System.Runtime.CompilerServices.NativeInteger(new[] { true, true })|}]
(nint, nuint) Method(nint x, nuint x2);
}
class Class : IInterface
{
public (nint, nuint) Method(nint x, nuint x2)
{
throw new System.NotImplementedException();
}
}" + nativeIntegerAttributeDefinition,
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethodWithTuple()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
(int, int) Method((string, string) x);
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
(int, int) Method((string, string) x);
}
class Class : IInterface
{
public (int, int) Method((string, string) x)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(16793, "https://github.com/dotnet/roslyn/issues/16793")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethodWithValueTupleArity1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"
using System;
interface I
{
ValueTuple<object> F();
}
class C : {|CS0535:I|}
{
}",
@"
using System;
interface I
{
ValueTuple<object> F();
}
class C : I
{
public ValueTuple<object> F()
{
throw new NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExpressionBodiedMethod1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"interface IInterface
{
void Method1();
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
void Method1();
}
class Class : IInterface
{
public void Method1() => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)]
public async Task TupleWithNamesInMethod()
{
// Note: we're putting the attribute by hand to simulate metadata
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
[return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Method1((int c, string) x);
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
[return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Method1((int c, string) x);
}
class Class : IInterface
{
public (int a, int b)[] Method1((int c, string) x)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)]
public async Task TupleWithNamesInMethod_Explicitly()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
[return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Method1((int c, string) x);
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
[return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Method1((int c, string) x);
}
class Class : IInterface
{
(int a, int b)[] IInterface.Method1((int c, string) x)
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)]
public async Task TupleWithNamesInProperty()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
[{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Property1 { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] get; [param: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] set; }
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
[{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
(int a, int b)[] Property1 { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] get; [param: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] set; }
}
class Class : IInterface
{
public (int a, int b)[] Property1
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)]
public async Task TupleWithNamesInEvent()
{
await new VerifyCS.Test
{
TestCode = @"interface IInterface
{
[{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
event System.Func<(int a, int b)> Event1;
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"using System;
interface IInterface
{
[{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}]
event System.Func<(int a, int b)> Event1;
}
class Class : IInterface
{
public event Func<(int a, int b)> Event1;
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task NoDynamicAttributeInMethod()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
[return: {|CS1970:System.Runtime.CompilerServices.DynamicAttribute()|}]
object Method1();
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
[return: {|CS1970:System.Runtime.CompilerServices.DynamicAttribute()|}]
object Method1();
}
class Class : IInterface
{
public object Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task NoNullableAttributesInMethodFromMetadata()
{
var test = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
#nullable enable
using System;
class C : {|CS0535:{|CS0535:IInterface|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"
#nullable enable
public interface IInterface
{
void M(string? s1, string s2);
string this[string? s1, string s2] { get; set; }
}"
},
},
},
AdditionalProjectReferences =
{
"Assembly1",
},
},
FixedState =
{
Sources =
{
@"
#nullable enable
using System;
class C : IInterface
{
public string this[string? s1, string s2]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public void M(string? s1, string s2)
{
throw new NotImplementedException();
}
}",
},
},
CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethodWhenClassBracesAreMissing()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
void Method1();
}
class Class : {|CS0535:IInterface|}{|CS1513:|}{|CS1514:|}",
@"interface IInterface
{
void Method1();
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInheritance1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
}
class Class : {|CS0535:IInterface2|}
{
}",
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
}
class Class : IInterface2
{
public void Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInheritance2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
}
interface IInterface2 : IInterface1
{
void Method1();
}
class Class : {|CS0535:IInterface2|}
{
}",
@"interface IInterface1
{
}
interface IInterface2 : IInterface1
{
void Method1();
}
class Class : IInterface2
{
public void Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInheritance3()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
void Method2();
}
class Class : {|CS0535:{|CS0535:IInterface2|}|}
{
}",
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
void Method2();
}
class Class : IInterface2
{
public void Method1()
{
throw new System.NotImplementedException();
}
public void Method2()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInheritanceMatchingMethod()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
void Method1();
}
class Class : {|CS0535:{|CS0535:IInterface2|}|}
{
}",
@"interface IInterface1
{
void Method1();
}
interface IInterface2 : IInterface1
{
void Method1();
}
class Class : IInterface2
{
public void Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExistingConflictingMethodReturnType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
void Method1();
}
class Class : {|CS0738:IInterface1|}
{
public int Method1()
{
return 0;
}
}",
@"interface IInterface1
{
void Method1();
}
class Class : IInterface1
{
public int Method1()
{
return 0;
}
void IInterface1.Method1()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExistingConflictingMethodParameters()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1
{
void Method1(int i);
}
class Class : {|CS0535:IInterface1|}
{
public void Method1(string i)
{
}
}",
@"interface IInterface1
{
void Method1(int i);
}
class Class : IInterface1
{
public void Method1(string i)
{
}
public void Method1(int i)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementGenericType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1<T>
{
void Method1(T t);
}
class Class : {|CS0535:IInterface1<int>|}
{
}",
@"interface IInterface1<T>
{
void Method1(T t);
}
class Class : IInterface1<int>
{
public void Method1(int t)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementGenericTypeWithGenericMethod()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1<T>
{
void Method1<U>(T t, U u);
}
class Class : {|CS0535:IInterface1<int>|}
{
}",
@"interface IInterface1<T>
{
void Method1<U>(T t, U u);
}
class Class : IInterface1<int>
{
public void Method1<U>(int t, U u)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementGenericTypeWithGenericMethodWithNaturalConstraint()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections.Generic;
interface IInterface1<T>
{
void Method1<U>(T t, U u) where U : IList<T>;
}
class Class : {|CS0535:IInterface1<int>|}
{
}",
@"using System.Collections.Generic;
interface IInterface1<T>
{
void Method1<U>(T t, U u) where U : IList<T>;
}
class Class : IInterface1<int>
{
public void Method1<U>(int t, U u) where U : IList<int>
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementGenericTypeWithGenericMethodWithUnexpressibleConstraint()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface1<T>
{
void Method1<U>(T t, U u) where U : T;
}
class Class : {|CS0535:IInterface1<int>|}
{
}",
@"interface IInterface1<T>
{
void Method1<U>(T t, U u) where U : T;
}
class Class : IInterface1<int>
{
void IInterface1<int>.Method1<U>(int t, U u)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestArrayType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
string[] M();
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
string[] M();
}
class C : I
{
public string[] M()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMember()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Method1();
}
class C : {|CS0535:I|}
{
I i;
}",
@"interface I
{
void Method1();
}
class C : I
{
I i;
public void Method1()
{
i.Method1();
}
}",
codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMember_FixAll_SameMemberInDifferentType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Method1();
}
class C : {|CS0535:I|}
{
I i;
}
class D : {|CS0535:I|}
{
I i;
}",
@"interface I
{
void Method1();
}
class C : I
{
I i;
public void Method1()
{
i.Method1();
}
}
class D : I
{
I i;
public void Method1()
{
i.Method1();
}
}",
codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMember_FixAll_FieldInOnePropInAnother()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Method1();
}
class C : {|CS0535:I|}
{
I i;
}
class D : {|CS0535:I|}
{
I i { get; }
}",
@"interface I
{
void Method1();
}
class C : I
{
I i;
public void Method1()
{
i.Method1();
}
}
class D : I
{
I i { get; }
public void Method1()
{
i.Method1();
}
}",
codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMember_FixAll_FieldInOneNonViableInAnother()
{
var test = new VerifyCS.Test
{
TestCode = @"interface I
{
void Method1();
}
class C : {|CS0535:I|}
{
I i;
}
class D : {|CS0535:I|}
{
int i;
}",
FixedState =
{
Sources =
{
@"interface I
{
void Method1();
}
class C : I
{
I i;
public void Method1()
{
i.Method1();
}
}
class D : {|CS0535:I|}
{
int i;
}",
},
MarkupHandling = MarkupMode.Allow,
},
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i",
CodeActionIndex = 1,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMemberInterfaceWithIndexer()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
int this[int x] { get; set; }
}
class Goo : {|CS0535:IGoo|}
{
IGoo f;
}",
@"interface IGoo
{
int this[int x] { get; set; }
}
class Goo : IGoo
{
IGoo f;
public int this[int x]
{
get
{
return f[x];
}
set
{
f[x] = value;
}
}
}",
codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;f", 1));
}
[WorkItem(472, "https://github.com/dotnet/roslyn/issues/472")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMemberRemoveUnnecessaryCast()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections;
sealed class X : {|CS0535:IComparer|}
{
X x;
}",
@"using System.Collections;
sealed class X : IComparer
{
X x;
public int Compare(object x, object y)
{
return ((IComparer)this.x).Compare(x, y);
}
}",
codeAction: ("False;False;False:global::System.Collections.IComparer;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;x", 1));
}
[WorkItem(472, "https://github.com/dotnet/roslyn/issues/472")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementThroughFieldMemberRemoveUnnecessaryCastAndThis()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections;
sealed class X : {|CS0535:IComparer|}
{
X a;
}",
@"using System.Collections;
sealed class X : IComparer
{
X a;
public int Compare(object x, object y)
{
return ((IComparer)a).Compare(x, y);
}
}",
codeAction: ("False;False;False:global::System.Collections.IComparer;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementAbstract()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Method1();
}
abstract class C : {|CS0535:I|}
{
}",
@"interface I
{
void Method1();
}
abstract class C : I
{
public abstract void Method1();
}",
codeAction: ("False;True;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceWithRefOutParameters()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class C : {|CS0535:{|CS0535:I|}|}
{
I goo;
}
interface I
{
void Method1(ref int x, out int y, int z);
int Method2();
}",
@"class C : I
{
I goo;
public void Method1(ref int x, out int y, int z)
{
goo.Method1(ref x, out y, z);
}
public int Method2()
{
return goo.Method2();
}
}
interface I
{
void Method1(ref int x, out int y, int z);
int Method2();
}",
codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConflictingMethods1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class B
{
public int Method1()
{
return 0;
}
}
class C : B, {|CS0738:I|}
{
}
interface I
{
void Method1();
}",
@"class B
{
public int Method1()
{
return 0;
}
}
class C : B, I
{
void I.Method1()
{
throw new System.NotImplementedException();
}
}
interface I
{
void Method1();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConflictingProperties()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class Test : {|CS0737:I1|}
{
int Prop { get; set; }
}
interface I1
{
int Prop { get; set; }
}",
@"class Test : I1
{
int Prop { get; set; }
int I1.Prop
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}
interface I1
{
int Prop { get; set; }
}");
}
[WorkItem(539043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539043")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExplicitProperties()
{
var code =
@"interface I2
{
decimal Calc { get; }
}
class C : I2
{
protected decimal pay;
decimal I2.Calc
{
get
{
return pay;
}
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedMethodName()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
void @M();
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
void @M();
}
class Class : IInterface
{
public void M()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedMethodKeyword()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
void @int();
}
class Class : {|CS0535:IInterface|}
{
}",
@"interface IInterface
{
void @int();
}
class Class : IInterface
{
public void @int()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedInterfaceName1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface @IInterface
{
void M();
}
class Class : {|CS0737:@IInterface|}
{
string M() => """";
}",
@"interface @IInterface
{
void M();
}
class Class : @IInterface
{
string M() => """";
void IInterface.M()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedInterfaceName2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface @IInterface
{
void @M();
}
class Class : {|CS0737:@IInterface|}
{
string M() => """";
}",
@"interface @IInterface
{
void @M();
}
class Class : @IInterface
{
string M() => """";
void IInterface.M()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedInterfaceKeyword1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface @int
{
void M();
}
class Class : {|CS0737:@int|}
{
string M() => """";
}",
@"interface @int
{
void M();
}
class Class : @int
{
string M() => """";
void @int.M()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEscapedInterfaceKeyword2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface @int
{
void @bool();
}
class Class : {|CS0737:@int|}
{
string @bool() => """";
}",
@"interface @int
{
void @bool();
}
class Class : @int
{
string @bool() => """";
void @int.@bool()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestPropertyFormatting()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface DD
{
int Prop { get; set; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; set; }
}
public class A : DD
{
public int Prop
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestProperty_PropertyCodeStyleOn1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int Prop { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; }
}
public class A : DD
{
public int Prop => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestProperty_AccessorCodeStyleOn1()
{
await TestWithAccessorCodeStyleOptionsOnAsync(
@"public interface DD
{
int Prop { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; }
}
public class A : DD
{
public int Prop { get => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexer_IndexerCodeStyleOn1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; }
}
public class A : DD
{
public int this[int i] => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexer_AccessorCodeStyleOn1()
{
await TestWithAccessorCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; }
}
public class A : DD
{
public int this[int i] { get => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMethod_AllCodeStyleOn1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int M();
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int M();
}
public class A : DD
{
public int M() => throw new System.NotImplementedException();
}");
}
[WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestReadonlyPropertyExpressionBodyYes1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int Prop { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; }
}
public class A : DD
{
public int Prop => throw new System.NotImplementedException();
}");
}
[WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestReadonlyPropertyAccessorBodyYes1()
{
await TestWithAccessorCodeStyleOptionsOnAsync(
@"public interface DD
{
int Prop { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; }
}
public class A : DD
{
public int Prop { get => throw new System.NotImplementedException(); }
}");
}
[WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestReadonlyPropertyAccessorBodyYes2()
{
await TestWithAccessorCodeStyleOptionsOnAsync(
@"public interface DD
{
int Prop { get; set; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; set; }
}
public class A : DD
{
public int Prop { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
}");
}
[WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestReadonlyPropertyExpressionBodyNo1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface DD
{
int Prop { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int Prop { get; }
}
public class A : DD
{
public int Prop
{
get
{
throw new System.NotImplementedException();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexerExpressionBodyYes1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; }
}
public class A : DD
{
public int this[int i] => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexerExpressionBodyNo1()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; set; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; set; }
}
public class A : DD
{
public int this[int i] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexerAccessorExpressionBodyYes1()
{
await TestWithAccessorCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; }
}
public class A : DD
{
public int this[int i] { get => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexerAccessorExpressionBodyYes2()
{
await TestWithAllCodeStyleOptionsOnAsync(
@"public interface DD
{
int this[int i] { get; set; }
}
public class A : {|CS0535:DD|}
{
}",
@"public interface DD
{
int this[int i] { get; set; }
}
public class A : DD
{
public int this[int i] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCommentPlacement()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface DD
{
void Goo();
}
public class A : {|CS0535:DD|}
{
//comments
}",
@"public interface DD
{
void Goo();
}
public class A : DD
{
//comments
public void Goo()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(539991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539991")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestBracePlacement()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IServiceProvider
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(540318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMissingWithIncompleteMember()
{
var code =
@"interface ITest
{
void Method();
}
class Test : ITest
{
p {|CS1585:public|} void Method()
{
throw new System.NotImplementedException();
}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[WorkItem(541380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541380")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExplicitProperty()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface i1
{
int p { get; set; }
}
class c1 : {|CS0535:i1|}
{
}",
@"interface i1
{
int p { get; set; }
}
class c1 : i1
{
int i1.p
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}",
codeAction: ("True;False;False:global::i1;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(541981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541981")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoDelegateThroughField1()
{
var code =
@"interface I
{
void Method1();
}
class C : {|CS0535:I|}
{
I i { get; set; }
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = @"interface I
{
void Method1();
}
class C : I
{
I i { get; set; }
public void Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
CodeActionEquivalenceKey = "False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
await new VerifyCS.Test
{
TestCode = code,
FixedCode = @"interface I
{
void Method1();
}
class C : I
{
I i { get; set; }
public void Method1()
{
i.Method1();
}
}",
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i",
CodeActionIndex = 1,
}.RunAsync();
await new VerifyCS.Test
{
TestCode = code,
FixedCode = @"interface I
{
void Method1();
}
class C : I
{
I i { get; set; }
void I.Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
CodeActionEquivalenceKey = "True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 2,
}.RunAsync();
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIReadOnlyListThroughField()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections.Generic;
class A : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IReadOnlyList<int>|}|}|}|}
{
int[] field;
}",
@"using System.Collections;
using System.Collections.Generic;
class A : IReadOnlyList<int>
{
int[] field;
public int this[int index]
{
get
{
return ((IReadOnlyList<int>)field)[index];
}
}
public int Count
{
get
{
return ((IReadOnlyCollection<int>)field).Count;
}
}
public IEnumerator<int> GetEnumerator()
{
return ((IEnumerable<int>)field).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return field.GetEnumerator();
}
}",
codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList<int>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1));
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIReadOnlyListThroughProperty()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections.Generic;
class A : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IReadOnlyList<int>|}|}|}|}
{
int[] field { get; set; }
}",
@"using System.Collections;
using System.Collections.Generic;
class A : IReadOnlyList<int>
{
public int this[int index]
{
get
{
return ((IReadOnlyList<int>)field)[index];
}
}
public int Count
{
get
{
return ((IReadOnlyCollection<int>)field).Count;
}
}
int[] field { get; set; }
public IEnumerator<int> GetEnumerator()
{
return ((IEnumerable<int>)field).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return field.GetEnumerator();
}
}",
codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList<int>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1));
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughField()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A a;
}",
@"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I
{
A a;
public int M()
{
return ((I)a).M();
}
}",
codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1));
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughField_FieldImplementsMultipleInterfaces()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I, I2
{
int I.M()
{
return 0;
}
int I2.M2()
{
return 0;
}
}
class B : {|CS0535:I|}, {|CS0535:I2|}
{
A a;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I, I2
{
int I.M()
{
return 0;
}
int I2.M2()
{
return 0;
}
}
class B : I, {|CS0535:I2|}
{
A a;
public int M()
{
return ((I)a).M();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
DiagnosticSelector = diagnostics => diagnostics[0],
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a",
CodeActionIndex = 1,
}.RunAsync();
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I, I2
{
int I.M()
{
return 0;
}
int I2.M2()
{
return 0;
}
}
class B : {|CS0535:I|}, {|CS0535:I2|}
{
A a;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I, I2
{
int I.M()
{
return 0;
}
int I2.M2()
{
return 0;
}
}
class B : {|CS0535:I|}, I2
{
A a;
public int M2()
{
return ((I2)a).M2();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
DiagnosticSelector = diagnostics => diagnostics[1],
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "False;False;False:global::I2;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughField_MultipleFieldsCanImplementInterface()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A a;
A aa;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I
{
A a;
A aa;
public int M()
{
return ((I)a).M();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(4, codeActions.Length),
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a",
CodeActionIndex = 1,
}.RunAsync();
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A a;
A aa;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I
{
A a;
A aa;
public int M()
{
return ((I)aa).M();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(4, codeActions.Length),
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;aa",
CodeActionIndex = 2,
}.RunAsync();
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughField_MultipleFieldsForMultipleInterfaces()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I2
{
int I2.M2()
{
return 0;
}
}
class C : {|CS0535:I|}, {|CS0535:I2|}
{
A a;
B b;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I2
{
int I2.M2()
{
return 0;
}
}
class C : I, {|CS0535:I2|}
{
A a;
B b;
public int M()
{
return ((I)a).M();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
DiagnosticSelector = diagnostics => diagnostics[0],
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a",
CodeActionIndex = 1,
}.RunAsync();
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I2
{
int I2.M2()
{
return 0;
}
}
class C : {|CS0535:I|}, {|CS0535:I2|}
{
A a;
B b;
}",
FixedState =
{
Sources =
{
@"interface I
{
int M();
}
interface I2
{
int M2();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I2
{
int I2.M2()
{
return 0;
}
}
class C : {|CS0535:I|}, I2
{
A a;
B b;
public int M2()
{
return ((I2)b).M2();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
DiagnosticSelector = diagnostics => diagnostics[1],
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "False;False;False:global::I2;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;b",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(18556, "https://github.com/dotnet/roslyn/issues/18556")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughExplicitProperty()
{
await new VerifyCS.Test
{
TestCode = @"interface IA
{
IB B { get; }
}
interface IB
{
int M();
}
class AB : IA, {|CS0535:IB|}
{
IB IA.B => null;
}",
FixedCode = @"interface IA
{
IB B { get; }
}
interface IB
{
int M();
}
class AB : IA, IB
{
IB IA.B => null;
public int M()
{
return ((IA)this).B.M();
}
}",
Options = { AllOptionsOff },
CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length),
CodeActionEquivalenceKey = "False;False;False:global::IB;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;IA.B",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoImplementThroughIndexer()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A this[int index]
{
get
{
return null;
}
}
}",
FixedCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : I
{
A this[int index]
{
get
{
return null;
}
}
public int M()
{
throw new System.NotImplementedException();
}
}",
CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length),
}.RunAsync();
}
[WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoImplementThroughWriteOnlyProperty()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A a
{
set
{
}
}
}",
FixedCode = @"interface I
{
int M();
}
class A : I
{
int I.M()
{
return 0;
}
}
class B : {|CS0535:I|}
{
A a
{
set
{
}
}
public int M()
{
throw new System.NotImplementedException();
}
}",
CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementEventThroughMember()
{
await TestInRegularAndScriptAsync(@"
interface IGoo
{
event System.EventHandler E;
}
class CanGoo : IGoo
{
public event System.EventHandler E;
}
class HasCanGoo : {|CS0535:IGoo|}
{
CanGoo canGoo;
}",
@"
using System;
interface IGoo
{
event System.EventHandler E;
}
class CanGoo : IGoo
{
public event System.EventHandler E;
}
class HasCanGoo : IGoo
{
CanGoo canGoo;
public event EventHandler E
{
add
{
((IGoo)canGoo).E += value;
}
remove
{
((IGoo)canGoo).E -= value;
}
}
}", codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;canGoo", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementEventThroughExplicitMember()
{
await TestInRegularAndScriptAsync(
@"interface IGoo { event System . EventHandler E ; } class CanGoo : IGoo { event System.EventHandler IGoo.E { add { } remove { } } } class HasCanGoo : {|CS0535:IGoo|} { CanGoo canGoo; } ",
@"using System;
interface IGoo { event System . EventHandler E ; } class CanGoo : IGoo { event System.EventHandler IGoo.E { add { } remove { } } } class HasCanGoo : IGoo { CanGoo canGoo;
public event EventHandler E
{
add
{
((IGoo)canGoo).E += value;
}
remove
{
((IGoo)canGoo).E -= value;
}
}
} ",
codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;canGoo", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementEvent()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : {|CS0535:IGoo|}
{
}",
@"using System;
interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : IGoo
{
public event EventHandler E;
}",
codeAction: ("False;False;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementEventAbstractly()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : {|CS0535:IGoo|}
{
}",
@"using System;
interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : IGoo
{
public abstract event EventHandler E;
}",
codeAction: ("False;True;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementEventExplicitly()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : {|CS0535:IGoo|}
{
}",
@"using System;
interface IGoo
{
event System.EventHandler E;
}
abstract class Goo : IGoo
{
event EventHandler IGoo.E
{
add
{
throw new NotImplementedException();
}
remove
{
throw new NotImplementedException();
}
}
}",
codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestFaultToleranceInStaticMembers_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IFoo
{
static string Name { set; get; }
static int {|CS0501:Foo|}(string s);
}
class Program : IFoo
{
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestFaultToleranceInStaticMembers_02()
{
var test = new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IFoo
{
string Name { set; get; }
static int {|CS0501:Foo|}(string s);
}
class Program : {|CS0535:IFoo|}
{
}",
FixedCode = @"interface IFoo
{
string Name { set; get; }
static int {|CS0501:Foo|}(string s);
}
class Program : IFoo
{
public string Name
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}",
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestFaultToleranceInStaticMembers_03()
{
var test = new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IGoo
{
static string Name { set; get; }
int Goo(string s);
}
class Program : {|CS0535:IGoo|}
{
}",
FixedCode = @"interface IGoo
{
static string Name { set; get; }
int Goo(string s);
}
class Program : IGoo
{
public int Goo(string s)
{
throw new System.NotImplementedException();
}
}",
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexers()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface ISomeInterface
{
int this[int index] { get; set; }
}
class IndexerClass : {|CS0535:ISomeInterface|}
{
}",
@"public interface ISomeInterface
{
int this[int index] { get; set; }
}
class IndexerClass : ISomeInterface
{
public int this[int index]
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexersExplicit()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface ISomeInterface
{
int this[int index] { get; set; }
}
class IndexerClass : {|CS0535:ISomeInterface|}
{
}",
@"public interface ISomeInterface
{
int this[int index] { get; set; }
}
class IndexerClass : ISomeInterface
{
int ISomeInterface.this[int index]
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}",
codeAction: ("True;False;False:global::ISomeInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexersWithASingleAccessor()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface ISomeInterface
{
int this[int index] { get; }
}
class IndexerClass : {|CS0535:ISomeInterface|}
{
}",
@"public interface ISomeInterface
{
int this[int index] { get; }
}
class IndexerClass : ISomeInterface
{
public int this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConstraints1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo<T>() where T : class;
}
class A : {|CS0535:I|}
{
}",
@"interface I
{
void Goo<T>() where T : class;
}
class A : I
{
public void Goo<T>() where T : class
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConstraintsExplicit()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo<T>() where T : class;
}
class A : {|CS0535:I|}
{
}",
@"interface I
{
void Goo<T>() where T : class;
}
class A : I
{
void I.Goo<T>()
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUsingAddedForConstraint()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo<T>() where T : System.Attribute;
}
class A : {|CS0535:I|}
{
}",
@"using System;
interface I
{
void Goo<T>() where T : System.Attribute;
}
class A : I
{
public void Goo<T>() where T : Attribute
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542379")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIndexer()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
int this[int x] { get; set; }
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
int this[int x] { get; set; }
}
class C : I
{
public int this[int x]
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(542588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542588")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRecursiveConstraint1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void Goo<T>() where T : IComparable<T>;
}
class C : {|CS0535:I|}
{
}",
@"using System;
interface I
{
void Goo<T>() where T : IComparable<T>;
}
class C : I
{
public void Goo<T>() where T : IComparable<T>
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542588")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRecursiveConstraint2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void Goo<T>() where T : IComparable<T>;
}
class C : {|CS0535:I|}
{
}",
@"using System;
interface I
{
void Goo<T>() where T : IComparable<T>;
}
class C : I
{
void I.Goo<T>()
{
throw new NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<string>|}
{
}",
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<string>
{
void I<string>.Goo<T>()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<object>|}
{
}",
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<object>
{
public void Goo<T>() where T : class
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint3()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<object>|}
{
}",
@"interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<object>
{
void I<object>.Goo<T>()
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I<object>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint4()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<Delegate>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<Delegate>
{
void I<Delegate>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint5()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<MulticastDelegate>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<MulticastDelegate>
{
void I<MulticastDelegate>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint6()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
delegate void Bar();
class A : {|CS0535:I<Bar>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
delegate void Bar();
class A : I<Bar>
{
void I<Bar>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint7()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<Enum>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<Enum>
{
void I<Enum>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint8()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : {|CS0535:I<int[]>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class A : I<int[]>
{
void I<int[]>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint9()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
enum E
{
}
class A : {|CS0535:I<E>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
enum E
{
}
class A : I<E>
{
void I<E>.Goo<{|CS0455:T|}>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542621")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnexpressibleConstraint10()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : S;
}
class A : {|CS0535:I<ValueType>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : S;
}
class A : I<ValueType>
{
void I<ValueType>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542669")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestArrayConstraint()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : S;
}
class C : {|CS0535:I<Array>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : S;
}
class C : I<Array>
{
void I<Array>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542743")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMultipleClassConstraints()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : Exception, S;
}
class C : {|CS0535:I<Attribute>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : Exception, S;
}
class C : I<Attribute>
{
void I<Attribute>.Goo<{|CS0455:T|}>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542751")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestClassConstraintAndRefConstraint()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class C : {|CS0535:I<Exception>|}
{
}",
@"using System;
interface I<S>
{
void Goo<T>() where T : class, S;
}
class C : I<Exception>
{
void I<Exception>.Goo<T>()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRenameConflictingTypeParameters1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Collections.Generic;
interface I<T>
{
void Goo<S>(T x, IList<S> list) where S : T;
}
class A<S> : {|CS0535:I<S>|}
{
}",
@"using System;
using System.Collections.Generic;
interface I<T>
{
void Goo<S>(T x, IList<S> list) where S : T;
}
class A<S> : I<S>
{
public void Goo<S1>(S x, IList<S1> list) where S1 : S
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRenameConflictingTypeParameters2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Collections.Generic;
interface I<T>
{
void Goo<S>(T x, IList<S> list) where S : T;
}
class A<S> : {|CS0535:I<S>|}
{
}",
@"using System;
using System.Collections.Generic;
interface I<T>
{
void Goo<S>(T x, IList<S> list) where S : T;
}
class A<S> : I<S>
{
void I<S>.Goo<S1>(S x, IList<S1> list)
{
throw new NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I<S>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRenameConflictingTypeParameters3()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Collections.Generic;
interface I<X, Y>
{
void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2)
where A : IList<B>
where B : IList<A>;
}
class C<A, B> : {|CS0535:I<A, B>|}
{
}",
@"using System;
using System.Collections.Generic;
interface I<X, Y>
{
void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2)
where A : IList<B>
where B : IList<A>;
}
class C<A, B> : I<A, B>
{
public void Goo<A1, B1>(A x, B y, IList<A1> list1, IList<B1> list2)
where A1 : IList<B1>
where B1 : IList<A1>
{
throw new NotImplementedException();
}
}");
}
[WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRenameConflictingTypeParameters4()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Collections.Generic;
interface I<X, Y>
{
void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2)
where A : IList<B>
where B : IList<A>;
}
class C<A, B> : {|CS0535:I<A, B>|}
{
}",
@"using System;
using System.Collections.Generic;
interface I<X, Y>
{
void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2)
where A : IList<B>
where B : IList<A>;
}
class C<A, B> : I<A, B>
{
void I<A, B>.Goo<A1, B1>(A x, B y, IList<A1> list1, IList<B1> list2)
{
throw new NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I<A, B>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNameSimplification()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class A<T>
{
class B
{
}
interface I
{
void Goo(B x);
}
class C<U> : {|CS0535:I|}
{
}
}",
@"using System;
class A<T>
{
class B
{
}
interface I
{
void Goo(B x);
}
class C<U> : I
{
public void Goo(B x)
{
throw new NotImplementedException();
}
}
}");
}
[WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNameSimplification2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class A<T>
{
class B
{
}
interface I
{
void Goo(B[] x);
}
class C<U> : {|CS0535:I|}
{
}
}",
@"class A<T>
{
class B
{
}
interface I
{
void Goo(B[] x);
}
class C<U> : I
{
public void Goo(B[] x)
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNameSimplification3()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class A<T>
{
class B
{
}
interface I
{
void Goo(B[][,][,,][,,,] x);
}
class C<U> : {|CS0535:I|}
{
}
}",
@"class A<T>
{
class B
{
}
interface I
{
void Goo(B[][,][,,][,,,] x);
}
class C<U> : I
{
public void Goo(B[][,][,,][,,,] x)
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(544166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544166")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementAbstractProperty()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
int Gibberish { get; set; }
}
abstract class Goo : {|CS0535:IGoo|}
{
}",
@"interface IGoo
{
int Gibberish { get; set; }
}
abstract class Goo : IGoo
{
public abstract int Gibberish { get; set; }
}",
codeAction: ("False;True;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(544210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544210")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMissingOnWrongArity()
{
var code =
@"interface I1<T>
{
int X { get; set; }
}
class C : {|CS0305:I1|}
{
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[WorkItem(544281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544281")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplicitDefaultValue()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IOptional
{
int Goo(int g = 0);
}
class Opt : {|CS0535:IOptional|}
{
}",
@"interface IOptional
{
int Goo(int g = 0);
}
class Opt : IOptional
{
public int Goo(int g = 0)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(544281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544281")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExplicitDefaultValue()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IOptional
{
int Goo(int g = 0);
}
class Opt : {|CS0535:IOptional|}
{
}",
@"interface IOptional
{
int Goo(int g = 0);
}
class Opt : IOptional
{
int IOptional.Goo(int g)
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::IOptional;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMissingInHiddenType()
{
var code =
@"using System;
class Program : {|CS0535:IComparable|}
{
#line hidden
}
#line default";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestGenerateIntoVisiblePart()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"#line default
using System;
partial class Program : {|CS0535:IComparable|}
{
void Goo()
{
#line hidden
}
}
#line default",
@"#line default
using System;
partial class Program : IComparable
{
public int CompareTo(object obj)
{
throw new NotImplementedException();
}
void Goo()
{
#line hidden
}
}
#line default");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestGenerateIfAvailableRegionExists()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
partial class Program : {|CS0535:IComparable|}
{
#line hidden
}
#line default
partial class Program
{
}",
@"using System;
partial class Program : IComparable
{
#line hidden
}
#line default
partial class Program
{
public int CompareTo(object obj)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(545334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545334")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoGenerateInVenusCase1()
{
var code =
@"using System;
#line 1 ""Bar""
class Goo : {|CS0535:IComparable|}{|CS1513:|}{|CS1514:|}
#line default
#line hidden
// stuff";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[WorkItem(545476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545476")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalDateTime1()
{
await new VerifyCS.Test
{
TestCode = @"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo([Optional][DateTimeConstant(100)] DateTime x);
}
public class C : {|CS0535:IGoo|}
{
}",
FixedCode = @"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo([Optional][DateTimeConstant(100)] DateTime x);
}
public class C : IGoo
{
public void Goo([DateTimeConstant(100), Optional] DateTime x)
{
throw new NotImplementedException();
}
}",
Options = { AllOptionsOff },
// 🐛 one value is generated with 0L instead of 0
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(545476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545476")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalDateTime2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo([Optional][DateTimeConstant(100)] DateTime x);
}
public class C : {|CS0535:IGoo|}
{
}",
@"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo([Optional][DateTimeConstant(100)] DateTime x);
}
public class C : IGoo
{
void IGoo.Goo(DateTime x)
{
throw new NotImplementedException();
}
}",
codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(545477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545477")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIUnknownIDispatchAttributes1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo1([Optional][IUnknownConstant] object x);
void Goo2([Optional][IDispatchConstant] object x);
}
public class C : {|CS0535:{|CS0535:IGoo|}|}
{
}",
@"using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo1([Optional][IUnknownConstant] object x);
void Goo2([Optional][IDispatchConstant] object x);
}
public class C : IGoo
{
public void Goo1([IUnknownConstant, Optional] object x)
{
throw new System.NotImplementedException();
}
public void Goo2([IDispatchConstant, Optional] object x)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545477")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIUnknownIDispatchAttributes2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo1([Optional][IUnknownConstant] object x);
void Goo2([Optional][IDispatchConstant] object x);
}
public class C : {|CS0535:{|CS0535:IGoo|}|}
{
}",
@"using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface IGoo
{
void Goo1([Optional][IUnknownConstant] object x);
void Goo2([Optional][IDispatchConstant] object x);
}
public class C : IGoo
{
void IGoo.Goo1(object x)
{
throw new System.NotImplementedException();
}
void IGoo.Goo2(object x)
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(545464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545464")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestTypeNameConflict()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo
{
void Goo();
}
public class Goo : {|CS0535:IGoo|}
{
}",
@"interface IGoo
{
void Goo();
}
public class Goo : IGoo
{
void IGoo.Goo()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStringLiteral()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IGoo { void Goo ( string s = ""\"""" ) ; } class B : {|CS0535:IGoo|} { } ",
@"interface IGoo { void Goo ( string s = ""\"""" ) ; }
class B : IGoo
{
public void Goo(string s = ""\"""")
{
throw new System.NotImplementedException();
}
} ");
}
[WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalNullableStructParameter1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"struct b
{
}
interface d
{
void m(b? x = null, b? y = default(b?));
}
class c : {|CS0535:d|}
{
}",
@"struct b
{
}
interface d
{
void m(b? x = null, b? y = default(b?));
}
class c : d
{
public void m(b? x = null, b? y = null)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalNullableStructParameter2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"struct b
{
}
interface d
{
void m(b? x = null, b? y = default(b?));
}
class c : {|CS0535:d|}
{
}",
@"struct b
{
}
interface d
{
void m(b? x = null, b? y = default(b?));
}
class c : d
{
void d.m(b? x, b? y)
{
throw new System.NotImplementedException();
}
}", codeAction: ("True;False;False:global::d;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalNullableIntParameter()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface d
{
void m(int? x = 5, int? y = null);
}
class c : {|CS0535:d|}
{
}",
@"interface d
{
void m(int? x = 5, int? y = null);
}
class c : d
{
public void m(int? x = 5, int? y = null)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545613")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalWithNoDefaultValue()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional] I o);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional] I o);
}
class C : I
{
public void Goo([Optional] I o)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestIntegralAndFloatLiterals()
{
await new VerifyCS.Test
{
TestCode = @"interface I
{
void M01(short s = short.MinValue);
void M02(short s = -1);
void M03(short s = short.MaxValue);
void M04(ushort s = ushort.MinValue);
void M05(ushort s = 1);
void M06(ushort s = ushort.MaxValue);
void M07(int s = int.MinValue);
void M08(int s = -1);
void M09(int s = int.MaxValue);
void M10(uint s = uint.MinValue);
void M11(uint s = 1);
void M12(uint s = uint.MaxValue);
void M13(long s = long.MinValue);
void M14(long s = -1);
void M15(long s = long.MaxValue);
void M16(ulong s = ulong.MinValue);
void M17(ulong s = 1);
void M18(ulong s = ulong.MaxValue);
void M19(float s = float.MinValue);
void M20(float s = 1);
void M21(float s = float.MaxValue);
void M22(double s = double.MinValue);
void M23(double s = 1);
void M24(double s = double.MaxValue);
}
class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}
{
}",
FixedCode = @"interface I
{
void M01(short s = short.MinValue);
void M02(short s = -1);
void M03(short s = short.MaxValue);
void M04(ushort s = ushort.MinValue);
void M05(ushort s = 1);
void M06(ushort s = ushort.MaxValue);
void M07(int s = int.MinValue);
void M08(int s = -1);
void M09(int s = int.MaxValue);
void M10(uint s = uint.MinValue);
void M11(uint s = 1);
void M12(uint s = uint.MaxValue);
void M13(long s = long.MinValue);
void M14(long s = -1);
void M15(long s = long.MaxValue);
void M16(ulong s = ulong.MinValue);
void M17(ulong s = 1);
void M18(ulong s = ulong.MaxValue);
void M19(float s = float.MinValue);
void M20(float s = 1);
void M21(float s = float.MaxValue);
void M22(double s = double.MinValue);
void M23(double s = 1);
void M24(double s = double.MaxValue);
}
class C : I
{
public void M01(short s = short.MinValue)
{
throw new System.NotImplementedException();
}
public void M02(short s = -1)
{
throw new System.NotImplementedException();
}
public void M03(short s = short.MaxValue)
{
throw new System.NotImplementedException();
}
public void M04(ushort s = 0)
{
throw new System.NotImplementedException();
}
public void M05(ushort s = 1)
{
throw new System.NotImplementedException();
}
public void M06(ushort s = ushort.MaxValue)
{
throw new System.NotImplementedException();
}
public void M07(int s = int.MinValue)
{
throw new System.NotImplementedException();
}
public void M08(int s = -1)
{
throw new System.NotImplementedException();
}
public void M09(int s = int.MaxValue)
{
throw new System.NotImplementedException();
}
public void M10(uint s = 0)
{
throw new System.NotImplementedException();
}
public void M11(uint s = 1)
{
throw new System.NotImplementedException();
}
public void M12(uint s = uint.MaxValue)
{
throw new System.NotImplementedException();
}
public void M13(long s = long.MinValue)
{
throw new System.NotImplementedException();
}
public void M14(long s = -1)
{
throw new System.NotImplementedException();
}
public void M15(long s = long.MaxValue)
{
throw new System.NotImplementedException();
}
public void M16(ulong s = 0)
{
throw new System.NotImplementedException();
}
public void M17(ulong s = 1)
{
throw new System.NotImplementedException();
}
public void M18(ulong s = ulong.MaxValue)
{
throw new System.NotImplementedException();
}
public void M19(float s = float.MinValue)
{
throw new System.NotImplementedException();
}
public void M20(float s = 1)
{
throw new System.NotImplementedException();
}
public void M21(float s = float.MaxValue)
{
throw new System.NotImplementedException();
}
public void M22(double s = double.MinValue)
{
throw new System.NotImplementedException();
}
public void M23(double s = 1)
{
throw new System.NotImplementedException();
}
public void M24(double s = double.MaxValue)
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
// 🐛 one value is generated with 0U instead of 0
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEnumLiterals()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
enum E
{
A = 1,
B = 2
}
[FlagsAttribute]
enum FlagE
{
A = 1,
B = 2
}
interface I
{
void M1(E e = E.A | E.B);
void M2(FlagE e = FlagE.A | FlagE.B);
}
class C : {|CS0535:{|CS0535:I|}|}
{
}",
@"using System;
enum E
{
A = 1,
B = 2
}
[FlagsAttribute]
enum FlagE
{
A = 1,
B = 2
}
interface I
{
void M1(E e = E.A | E.B);
void M2(FlagE e = FlagE.A | FlagE.B);
}
class C : I
{
public void M1(E e = (E)3)
{
throw new NotImplementedException();
}
public void M2(FlagE e = FlagE.A | FlagE.B)
{
throw new NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCharLiterals()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void M01(char c = '\0');
void M02(char c = '\r');
void M03(char c = '\n');
void M04(char c = '\t');
void M05(char c = '\b');
void M06(char c = '\v');
void M07(char c = '\'');
void M08(char c = '“');
void M09(char c = 'a');
void M10(char c = '""');
void M11(char c = '\u2029');
}
class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|}|}|}|}|}|}|}|}
{
}",
@"using System;
interface I
{
void M01(char c = '\0');
void M02(char c = '\r');
void M03(char c = '\n');
void M04(char c = '\t');
void M05(char c = '\b');
void M06(char c = '\v');
void M07(char c = '\'');
void M08(char c = '“');
void M09(char c = 'a');
void M10(char c = '""');
void M11(char c = '\u2029');
}
class C : I
{
public void M01(char c = '\0')
{
throw new NotImplementedException();
}
public void M02(char c = '\r')
{
throw new NotImplementedException();
}
public void M03(char c = '\n')
{
throw new NotImplementedException();
}
public void M04(char c = '\t')
{
throw new NotImplementedException();
}
public void M05(char c = '\b')
{
throw new NotImplementedException();
}
public void M06(char c = '\v')
{
throw new NotImplementedException();
}
public void M07(char c = '\'')
{
throw new NotImplementedException();
}
public void M08(char c = '“')
{
throw new NotImplementedException();
}
public void M09(char c = 'a')
{
throw new NotImplementedException();
}
public void M10(char c = '""')
{
throw new NotImplementedException();
}
public void M11(char c = '\u2029')
{
throw new NotImplementedException();
}
}");
}
[WorkItem(545695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545695")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRemoveParenthesesAroundTypeReference1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void Goo(DayOfWeek x = DayOfWeek.Friday);
}
class C : {|CS0535:I|}
{
DayOfWeek DayOfWeek { get; set; }
}",
@"using System;
interface I
{
void Goo(DayOfWeek x = DayOfWeek.Friday);
}
class C : I
{
DayOfWeek DayOfWeek { get; set; }
public void Goo(DayOfWeek x = DayOfWeek.Friday)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(545696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545696")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDecimalConstants1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo(decimal x = decimal.MaxValue);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void Goo(decimal x = decimal.MaxValue);
}
class C : I
{
public void Goo(decimal x = decimal.MaxValue)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545711")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNullablePrimitiveLiteral()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo(decimal? x = decimal.MaxValue);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void Goo(decimal? x = decimal.MaxValue);
}
class C : I
{
public void Goo(decimal? x = decimal.MaxValue)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545715")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNullableEnumType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void Goo(DayOfWeek? x = DayOfWeek.Friday);
}
class C : {|CS0535:I|}
{
}",
@"using System;
interface I
{
void Goo(DayOfWeek? x = DayOfWeek.Friday);
}
class C : I
{
public void Goo(DayOfWeek? x = DayOfWeek.Friday)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(545752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545752")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestByteLiterals()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo(byte x = 1);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void Goo(byte x = 1);
}
class C : I
{
public void Goo(byte x = 1)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545736")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCastedOptionalParameter1()
{
const string code = @"
using System;
interface I
{
void Goo(ConsoleColor x = (ConsoleColor)(-1));
}
class C : {|CS0535:I|}
{
}";
const string expected = @"
using System;
interface I
{
void Goo(ConsoleColor x = (ConsoleColor)(-1));
}
class C : I
{
public void Goo(ConsoleColor x = (ConsoleColor)(-1))
{
throw new NotImplementedException();
}
}";
await TestWithAllCodeStyleOptionsOffAsync(code, expected);
}
[WorkItem(545737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545737")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCastedEnumValue()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I
{
void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue);
}
class C : {|CS0535:I|}
{
}",
@"using System;
interface I
{
void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue);
}
class C : I
{
public void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(545785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545785")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoCastFromZeroToEnum()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"enum E
{
A = 1,
}
interface I
{
void Goo(E x = 0);
}
class C : {|CS0535:I|}
{
}",
@"enum E
{
A = 1,
}
interface I
{
void Goo(E x = 0);
}
class C : I
{
public void Goo(E x = 0)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545793")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMultiDimArray()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional][DefaultParameterValue(1)] int x, int[,] y);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional][DefaultParameterValue(1)] int x, int[,] y);
}
class C : I
{
public void Goo([{|CS1745:DefaultParameterValue|}(1), {|CS1745:Optional|}] int x = {|CS8017:1|}, int[,] y = null)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545794")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestParametersAfterOptionalParameter()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional, DefaultParameterValue(1)] int x, int[] y, int[] z);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
void Goo([Optional, DefaultParameterValue(1)] int x, int[] y, int[] z);
}
class C : I
{
public void Goo([{|CS1745:DefaultParameterValue|}(1), {|CS1745:Optional|}] int x = {|CS8017:1|}, int[] y = null, int[] z = null)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545605")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestAttributeInParameter()
{
var test = new VerifyCS.Test
{
TestCode =
@"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface I
{
void Goo([Optional][DateTimeConstant(100)] DateTime d1, [Optional][IUnknownConstant] object d2);
}
class C : {|CS0535:I|}
{
}
",
FixedCode =
@"using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
interface I
{
void Goo([Optional][DateTimeConstant(100)] DateTime d1, [Optional][IUnknownConstant] object d2);
}
class C : I
{
public void Goo([DateTimeConstant(100), Optional] DateTime d1, [IUnknownConstant, Optional] object d2)
{
throw new NotImplementedException();
}
}
",
// 🐛 the DateTimeConstant attribute is generated with 100L instead of 100
CodeActionValidationMode = CodeActionValidationMode.None,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[WorkItem(545897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545897")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNameConflictBetweenMethodAndTypeParameter()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<S>
{
void T1<T>(S x, T y);
}
class C<T> : {|CS0535:I<T>|}
{
}",
@"interface I<S>
{
void T1<T>(S x, T y);
}
class C<T> : I<T>
{
public void T1<T2>(T x, T2 y)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545895")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestTypeParameterReplacementWithOuterType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections.Generic;
interface I<S>
{
void Goo<T>(S y, List<T>.Enumerator x);
}
class D<T> : {|CS0535:I<T>|}
{
}",
@"using System.Collections.Generic;
interface I<S>
{
void Goo<T>(S y, List<T>.Enumerator x);
}
class D<T> : I<T>
{
public void Goo<T1>(T y, List<T1>.Enumerator x)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545864")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestFloatConstant()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo(float x = 1E10F);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void Goo(float x = 1E10F);
}
class C : I
{
public void Goo(float x = 1E+10F)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(544640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544640")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestKeywordForTypeParameterName()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo<@class>();
}
class C : {|CS0535:I|}{|CS1513:|}{|CS1514:|}",
@"interface I
{
void Goo<@class>();
}
class C : I
{
public void Goo<@class>()
{
throw new System.NotImplementedException();
}
}
");
}
[WorkItem(545922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545922")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExtremeDecimals()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo1(decimal x = 1E28M);
void Goo2(decimal x = -1E28M);
}
class C : {|CS0535:{|CS0535:I|}|}
{
}",
@"interface I
{
void Goo1(decimal x = 1E28M);
void Goo2(decimal x = -1E28M);
}
class C : I
{
public void Goo1(decimal x = 10000000000000000000000000000M)
{
throw new System.NotImplementedException();
}
public void Goo2(decimal x = -10000000000000000000000000000M)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(544659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544659")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonZeroScaleDecimals()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo(decimal x = 0.1M);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void Goo(decimal x = 0.1M);
}
class C : I
{
public void Goo(decimal x = 0.1M)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(544639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544639")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnterminatedComment()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
// Implement interface
class C : {|CS0535:IServiceProvider|} {|CS1035:|}/*
{|CS1513:|}{|CS1514:|}",
@"using System;
// Implement interface
class C : IServiceProvider /*
*/
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(529920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529920")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNewLineBeforeDirective()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
// Implement interface
class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|}
#pragma warning disable
",
@"using System;
// Implement interface
class C : IServiceProvider
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
#pragma warning disable
");
}
[WorkItem(529947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529947")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCommentAfterInterfaceList1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|} // Implement interface
",
@"using System;
class C : IServiceProvider // Implement interface
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(529947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529947")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestCommentAfterInterfaceList2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|}
// Implement interface
",
@"using System;
class C : IServiceProvider
{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
// Implement interface
");
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposable_NoDisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0));
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposable_DisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
$@"using System;
class C : IDisposable
{{
private bool disposedValue;
{DisposePattern("protected virtual ", "C", "public void ")}
}}
", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1));
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableExplicitly_NoDisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IDisposable
{
void IDisposable.Dispose()
{
throw new NotImplementedException();
}
}
", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2));
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableExplicitly_DisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:System.IDisposable|}
{
class IDisposable
{
}
}",
$@"using System;
class C : System.IDisposable
{{
private bool disposedValue;
class IDisposable
{{
}}
{DisposePattern("protected virtual ", "C", "void System.IDisposable.")}
}}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3));
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableAbstractly_NoDisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
abstract class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
@"using System;
abstract class C : IDisposable
{
public abstract void Dispose();
}
", codeAction: ("False;True;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2));
}
[WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")]
[WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableThroughMember_NoDisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IDisposable|}
{
private IDisposable goo;
}",
@"using System;
class C : IDisposable
{
private IDisposable goo;
public void Dispose()
{
goo.Dispose();
}
}", codeAction: ("False;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 2));
}
[WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableExplicitly_NoNamespaceImportForSystem()
{
await new VerifyCS.Test
{
TestCode = @"class C : {|CS0535:System.IDisposable|}{|CS1513:|}{|CS1514:|}",
FixedCode = $@"class C : System.IDisposable
{{
private bool disposedValue;
{DisposePattern("protected virtual ", "C", "void System.IDisposable.", gcPrefix: "System.")}
}}
",
CodeActionEquivalenceKey = "True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;",
CodeActionIndex = 3,
// 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected
CodeActionValidationMode = CodeActionValidationMode.None,
}.RunAsync();
}
[WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableViaBaseInterface_NoDisposePattern()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I : IDisposable
{
void F();
}
class C : {|CS0535:{|CS0535:I|}|}
{
}",
@"using System;
interface I : IDisposable
{
void F();
}
class C : I
{
public void Dispose()
{
throw new NotImplementedException();
}
public void F()
{
throw new NotImplementedException();
}
}", codeAction: ("False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0));
}
[WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableViaBaseInterface()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I : IDisposable
{
void F();
}
class C : {|CS0535:{|CS0535:I|}|}
{
}",
$@"using System;
interface I : IDisposable
{{
void F();
}}
class C : I
{{
private bool disposedValue;
public void F()
{{
throw new NotImplementedException();
}}
{DisposePattern("protected virtual ", "C", "public void ")}
}}", codeAction: ("False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1));
}
[WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementIDisposableExplicitlyViaBaseInterface()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface I : IDisposable
{
void F();
}
class C : {|CS0535:{|CS0535:I|}|}
{
}",
$@"using System;
interface I : IDisposable
{{
void F();
}}
class C : I
{{
private bool disposedValue;
void I.F()
{{
throw new NotImplementedException();
}}
{DisposePattern("protected virtual ", "C", "void IDisposable.")}
}}", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3));
}
[WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDontImplementDisposePatternForLocallyDefinedIDisposable()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"namespace System
{
interface IDisposable
{
void Dispose();
}
class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}
}",
@"namespace System
{
interface IDisposable
{
void Dispose();
}
class C : IDisposable
{
void IDisposable.Dispose()
{
throw new NotImplementedException();
}
}
}", codeAction: ("True;False;False:global::System.IDisposable;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDontImplementDisposePatternForStructures1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
struct S : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
@"using System;
struct S : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDontImplementDisposePatternForStructures2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
struct S : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}",
@"using System;
struct S : IDisposable
{
void IDisposable.Dispose()
{
throw new NotImplementedException();
}
}
", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(545924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545924")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestEnumNestedInGeneric()
{
var test = new VerifyCS.Test()
{
TestCode = @"class C<T>
{
public enum E
{
X
}
}
interface I
{
void Goo<T>(C<T>.E x = C<T>.E.X);
}
class D : {|CS0535:I|}
{
}",
FixedCode = @"class C<T>
{
public enum E
{
X
}
}
interface I
{
void Goo<T>(C<T>.E x = C<T>.E.X);
}
class D : I
{
public void Goo<T>(C<T>.E x = C<T>.E.X)
{
throw new System.NotImplementedException();
}
}",
// 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected
CodeActionValidationMode = CodeActionValidationMode.None,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnterminatedString1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|} {|CS1039:|}@""{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IServiceProvider {|CS1003:@""""|}{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnterminatedString2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|} {|CS1010:|}""{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IServiceProvider {|CS1003:""""|}{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnterminatedString3()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|} {|CS1039:|}@""{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IServiceProvider {|CS1003:@""""|}{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnterminatedString4()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class C : {|CS0535:IServiceProvider|} {|CS1010:|}""{|CS1513:|}{|CS1514:|}",
@"using System;
class C : IServiceProvider {|CS1003:""""|}{
public object GetService(Type serviceType)
{
throw new NotImplementedException();
}
}
");
}
[WorkItem(545940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545940")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDecimalENotation()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void Goo1(decimal x = 1E-25M);
void Goo2(decimal x = -1E-25M);
void Goo3(decimal x = 1E-24M);
void Goo4(decimal x = -1E-24M);
}
class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|}
{
}",
@"interface I
{
void Goo1(decimal x = 1E-25M);
void Goo2(decimal x = -1E-25M);
void Goo3(decimal x = 1E-24M);
void Goo4(decimal x = -1E-24M);
}
class C : I
{
public void Goo1(decimal x = 0.0000000000000000000000001M)
{
throw new System.NotImplementedException();
}
public void Goo2(decimal x = -0.0000000000000000000000001M)
{
throw new System.NotImplementedException();
}
public void Goo3(decimal x = 0.000000000000000000000001M)
{
throw new System.NotImplementedException();
}
public void Goo4(decimal x = -0.000000000000000000000001M)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(545938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545938")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestGenericEnumWithRenamedTypeParameters()
{
var test = new VerifyCS.Test
{
TestCode = @"class C<T>
{
public enum E
{
X
}
}
interface I<S>
{
void Goo<T>(S y, C<T>.E x = C<T>.E.X);
}
class D<T> : {|CS0535:I<T>|}
{
}",
FixedCode = @"class C<T>
{
public enum E
{
X
}
}
interface I<S>
{
void Goo<T>(S y, C<T>.E x = C<T>.E.X);
}
class D<T> : I<T>
{
public void Goo<T1>(T y, C<T1>.E x = C<T1>.E.X)
{
throw new System.NotImplementedException();
}
}",
// 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected
CodeActionValidationMode = CodeActionValidationMode.None,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[WorkItem(545919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545919")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDoNotRenameTypeParameterToParameterName()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<S>
{
void Goo<T>(S T1);
}
class C<T> : {|CS0535:I<T>|}
{
}",
@"interface I<S>
{
void Goo<T>(S T1);
}
class C<T> : I<T>
{
public void Goo<T2>(T T1)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(530265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530265")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestAttributes()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.U1)]
bool Goo([MarshalAs(UnmanagedType.U1)] bool x);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.U1)]
bool Goo([MarshalAs(UnmanagedType.U1)] bool x);
}
class C : I
{
[return: MarshalAs(UnmanagedType.U1)]
public bool Goo([MarshalAs(UnmanagedType.U1)] bool x)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(530265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530265")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestAttributesExplicit()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.U1)]
bool Goo([MarshalAs(UnmanagedType.U1)] bool x);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.U1)]
bool Goo([MarshalAs(UnmanagedType.U1)] bool x);
}
class C : I
{
bool I.Goo(bool x)
{
throw new System.NotImplementedException();
}
}",
codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(546443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546443")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestParameterNameWithTypeName()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
interface IGoo
{
void Bar(DateTime DateTime);
}
class C : {|CS0535:IGoo|}
{
}",
@"using System;
interface IGoo
{
void Bar(DateTime DateTime);
}
class C : IGoo
{
public void Bar(DateTime DateTime)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(530521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530521")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnboundGeneric()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Collections.Generic;
using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))]
void Goo();
}
class C : {|CS0535:I|}
{
}",
@"using System.Collections.Generic;
using System.Runtime.InteropServices;
interface I
{
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))]
void Goo();
}
class C : I
{
[return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))]
public void Goo()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(752436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752436")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestQualifiedNameImplicitInterface()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"namespace N
{
public interface I
{
void M();
}
}
class C : {|CS0535:N.I|}
{
}",
@"namespace N
{
public interface I
{
void M();
}
}
class C : N.I
{
public void M()
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(752436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752436")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestQualifiedNameExplicitInterface()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"namespace N
{
public interface I
{
void M();
}
}
class C : {|CS0535:N.I|}
{
}",
@"using N;
namespace N
{
public interface I
{
void M();
}
}
class C : N.I
{
void I.M()
{
throw new System.NotImplementedException();
}
}", codeAction: ("True;False;False:global::N.I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForPartialType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface I
{
void Goo();
}
partial class C
{
}
partial class C : {|CS0535:I|}
{
}",
@"public interface I
{
void Goo();
}
partial class C
{
}
partial class C : I
{
void I.Goo()
{
throw new System.NotImplementedException();
}
}", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForPartialType2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"public interface I
{
void Goo();
}
partial class C : {|CS0535:I|}
{
}
partial class C
{
}",
@"public interface I
{
void Goo();
}
partial class C : I
{
void I.Goo()
{
throw new System.NotImplementedException();
}
}
partial class C
{
}", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForPartialType3()
{
await new VerifyCS.Test
{
TestCode = @"public interface I
{
void Goo();
}
public interface I2
{
void Goo2();
}
partial class C : {|CS0535:I|}
{
}
partial class C : {|CS0535:I2|}
{
}",
FixedState =
{
Sources =
{
@"public interface I
{
void Goo();
}
public interface I2
{
void Goo2();
}
partial class C : I
{
void I.Goo()
{
throw new System.NotImplementedException();
}
}
partial class C : {|CS0535:I2|}
{
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(752447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752447")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestExplicitImplOfIndexedProperty()
{
var test = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class Test : {|CS0535:{|CS0535:IGoo|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1", LanguageNames.VisualBasic] =
{
Sources =
{
@"
Public Interface IGoo
Property IndexProp(ByVal p1 As Integer) As String
End Interface",
},
},
},
AdditionalProjectReferences =
{
"Assembly1",
},
},
FixedState =
{
Sources =
{
@"
public class Test : IGoo
{
string IGoo.get_IndexProp(int p1)
{
throw new System.NotImplementedException();
}
void IGoo.set_IndexProp(int p1, string Value)
{
throw new System.NotImplementedException();
}
}",
},
},
CodeActionEquivalenceKey = "True;False;False:global::IGoo;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
[WorkItem(602475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602475")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplicitImplOfIndexedProperty()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"using System;
class C : {|CS0535:{|CS0535:I|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1", LanguageNames.VisualBasic] =
{
Sources =
{
@"Public Interface I
Property P(x As Integer)
End Interface",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"using System;
class C : I
{
public object get_P(int x)
{
throw new NotImplementedException();
}
public void set_P(int x, object Value)
{
throw new NotImplementedException();
}
}",
},
},
CodeActionEquivalenceKey = "False;False;True:global::I;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementationOfIndexerWithInaccessibleAttributes()
{
var test = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
using System;
class C : {|CS0535:I|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"
using System;
internal class ShouldBeRemovedAttribute : Attribute { }
public interface I
{
string this[[ShouldBeRemovedAttribute] int i] { get; set; }
}"
},
},
},
AdditionalProjectReferences =
{
"Assembly1",
},
},
FixedState =
{
Sources =
{
@"
using System;
class C : I
{
public string this[int i]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}",
},
},
CodeActionEquivalenceKey = "False;False;True:global::I;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
};
test.Options.AddRange(AllOptionsOff);
await test.RunAsync();
}
#if false
[WorkItem(13677)]
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoGenerateInVenusCase2()
{
await TestMissingAsync(
@"using System;
#line 1 ""Bar""
class Goo : [|IComparable|]
#line default
#line hidden");
}
#endif
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForImplicitIDisposable()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class Program : {|CS0535:IDisposable|}
{
}",
$@"using System;
class Program : IDisposable
{{
private bool disposedValue;
{DisposePattern("protected virtual ", "Program", "public void ")}
}}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForExplicitIDisposable()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class Program : {|CS0535:IDisposable|}
{
private bool DisposedValue;
}",
$@"using System;
class Program : IDisposable
{{
private bool DisposedValue;
private bool disposedValue;
{DisposePattern("protected virtual ", "Program", "void IDisposable.")}
}}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForIDisposableNonApplicable1()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class Program : {|CS0535:IDisposable|}
{
private bool disposedValue;
}",
@"using System;
class Program : IDisposable
{
private bool disposedValue;
public void Dispose()
{
throw new NotImplementedException();
}
}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForIDisposableNonApplicable2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class Program : {|CS0535:IDisposable|}
{
public void Dispose(bool flag)
{
}
}",
@"using System;
class Program : IDisposable
{
public void Dispose(bool flag)
{
}
public void Dispose()
{
throw new NotImplementedException();
}
}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForExplicitIDisposableWithSealedClass()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
sealed class Program : {|CS0535:IDisposable|}
{
}",
$@"using System;
sealed class Program : IDisposable
{{
private bool disposedValue;
{DisposePattern("private ", "Program", "void IDisposable.")}
}}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3));
}
[WorkItem(9760, "https://github.com/dotnet/roslyn/issues/9760")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceForExplicitIDisposableWithExistingField()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
class Program : {|CS0535:IDisposable|}
{
private bool disposedValue;
}",
$@"using System;
class Program : IDisposable
{{
private bool disposedValue;
private bool disposedValue1;
{DisposePattern("protected virtual ", "Program", "public void ", disposeField: "disposedValue1")}
}}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1));
}
[WorkItem(9760, "https://github.com/dotnet/roslyn/issues/9760")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceUnderscoreNameForFields()
{
await new VerifyCS.Test
{
TestCode = @"using System;
class Program : {|CS0535:IDisposable|}
{
}",
FixedCode = $@"using System;
class Program : IDisposable
{{
private bool _disposedValue;
{DisposePattern("protected virtual ", "Program", "public void ", disposeField: "_disposedValue")}
}}",
Options =
{
_options.FieldNamesAreCamelCaseWithUnderscorePrefix,
},
CodeActionEquivalenceKey = "False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoComAliasNameAttributeOnMethodParameters()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
void M([System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p);
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
void M([System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p);
}
class C : I
{
public void M(int p)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoComAliasNameAttributeOnMethodReturnType()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System.Runtime.InteropServices;
interface I
{
[return: ComAliasName(""pAlias1"")]
long M([ComAliasName(""pAlias2"")] int p);
}
class C : {|CS0535:I|}
{
}",
@"using System.Runtime.InteropServices;
interface I
{
[return: ComAliasName(""pAlias1"")]
long M([ComAliasName(""pAlias2"")] int p);
}
class C : I
{
public long M(int p)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNoComAliasNameAttributeOnIndexerParameters()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I
{
long this[[System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p] { get; }
}
class C : {|CS0535:I|}
{
}",
@"interface I
{
long this[[System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p] { get; }
}
class C : I
{
public long this[int p]
{
get
{
throw new System.NotImplementedException();
}
}
}");
}
[WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestMissingOpenBrace()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"namespace Scenarios
{
public interface TestInterface
{
void M1();
}
struct TestStruct1 : {|CS0535:TestInterface|}{|CS1513:|}{|CS1514:|}
// Comment
}",
@"namespace Scenarios
{
public interface TestInterface
{
void M1();
}
struct TestStruct1 : TestInterface
{
public void M1()
{
throw new System.NotImplementedException();
}
}
// Comment
}");
}
[WorkItem(994328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced1()
{
//CSharpFeaturesResources.DisposePattern
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T
{
System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c);
System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT;
}
partial class C
{
}
partial class C : {|CS0535:{|CS0535:{|CS0535:I<System.Exception, System.AggregateException>|}|}|}, {|CS0535:System.IDisposable|}
{
}",
$@"using System;
using System.Collections.Generic;
interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T
{{
System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c);
System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT;
}}
partial class C
{{
}}
partial class C : I<System.Exception, System.AggregateException>, System.IDisposable
{{
private bool disposedValue;
public bool Equals(int other)
{{
throw new NotImplementedException();
}}
public List<AggregateException> M(Dictionary<Exception, List<AggregateException>> a, Exception b, AggregateException c)
{{
throw new NotImplementedException();
}}
public List<UU> M<TT, UU>(Dictionary<TT, List<UU>> a, TT b, UU c) where UU : TT
{{
throw new NotImplementedException();
}}
{DisposePattern("protected virtual ", "C", "public void ")}
}}", codeAction: ("False;False;True:global::I<global::System.Exception, global::System.AggregateException>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1));
}
[WorkItem(994328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced2()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T
{
System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c);
System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT;
}
partial class C : {|CS0535:{|CS0535:{|CS0535:I<System.Exception, System.AggregateException>|}|}|}, {|CS0535:System.IDisposable|}
{
}
partial class C
{
}",
$@"using System;
using System.Collections.Generic;
interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T
{{
System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c);
System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT;
}}
partial class C : I<System.Exception, System.AggregateException>, System.IDisposable
{{
private bool disposedValue;
bool IEquatable<int>.Equals(int other)
{{
throw new NotImplementedException();
}}
List<AggregateException> I<Exception, AggregateException>.M(Dictionary<Exception, List<AggregateException>> a, Exception b, AggregateException c)
{{
throw new NotImplementedException();
}}
List<UU> I<Exception, AggregateException>.M<TT, UU>(Dictionary<TT, List<UU>> a, TT b, UU c)
{{
throw new NotImplementedException();
}}
{DisposePattern("protected virtual ", "C", "void IDisposable.")}
}}
partial class C
{{
}}", codeAction: ("True;False;False:global::I<global::System.Exception, global::System.AggregateException>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3));
}
private static string DisposePattern(
string disposeVisibility,
string className,
string implementationVisibility,
string disposeField = "disposedValue",
string gcPrefix = "")
{
return $@" {disposeVisibility}void Dispose(bool disposing)
{{
if (!{disposeField})
{{
if (disposing)
{{
// {FeaturesResources.TODO_colon_dispose_managed_state_managed_objects}
}}
// {FeaturesResources.TODO_colon_free_unmanaged_resources_unmanaged_objects_and_override_finalizer}
// {FeaturesResources.TODO_colon_set_large_fields_to_null}
{disposeField} = true;
}}
}}
// // {string.Format(FeaturesResources.TODO_colon_override_finalizer_only_if_0_has_code_to_free_unmanaged_resources, "Dispose(bool disposing)")}
// ~{className}()
// {{
// // {string.Format(FeaturesResources.Do_not_change_this_code_Put_cleanup_code_in_0_method, "Dispose(bool disposing)")}
// Dispose(disposing: false);
// }}
{implementationVisibility}Dispose()
{{
// {string.Format(FeaturesResources.Do_not_change_this_code_Put_cleanup_code_in_0_method, "Dispose(bool disposing)")}
Dispose(disposing: true);
{gcPrefix}GC.SuppressFinalize(this);
}}";
}
[WorkItem(1132014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1132014")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleAttributes()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
public class Goo : {|CS0535:Holder.SomeInterface|}
{
}
public class Holder
{
public interface SomeInterface
{
void Something([SomeAttribute] string helloWorld);
}
private class SomeAttribute : Attribute
{
}
}",
@"using System;
public class Goo : Holder.SomeInterface
{
public void Something(string helloWorld)
{
throw new NotImplementedException();
}
}
public class Holder
{
public interface SomeInterface
{
void Something([SomeAttribute] string helloWorld);
}
private class SomeAttribute : Attribute
{
}
}");
}
[WorkItem(2785, "https://github.com/dotnet/roslyn/issues/2785")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementInterfaceThroughStaticMemberInGenericClass()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Issue2785<T> : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:IList<object>|}|}|}|}|}|}|}|}|}|}|}|}|}
{
private static List<object> innerList = new List<object>();
}",
@"using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Issue2785<T> : IList<object>
{
private static List<object> innerList = new List<object>();
public object this[int index]
{
get
{
return ((IList<object>)innerList)[index];
}
set
{
((IList<object>)innerList)[index] = value;
}
}
public int Count
{
get
{
return ((ICollection<object>)innerList).Count;
}
}
public bool IsReadOnly
{
get
{
return ((ICollection<object>)innerList).IsReadOnly;
}
}
public void Add(object item)
{
((ICollection<object>)innerList).Add(item);
}
public void Clear()
{
((ICollection<object>)innerList).Clear();
}
public bool Contains(object item)
{
return ((ICollection<object>)innerList).Contains(item);
}
public void CopyTo(object[] array, int arrayIndex)
{
((ICollection<object>)innerList).CopyTo(array, arrayIndex);
}
public IEnumerator<object> GetEnumerator()
{
return ((IEnumerable<object>)innerList).GetEnumerator();
}
public int IndexOf(object item)
{
return ((IList<object>)innerList).IndexOf(item);
}
public void Insert(int index, object item)
{
((IList<object>)innerList).Insert(index, item);
}
public bool Remove(object item)
{
return ((ICollection<object>)innerList).Remove(item);
}
public void RemoveAt(int index)
{
((IList<object>)innerList).RemoveAt(index);
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)innerList).GetEnumerator();
}
}",
codeAction: ("False;False;False:global::System.Collections.Generic.IList<object>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;innerList", 1));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)]
public async Task LongTuple()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
(int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y);
}
class Class : {|CS0535:IInterface|}
{
(int, string) x;
}",
@"interface IInterface
{
(int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y);
}
class Class : IInterface
{
(int, string) x;
public (int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task LongTupleWithNames()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface
{
(int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y);
}
class Class : {|CS0535:IInterface|}
{
(int, string) x;
}",
@"interface IInterface
{
(int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y);
}
class Class : IInterface
{
(int, string) x;
public (int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task GenericWithTuple()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface<TA, TB>
{
(TA, TB) Method1((TA, TB) y);
}
class Class : {|CS0535:IInterface<(int, string), int>|}
{
(int, string) x;
}",
@"interface IInterface<TA, TB>
{
(TA, TB) Method1((TA, TB) y);
}
class Class : IInterface<(int, string), int>
{
(int, string) x;
public ((int, string), int) Method1(((int, string), int) y)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task GenericWithTupleWithNamess()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"interface IInterface<TA, TB>
{
(TA a, TB b) Method1((TA a, TB b) y);
}
class Class : {|CS0535:IInterface<(int, string), int>|}
{
(int, string) x;
}",
@"interface IInterface<TA, TB>
{
(TA a, TB b) Method1((TA a, TB b) y);
}
class Class : IInterface<(int, string), int>
{
(int, string) x;
public ((int, string) a, int b) Method1(((int, string) a, int b) y)
{
throw new System.NotImplementedException();
}
}");
}
[WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithGroupingOff1()
{
await new VerifyCS.Test
{
TestCode = @"interface IInterface
{
int Prop { get; }
}
class Class : {|CS0535:IInterface|}
{
void M() { }
}",
FixedCode = @"interface IInterface
{
int Prop { get; }
}
class Class : IInterface
{
void M() { }
public int Prop => throw new System.NotImplementedException();
}",
Options =
{
{ ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd },
},
}.RunAsync();
}
[WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDoNotReorderComImportMembers_01()
{
await TestInRegularAndScriptAsync(
@"
using System.Runtime.InteropServices;
[ComImport]
[Guid(""00000000-0000-0000-0000-000000000000"")]
interface IComInterface
{
void MOverload();
void X();
void MOverload(int i);
int Prop { get; }
}
class Class : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IComInterface|}|}|}|}
{
}",
@"
using System.Runtime.InteropServices;
[ComImport]
[Guid(""00000000-0000-0000-0000-000000000000"")]
interface IComInterface
{
void MOverload();
void X();
void MOverload(int i);
int Prop { get; }
}
class Class : IComInterface
{
public void MOverload()
{
throw new System.NotImplementedException();
}
public void X()
{
throw new System.NotImplementedException();
}
public void MOverload(int i)
{
throw new System.NotImplementedException();
}
public int Prop => throw new System.NotImplementedException();
}");
}
[WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDoNotReorderComImportMembers_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode =
@"
using System.Runtime.InteropServices;
[ComImport]
[Guid(""00000000-0000-0000-0000-000000000000"")]
interface IComInterface
{
void MOverload() { }
void X() { }
void MOverload(int i) { }
int Prop { get; }
}
class Class : {|CS0535:IComInterface|}
{
}",
FixedCode =
@"
using System.Runtime.InteropServices;
[ComImport]
[Guid(""00000000-0000-0000-0000-000000000000"")]
interface IComInterface
{
void MOverload() { }
void X() { }
void MOverload(int i) { }
int Prop { get; }
}
class Class : IComInterface
{
public int Prop => throw new System.NotImplementedException();
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRefReturns()
{
await TestInRegularAndScriptAsync(
@"
using System;
interface I {
ref int IGoo();
ref int Goo { get; }
ref int this[int i] { get; }
}
class C : {|CS0535:{|CS0535:{|CS0535:I|}|}|}
{
}",
@"
using System;
interface I {
ref int IGoo();
ref int Goo { get; }
ref int this[int i] { get; }
}
class C : I
{
public ref int this[int i] => throw new NotImplementedException();
public ref int Goo => throw new NotImplementedException();
public ref int IGoo()
{
throw new NotImplementedException();
}
}");
}
[WorkItem(13932, "https://github.com/dotnet/roslyn/issues/13932")]
[WorkItem(5898, "https://github.com/dotnet/roslyn/issues/5898")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestAutoProperties()
{
await new VerifyCS.Test()
{
TestCode = @"interface IInterface
{
int ReadOnlyProp { get; }
int ReadWriteProp { get; set; }
int WriteOnlyProp { set; }
}
class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
FixedCode = @"interface IInterface
{
int ReadOnlyProp { get; }
int ReadWriteProp { get; set; }
int WriteOnlyProp { set; }
}
class Class : IInterface
{
public int ReadOnlyProp { get; }
public int ReadWriteProp { get; set; }
public int WriteOnlyProp { set => throw new System.NotImplementedException(); }
}",
Options =
{
{ ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties },
},
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestOptionalParameterWithDefaultLiteral()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp7_1,
TestCode = @"
using System.Threading;
interface IInterface
{
void Method1(CancellationToken cancellationToken = default(CancellationToken));
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"
using System.Threading;
interface IInterface
{
void Method1(CancellationToken cancellationToken = default(CancellationToken));
}
class Class : IInterface
{
public void Method1(CancellationToken cancellationToken = default)
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInWithMethod_Parameters()
{
await TestInRegularAndScriptAsync(
@"interface ITest
{
void Method(in int p);
}
public class Test : {|CS0535:ITest|}
{
}",
@"interface ITest
{
void Method(in int p);
}
public class Test : ITest
{
public void Method(in int p)
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRefReadOnlyWithMethod_ReturnType()
{
await TestInRegularAndScriptAsync(
@"interface ITest
{
ref readonly int Method();
}
public class Test : {|CS0535:ITest|}
{
}",
@"interface ITest
{
ref readonly int Method();
}
public class Test : ITest
{
public ref readonly int Method()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRefReadOnlyWithProperty()
{
await TestInRegularAndScriptAsync(
@"interface ITest
{
ref readonly int Property { get; }
}
public class Test : {|CS0535:ITest|}
{
}",
@"interface ITest
{
ref readonly int Property { get; }
}
public class Test : ITest
{
public ref readonly int Property => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInWithIndexer_Parameters()
{
await TestInRegularAndScriptAsync(
@"interface ITest
{
int this[in int p] { set; }
}
public class Test : {|CS0535:ITest|}
{
}",
@"interface ITest
{
int this[in int p] { set; }
}
public class Test : ITest
{
public int this[in int p] { set => throw new System.NotImplementedException(); }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestRefReadOnlyWithIndexer_ReturnType()
{
await TestInRegularAndScriptAsync(
@"interface ITest
{
ref readonly int this[int p] { get; }
}
public class Test : {|CS0535:ITest|}
{
}",
@"interface ITest
{
ref readonly int this[int p] { get; }
}
public class Test : ITest
{
public ref readonly int this[int p] => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnmanagedConstraint()
{
await TestInRegularAndScriptAsync(
@"public interface ITest
{
void M<T>() where T : unmanaged;
}
public class Test : {|CS0535:ITest|}
{
}",
@"public interface ITest
{
void M<T>() where T : unmanaged;
}
public class Test : ITest
{
public void M<T>() where T : unmanaged
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestSealedMember_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestSealedMember_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
class Class : IInterface
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestSealedMember_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
abstract class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
sealed void M1() {}
sealed int P1 => 1;
}
abstract class Class : IInterface
{
public abstract void Method1();
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicMember_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
protected void M1();
protected int P1 {get;}
}
class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
void Method1();
protected void M1();
protected int P1 {get;}
}
class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;False;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicMember_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
protected void M1();
protected int P1 {get;}
}
class Class : {|CS0535:{|CS0535:IInterface|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
protected void M1();
protected int P1 {get;}
}
class Class : IInterface
{
int IInterface.P1
{
get
{
throw new System.NotImplementedException();
}
}
void IInterface.M1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
DiagnosticSelector = diagnostics => diagnostics[1],
CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne,
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicMember_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
protected void M1();
protected int P1 {get;}
}
abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
void Method1();
protected void M1();
protected int P1 {get;}
}
abstract class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public abstract void Method1();
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicAccessor_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
int P1 {get; protected set;}
int P2 {protected get; set;}
}
class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
void Method1();
int P1 {get; protected set;}
int P2 {protected get; set;}
}
class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;False;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicAccessor_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
int P1 {get; protected set;}
int P2 {protected get; set;}
}
class Class : {|CS0535:{|CS0535:IInterface|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
int P1 {get; protected set;}
int P2 {protected get; set;}
}
class Class : IInterface
{
int IInterface.P1
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
int IInterface.P2
{
get
{
throw new System.NotImplementedException();
}
set
{
throw new System.NotImplementedException();
}
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNonPublicAccessor_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
int P1 {get; protected set;}
int P2 {protected get; set;}
}
abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
FixedState =
{
Sources =
{
@"interface IInterface
{
void Method1();
int P1 {get; protected set;}
int P2 {protected get; set;}
}
abstract class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public abstract void Method1();
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestPrivateAccessor_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestPrivateAccessor_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
class Class : IInterface
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestPrivateAccessor_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
abstract class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
int P1 {get => 0; private set {}}
int P2 {private get => 0; set {}}
}
abstract class Class : IInterface
{
public abstract void Method1();
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleMember_01()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
internal void M1();
internal int P1 {get;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
// Specify the code action by equivalence key only to avoid trying to implement the interface explicitly with a second code fix pass.
CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleMember_02()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
internal void M1();
internal int P1 {get;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:IInterface|}|}
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleMember_03()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
internal void M1();
internal int P1 {get;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"abstract class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public abstract void Method1();
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
// Specify the code action by equivalence key only to avoid trying to execute a second code fix pass with a different action
CodeActionEquivalenceKey = "False;True;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleAccessor_01()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
int P1 {get; internal set;}
int P2 {internal get; set;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
// Specify the code action by equivalence key only to avoid trying to implement the interface explicitly with a second code fix pass.
CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleAccessor_02()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
int P1 {get; internal set;}
int P2 {internal get; set;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"class Class : {|CS0535:{|CS0535:IInterface|}|}
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestInaccessibleAccessor_03()
{
await new VerifyCS.Test
{
TestState =
{
Sources =
{
@"abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|}
{
}",
},
AdditionalProjects =
{
["Assembly1"] =
{
Sources =
{
@"public interface IInterface
{
void Method1();
int P1 {get; internal set;}
int P2 {internal get; set;}
}",
},
},
},
AdditionalProjectReferences = { "Assembly1" },
},
FixedState =
{
Sources =
{
@"abstract class Class : {|CS0535:{|CS0535:IInterface|}|}
{
public abstract void Method1();
}",
},
MarkupHandling = MarkupMode.Allow,
},
Options = { AllOptionsOff },
// Specify the code action by equivalence key only to avoid trying to execute a second code fix pass with a different action
CodeActionEquivalenceKey = "False;True;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestVirtualMember_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestVirtualMember_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
class Class : IInterface
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestVirtualMember_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
abstract class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
virtual void M1() {}
virtual int P1 => 1;
}
abstract class Class : IInterface
{
public abstract void Method1();
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticMember_01()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
class Class : IInterface
{
public void Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticMember_02()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
class Class : IInterface
{
void IInterface.Method1()
{
throw new System.NotImplementedException();
}
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticMember_03()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
abstract class Class : {|CS0535:IInterface|}
{
}",
FixedCode = @"interface IInterface
{
void Method1();
static void M1() {}
static int P1 => 1;
static int F1;
public abstract class C {}
}
abstract class Class : IInterface
{
public abstract void Method1();
}",
Options = { AllOptionsOff },
CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestNotNullConstraint()
{
await TestInRegularAndScriptAsync(
@"public interface ITest
{
void M<T>() where T : notnull;
}
public class Test : {|CS0535:ITest|}
{
}",
@"public interface ITest
{
void M<T>() where T : notnull;
}
public class Test : ITest
{
public void M<T>() where T : notnull
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullableProperty()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
public interface ITest
{
string? P { get; }
}
public class Test : {|CS0535:ITest|}
{
}",
@"#nullable enable
public interface ITest
{
string? P { get; }
}
public class Test : ITest
{
public string? P => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullablePropertyAlreadyImplemented()
{
var code =
@"#nullable enable
public interface ITest
{
string? P { get; }
}
public class Test : ITest
{
public string? P => throw new System.NotImplementedException();
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullableMethod()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
public interface ITest
{
string? P();
}
public class Test : {|CS0535:ITest|}
{
}",
@"#nullable enable
public interface ITest
{
string? P();
}
public class Test : ITest
{
public string? P()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullableEvent()
{
// Question whether this is needed,
// see https://github.com/dotnet/roslyn/issues/36673
await TestInRegularAndScriptAsync(
@"#nullable enable
using System;
public interface ITest
{
event EventHandler? SomeEvent;
}
public class Test : {|CS0535:ITest|}
{
}",
@"#nullable enable
using System;
public interface ITest
{
event EventHandler? SomeEvent;
}
public class Test : ITest
{
public event EventHandler? SomeEvent;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestWithNullableDisabled()
{
await TestInRegularAndScriptAsync(
@"#nullable enable
public interface ITest
{
string? P { get; }
}
#nullable disable
public class Test : {|CS0535:ITest|}
{
}",
@"#nullable enable
public interface ITest
{
string? P { get; }
}
#nullable disable
public class Test : ITest
{
public string P => throw new System.NotImplementedException();
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task GenericInterfaceNotNull1()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"#nullable enable
using System.Diagnostics.CodeAnalysis;
interface IFoo<T>
{
[return: NotNull]
T Bar([DisallowNull] T bar);
[return: MaybeNull]
T Baz([AllowNull] T bar);
}
class A : {|CS0535:{|CS0535:IFoo<int>|}|}
{
}",
FixedCode = @"#nullable enable
using System.Diagnostics.CodeAnalysis;
interface IFoo<T>
{
[return: NotNull]
T Bar([DisallowNull] T bar);
[return: MaybeNull]
T Baz([AllowNull] T bar);
}
class A : IFoo<int>
{
[return: NotNull]
public int Bar([DisallowNull] int bar)
{
throw new System.NotImplementedException();
}
[return: MaybeNull]
public int Baz([AllowNull] int bar)
{
throw new System.NotImplementedException();
}
}",
}.RunAsync();
}
[WorkItem(13427, "https://github.com/dotnet/roslyn/issues/13427")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestDoNotAddNewWithGenericAndNonGenericMethods()
{
await TestWithAllCodeStyleOptionsOffAsync(
@"class B
{
public void M<T>() { }
}
interface I
{
void M();
}
class D : B, {|CS0535:I|}
{
}",
@"class B
{
public void M<T>() { }
}
interface I
{
void M();
}
class D : B, I
{
public void M()
{
throw new System.NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task ImplementRemainingExplicitlyWhenPartiallyImplemented()
{
await TestInRegularAndScriptAsync(@"
interface I
{
void M1();
void M2();
}
class C : {|CS0535:I|}
{
public void M1(){}
}",
@"
interface I
{
void M1();
void M2();
}
class C : {|CS0535:I|}
{
public void M1(){}
void I.M2()
{
throw new System.NotImplementedException();
}
}", codeAction: ("True;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task ImplementInitOnlyProperty()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"
interface I
{
int Property { get; init; }
}
class C : {|CS0535:I|}
{
}",
FixedCode = @"
interface I
{
int Property { get; init; }
}
class C : I
{
public int Property { get => throw new System.NotImplementedException(); init => throw new System.NotImplementedException(); }
}",
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task ImplementRemainingExplicitlyMissingWhenAllImplemented()
{
var code = @"
interface I
{
void M1();
void M2();
}
class C : I
{
public void M1(){}
public void M2(){}
}";
await VerifyCS.VerifyCodeFixAsync(code, code);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task ImplementRemainingExplicitlyMissingWhenAllImplementedAreExplicit()
{
var code = @"
interface I
{
void M1();
void M2();
}
class C : {|CS0535:I|}
{
void I.M1(){}
}";
var fixedCode = @"
interface I
{
void M1();
void M2();
}
class C : I
{
public void M2()
{
throw new System.NotImplementedException();
}
void I.M1(){}
}";
await new VerifyCS.Test
{
TestCode = code,
FixedCode = fixedCode,
CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length),
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementRemainingExplicitlyNonPublicMember()
{
await TestInRegularAndScriptAsync(@"
interface I
{
void M1();
internal void M2();
}
class C : {|CS0535:I|}
{
public void M1(){}
}",
@"
interface I
{
void M1();
internal void M2();
}
class C : {|CS0535:I|}
{
public void M1(){}
void I.M2()
{
throw new System.NotImplementedException();
}
}", codeAction: ("True;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1));
}
[WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementOnRecord_WithSemiColon()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface I
{
void M1();
}
record C : {|CS0535:I|};
",
FixedCode = @"
interface I
{
void M1();
}
record C : {|CS0535:I|}
{
public void M1()
{
throw new System.NotImplementedException();
}
}
",
}.RunAsync();
}
[WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementOnRecord_WithBracesAndTrivia()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface I
{
void M1();
}
record C : {|CS0535:I|} { } // hello
",
FixedCode = @"
interface I
{
void M1();
}
record C : {|CS0535:I|}
{
public void M1()
{
throw new System.NotImplementedException();
}
} // hello
",
}.RunAsync();
}
[WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")]
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
[InlineData("record")]
[InlineData("record class")]
[InlineData("record struct")]
public async Task TestImplementOnRecord_WithSemiColonAndTrivia(string record)
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = $@"
interface I
{{
void M1();
}}
{record} C : {{|CS0535:I|}}; // hello
",
FixedCode = $@"
interface I
{{
void M1();
}}
{record} C : {{|CS0535:I|}} // hello
{{
public void M1()
{{
throw new System.NotImplementedException();
}}
}}
",
}.RunAsync();
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnconstrainedGenericInstantiatedWithValueType()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"#nullable enable
interface IGoo<T>
{
void Bar(T? x);
}
class C : {|CS0535:IGoo<int>|}
{
}
",
FixedCode = @"#nullable enable
interface IGoo<T>
{
void Bar(T? x);
}
class C : IGoo<int>
{
public void Bar(int x)
{
throw new System.NotImplementedException();
}
}
",
}.RunAsync();
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConstrainedGenericInstantiatedWithValueType()
{
await TestInRegularAndScriptAsync(@"
interface IGoo<T> where T : struct
{
void Bar(T? x);
}
class C : {|CS0535:IGoo<int>|}
{
}
",
@"
interface IGoo<T> where T : struct
{
void Bar(T? x);
}
class C : IGoo<int>
{
public void Bar(int? x)
{
throw new System.NotImplementedException();
}
}
");
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnconstrainedGenericInstantiatedWithReferenceType()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"
interface IGoo<T>
{
#nullable enable
void Bar(T? x);
#nullable restore
}
class C : {|CS0535:IGoo<string>|}
{
}
",
FixedCode = @"
interface IGoo<T>
{
#nullable enable
void Bar(T? x);
#nullable restore
}
class C : IGoo<string>
{
public void Bar(string x)
{
throw new System.NotImplementedException();
}
}
",
}.RunAsync();
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestUnconstrainedGenericInstantiatedWithReferenceType_NullableEnable()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"
#nullable enable
interface IGoo<T>
{
void Bar(T? x);
}
class C : {|CS0535:IGoo<string>|}
{
}
",
FixedCode = @"
#nullable enable
interface IGoo<T>
{
void Bar(T? x);
}
class C : IGoo<string>
{
public void Bar(string? x)
{
throw new System.NotImplementedException();
}
}
",
}.RunAsync();
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConstrainedGenericInstantiatedWithReferenceType()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp9,
TestCode = @"
#nullable enable
interface IGoo<T> where T : class
{
void Bar(T? x);
}
class C : {|CS0535:IGoo<string>|}
{
}
",
FixedCode = @"
#nullable enable
interface IGoo<T> where T : class
{
void Bar(T? x);
}
class C : IGoo<string>
{
public void Bar(string? x)
{
throw new System.NotImplementedException();
}
}
",
}.RunAsync();
}
[WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestConstrainedGenericInstantiatedWithReferenceType_NullableEnable()
{
await TestInRegularAndScriptAsync(@"
#nullable enable
interface IGoo<T> where T : class
{
void Bar(T? x);
}
class C : {|CS0535:IGoo<string>|}
{
}
",
@"
#nullable enable
interface IGoo<T> where T : class
{
void Bar(T? x);
}
class C : IGoo<string>
{
public void Bar(string? x)
{
throw new System.NotImplementedException();
}
}
");
}
[WorkItem(51779, "https://github.com/dotnet/roslyn/issues/51779")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestImplementTwoPropertiesOfCSharp5()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp5,
TestCode = @"
interface ITest
{
int Bar { get; }
int Foo { get; }
}
class Program : {|CS0535:{|CS0535:ITest|}|}
{
}
",
FixedCode = @"
interface ITest
{
int Bar { get; }
int Foo { get; }
}
class Program : ITest
{
public int Bar
{
get
{
throw new System.NotImplementedException();
}
}
public int Foo
{
get
{
throw new System.NotImplementedException();
}
}
}
",
}.RunAsync();
}
[WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceMember()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract void M1();
}
class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract void M1();
}
class C : ITest
{
public static void M1()
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title),
CodeActionEquivalenceKey = "False;False;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceMemberExplicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract void M1();
}
class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract void M1();
}
class C : ITest
{
static void ITest.M1()
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title),
CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceMember_ImplementAbstractly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract void M1();
}
abstract class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract void M1();
}
abstract class C : ITest
{
public static void M1()
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title),
CodeActionEquivalenceKey = "False;True;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceOperator_OnlyExplicitlyImplementable()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract int operator -(ITest x);
}
class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract int operator -(ITest x);
}
class C : ITest
{
static int ITest.operator -(ITest x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title),
CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceOperator_ImplementImplicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
static abstract int operator -(T x, int y);
}
class C : {|CS0535:{|CS0535:ITest<C>|}|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
static abstract int operator -(T x, int y);
}
class C : ITest<C>
{
public static int operator -(C x)
{
throw new System.NotImplementedException();
}
public static int operator -(C x, int y)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title),
CodeActionEquivalenceKey = "False;False;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceOperator_ImplementExplicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
}
class C : {|CS0535:ITest<C>|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
}
class C : ITest<C>
{
static int ITest<C>.operator -(C x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title),
CodeActionEquivalenceKey = "True;False;False:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterfaceOperator_ImplementAbstractly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
}
abstract class C : {|CS0535:ITest<C>|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int operator -(T x);
}
abstract class C : ITest<C>
{
public static int operator -(C x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title),
CodeActionEquivalenceKey = "False;True;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterface_Explicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract int M(ITest x);
}
class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract int M(ITest x);
}
class C : ITest
{
static int ITest.M(ITest x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title),
CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterface_Implicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest
{
static abstract int M(ITest x);
}
class C : {|CS0535:ITest|}
{
}
",
FixedCode = @"
interface ITest
{
static abstract int M(ITest x);
}
class C : ITest
{
public static int M(ITest x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title),
CodeActionEquivalenceKey = "False;False;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterface_ImplementImplicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
class C : {|CS0535:ITest<C>|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
class C : ITest<C>
{
public static int M(C x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title),
CodeActionEquivalenceKey = "False;False;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 0,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterface_ImplementExplicitly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
class C : {|CS0535:ITest<C>|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
class C : ITest<C>
{
static int ITest<C>.M(C x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title),
CodeActionEquivalenceKey = "True;False;False:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
[WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)]
public async Task TestStaticAbstractInterface_ImplementAbstractly()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
LanguageVersion = LanguageVersion.Preview,
TestCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
abstract class C : {|CS0535:ITest<C>|}
{
}
",
FixedCode = @"
interface ITest<T> where T : ITest<T>
{
static abstract int M(T x);
}
abstract class C : ITest<C>
{
public static int M(C x)
{
throw new System.NotImplementedException();
}
}
",
CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title),
CodeActionEquivalenceKey = "False;True;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;",
CodeActionIndex = 1,
}.RunAsync();
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Compilers/Core/CodeAnalysisTest/MetadataReferences/AssemblyIdentityTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using System.Reflection;
using System.Reflection.Metadata;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class AssemblyIdentityTests : AssemblyIdentityTestBase
{
[Fact]
public void Equality()
{
var id1 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false);
var id11 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false);
var id2 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var id22 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var id3 = new AssemblyIdentity("Goo!", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var id4 = new AssemblyIdentity("Goo", new Version(1, 0, 1, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var id5 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "en-US", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var id6 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", default(ImmutableArray<byte>), hasPublicKey: false, isRetargetable: false);
var id7 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: true);
var win1 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false, contentType: AssemblyContentType.WindowsRuntime);
var win2 = new AssemblyIdentity("Bar", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false, contentType: AssemblyContentType.WindowsRuntime);
var win3 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false, contentType: AssemblyContentType.WindowsRuntime);
Assert.True(id1.Equals(id1));
Assert.True(id1.Equals(id2));
Assert.True(id2.Equals(id1));
Assert.True(id1.Equals(id11));
Assert.True(id11.Equals(id1));
Assert.True(id2.Equals(id22));
Assert.True(id22.Equals(id2));
Assert.False(id1.Equals(id3));
Assert.False(id1.Equals(id4));
Assert.False(id1.Equals(id5));
Assert.False(id1.Equals(id6));
Assert.False(id1.Equals(id7));
Assert.Equal((object)id1, id1);
Assert.NotNull(id1);
Assert.False(id2.Equals((AssemblyIdentity)null));
Assert.Equal(id1.GetHashCode(), id2.GetHashCode());
Assert.False(win1.Equals(win2));
Assert.False(win1.Equals(id1));
Assert.True(win1.Equals(win3));
Assert.Equal(win1.GetHashCode(), win3.GetHashCode());
}
[Fact]
public void Equality_InvariantCulture()
{
var neutral1 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "NEUtral", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var neutral2 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), null, RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var neutral3 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "neutral", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var invariant = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
Assert.True(neutral1.Equals(invariant));
Assert.True(neutral2.Equals(invariant));
Assert.True(neutral3.Equals(invariant));
}
[Fact]
public void FromAssemblyDefinitionInvalidParameters()
{
Assembly asm = null;
Assert.Throws<ArgumentNullException>(() => { AssemblyIdentity.FromAssemblyDefinition(asm); });
}
[Fact]
public void FromAssemblyDefinition()
{
var name = new AssemblyName("goo");
name.Flags = AssemblyNameFlags.Retargetable | AssemblyNameFlags.PublicKey | AssemblyNameFlags.EnableJITcompileOptimizer | AssemblyNameFlags.EnableJITcompileTracking;
name.CultureInfo = new CultureInfo("en-US", useUserOverride: false);
name.ContentType = AssemblyContentType.Default;
name.Version = new Version(1, 2, 3, 4);
name.ProcessorArchitecture = ProcessorArchitecture.X86;
var id = AssemblyIdentity.FromAssemblyDefinition(name);
Assert.Equal("goo", id.Name);
Assert.True(id.IsRetargetable);
Assert.Equal(new Version(1, 2, 3, 4), id.Version);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
Assert.False(id.HasPublicKey);
Assert.False(id.IsStrongName);
name = new AssemblyName("goo");
name.SetPublicKey(PublicKey1);
name.Version = new Version(1, 2, 3, 4);
id = AssemblyIdentity.FromAssemblyDefinition(name);
Assert.Equal("goo", id.Name);
Assert.Equal(new Version(1, 2, 3, 4), id.Version);
Assert.True(id.HasPublicKey);
Assert.True(id.IsStrongName);
AssertEx.Equal(id.PublicKey, PublicKey1);
name = new AssemblyName("goo");
name.ContentType = AssemblyContentType.WindowsRuntime;
id = AssemblyIdentity.FromAssemblyDefinition(name);
Assert.Equal("goo", id.Name);
Assert.Equal(AssemblyContentType.WindowsRuntime, id.ContentType);
}
[Fact]
public void FromAssemblyDefinition_InvariantCulture()
{
var name = new AssemblyName("goo");
name.Flags = AssemblyNameFlags.None;
name.CultureInfo = CultureInfo.InvariantCulture;
name.ContentType = AssemblyContentType.Default;
name.Version = new Version(1, 2, 3, 4);
name.ProcessorArchitecture = ProcessorArchitecture.X86;
var id = AssemblyIdentity.FromAssemblyDefinition(name);
Assert.Equal("", id.CultureName);
}
[Fact]
public void Properties()
{
var id = new AssemblyIdentity("Goo", hasPublicKey: false, isRetargetable: false);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(0, 0, 0, 0), id.Version);
Assert.Equal(AssemblyNameFlags.None, id.Flags);
Assert.Equal("", id.CultureName);
Assert.False(id.HasPublicKey);
Assert.False(id.IsRetargetable);
Assert.Equal(0, id.PublicKey.Length);
Assert.Equal(0, id.PublicKeyToken.Length);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
id = new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKey1, hasPublicKey: true, isRetargetable: false);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(0, 0, 0, 0), id.Version);
Assert.Equal(AssemblyNameFlags.PublicKey, id.Flags);
Assert.Equal("", id.CultureName);
Assert.True(id.HasPublicKey);
Assert.False(id.IsRetargetable);
AssertEx.Equal(PublicKey1, id.PublicKey);
AssertEx.Equal(PublicKeyToken1, id.PublicKeyToken);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
id = new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKeyToken1, hasPublicKey: false, isRetargetable: true);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(0, 0, 0, 0), id.Version);
Assert.Equal(AssemblyNameFlags.Retargetable, id.Flags);
Assert.Equal("", id.CultureName);
Assert.False(id.HasPublicKey);
Assert.True(id.IsRetargetable);
Assert.Equal(0, id.PublicKey.Length);
AssertEx.Equal(PublicKeyToken1, id.PublicKeyToken);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
id = new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKey1, hasPublicKey: true, isRetargetable: true);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(0, 0, 0, 0), id.Version);
Assert.Equal(AssemblyNameFlags.PublicKey | AssemblyNameFlags.Retargetable, id.Flags);
Assert.Equal("", id.CultureName);
Assert.True(id.HasPublicKey);
Assert.True(id.IsRetargetable);
AssertEx.Equal(PublicKey1, id.PublicKey);
AssertEx.Equal(PublicKeyToken1, id.PublicKeyToken);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
id = new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKey1, hasPublicKey: true, contentType: AssemblyContentType.WindowsRuntime);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(0, 0, 0, 0), id.Version);
Assert.Equal(AssemblyNameFlags.PublicKey, id.Flags);
Assert.Equal("", id.CultureName);
Assert.True(id.HasPublicKey);
Assert.False(id.IsRetargetable);
AssertEx.Equal(PublicKey1, id.PublicKey);
AssertEx.Equal(PublicKeyToken1, id.PublicKeyToken);
Assert.Equal(AssemblyContentType.WindowsRuntime, id.ContentType);
}
[Fact]
public void IsStrongName()
{
var id1 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false);
Assert.True(id1.IsStrongName);
var id2 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
Assert.True(id2.IsStrongName);
var id3 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", ImmutableArray<byte>.Empty, hasPublicKey: false, isRetargetable: false);
Assert.False(id3.IsStrongName);
// for WinRT references "strong name" doesn't make sense:
var id4 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", ImmutableArray<byte>.Empty, hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.WindowsRuntime);
Assert.False(id4.IsStrongName);
var id5 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.WindowsRuntime);
Assert.True(id5.IsStrongName);
}
[Fact]
public void InvalidConstructorArgs()
{
Assert.Throws<ArgumentException>(() => new AssemblyIdentity("xx\0xx"));
Assert.Throws<ArgumentException>(() => new AssemblyIdentity(""));
Assert.Throws<ArgumentException>(() => new AssemblyIdentity(null));
Assert.Throws<ArgumentException>(
() => new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", ImmutableArray<byte>.Empty, hasPublicKey: true, isRetargetable: false, contentType: AssemblyContentType.Default));
Assert.Throws<ArgumentException>(
() => new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", new byte[] { 1, 2, 3 }.AsImmutableOrNull(), hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default));
foreach (var v in new Version[]
{
new Version(),
new Version(0, 0),
new Version(0, 0, 0),
new Version(int.MaxValue, 0, 0, 0),
new Version(0, int.MaxValue, 0, 0),
new Version(0, 0, int.MaxValue, 0),
new Version(0, 0, 0, int.MaxValue),
})
{
Assert.Throws<ArgumentOutOfRangeException>(() => new AssemblyIdentity("Goo", v));
}
Assert.Throws<ArgumentOutOfRangeException>(() => new AssemblyIdentity("Goo", contentType: (AssemblyContentType)(-1)));
Assert.Throws<ArgumentOutOfRangeException>(() => new AssemblyIdentity("Goo", contentType: (AssemblyContentType)int.MaxValue));
Assert.Throws<ArgumentException>(() =>
new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKey1, hasPublicKey: true, isRetargetable: true, contentType: AssemblyContentType.WindowsRuntime));
}
[Fact]
public void MetadataConstructor()
{
var id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), "en-US", RoPublicKey1,
hasPublicKey: true, isRetargetable: true, contentType: AssemblyContentType.Default);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(1, 2, 3, 4), id.Version);
Assert.Equal(AssemblyNameFlags.PublicKey | AssemblyNameFlags.Retargetable, id.Flags);
Assert.Equal("en-US", id.CultureName);
Assert.True(id.HasPublicKey);
Assert.True(id.IsRetargetable);
AssertEx.Equal(PublicKey1, id.PublicKey);
AssertEx.Equal(PublicKeyToken1, id.PublicKeyToken);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
// invalid content type:
id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), null, ImmutableArray<byte>.Empty,
hasPublicKey: false, isRetargetable: false, contentType: (AssemblyContentType)2);
Assert.Equal(AssemblyNameFlags.None, id.Flags);
Assert.Equal("", id.CultureName);
Assert.False(id.HasPublicKey);
Assert.Equal(0, id.PublicKey.Length);
Assert.Equal(0, id.PublicKeyToken.Length);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
// default Retargetable=No if content type is WinRT
id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), null, ImmutableArray<byte>.Empty,
hasPublicKey: false, isRetargetable: true, contentType: AssemblyContentType.WindowsRuntime);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(1, 2, 3, 4), id.Version);
Assert.Equal(AssemblyNameFlags.None, id.Flags);
Assert.Equal("", id.CultureName);
Assert.False(id.HasPublicKey);
Assert.False(id.IsRetargetable);
Assert.Equal(AssemblyContentType.WindowsRuntime, id.ContentType);
// invalid culture:
// The native compiler doesn't enforce that the culture be anything in particular.
// AssemblyIdentity should preserve user input even if it is of dubious utility.
id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), "blah,", ImmutableArray<byte>.Empty,
hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default);
Assert.Equal("blah,", id.CultureName);
id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), "*", ImmutableArray<byte>.Empty,
hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default);
Assert.Equal("*", id.CultureName);
id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), "neutral", ImmutableArray<byte>.Empty,
hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default);
Assert.Equal("", id.CultureName);
}
[Fact]
public void ToAssemblyName()
{
var ai = new AssemblyIdentity("goo");
var an = ai.ToAssemblyName();
Assert.Equal("goo", an.Name);
Assert.Equal(new Version(0, 0, 0, 0), an.Version);
Assert.Equal(CultureInfo.InvariantCulture, an.CultureInfo);
AssertEx.Equal(new byte[0], an.GetPublicKeyToken());
AssertEx.Equal(null, an.GetPublicKey());
Assert.Equal(AssemblyNameFlags.None, an.Flags);
Assert.Null(an.CodeBase);
ai = new AssemblyIdentity("goo", new Version(1, 2, 3, 4), "en-US", RoPublicKey1,
hasPublicKey: true,
isRetargetable: true);
an = ai.ToAssemblyName();
Assert.Equal("goo", an.Name);
Assert.Equal(new Version(1, 2, 3, 4), an.Version);
Assert.Equal(CultureInfo.GetCultureInfo("en-US"), an.CultureInfo);
AssertEx.Equal(PublicKeyToken1, an.GetPublicKeyToken());
AssertEx.Equal(PublicKey1, an.GetPublicKey());
Assert.Equal(AssemblyNameFlags.PublicKey | AssemblyNameFlags.Retargetable, an.Flags);
Assert.Null(an.CodeBase);
// invalid characters are ok in the name, the FullName can't be built though:
foreach (char c in ClrInvalidCharacters)
{
ai = new AssemblyIdentity(c.ToString());
an = ai.ToAssemblyName();
Assert.Equal(c.ToString(), an.Name);
Assert.Equal(new Version(0, 0, 0, 0), an.Version);
Assert.Equal(CultureInfo.InvariantCulture, an.CultureInfo);
AssertEx.Equal(new byte[0], an.GetPublicKeyToken());
AssertEx.Equal(null, an.GetPublicKey());
Assert.Equal(AssemblyNameFlags.None, an.Flags);
AssertEx.Equal(null, an.CodeBase);
}
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)]
public void ToAssemblyName_Errors()
{
var ai = new AssemblyIdentity("goo", cultureName: "*");
Assert.Throws<CultureNotFoundException>(() => ai.ToAssemblyName());
}
[Fact]
public void Keys()
{
var an = new AssemblyName();
an.Name = "Goo";
an.Version = new Version(1, 0, 0, 0);
an.SetPublicKey(PublicKey1);
var anPkt = an.GetPublicKeyToken();
var aiPkt = AssemblyIdentity.CalculatePublicKeyToken(RoPublicKey1);
AssertEx.Equal(PublicKeyToken1, anPkt);
AssertEx.Equal(PublicKeyToken1, aiPkt);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void FullKeyAndToken()
{
string displayPkt = "Goo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=" + StrPublicKeyToken1;
string displayPk = "Goo, Version=1.0.0.0, Culture=neutral, PublicKey=" + StrPublicKey1;
bool equivalent;
FusionAssemblyIdentityComparer.AssemblyComparisonResult result;
int hr = FusionAssemblyIdentityComparer.DefaultModelCompareAssemblyIdentity(displayPkt, false, displayPk, false, out equivalent, out result, IntPtr.Zero);
Assert.Equal(0, hr);
Assert.True(equivalent, "Expected equivalent");
Assert.Equal(FusionAssemblyIdentityComparer.AssemblyComparisonResult.EquivalentFullMatch, result);
hr = FusionAssemblyIdentityComparer.DefaultModelCompareAssemblyIdentity(displayPk, false, displayPkt, false, out equivalent, out result, IntPtr.Zero);
Assert.Equal(0, hr);
Assert.True(equivalent, "Expected equivalent");
Assert.Equal(FusionAssemblyIdentityComparer.AssemblyComparisonResult.EquivalentFullMatch, result);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using System.Reflection;
using System.Reflection.Metadata;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class AssemblyIdentityTests : AssemblyIdentityTestBase
{
[Fact]
public void Equality()
{
var id1 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false);
var id11 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false);
var id2 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var id22 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var id3 = new AssemblyIdentity("Goo!", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var id4 = new AssemblyIdentity("Goo", new Version(1, 0, 1, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var id5 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "en-US", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var id6 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", default(ImmutableArray<byte>), hasPublicKey: false, isRetargetable: false);
var id7 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: true);
var win1 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false, contentType: AssemblyContentType.WindowsRuntime);
var win2 = new AssemblyIdentity("Bar", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false, contentType: AssemblyContentType.WindowsRuntime);
var win3 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false, contentType: AssemblyContentType.WindowsRuntime);
Assert.True(id1.Equals(id1));
Assert.True(id1.Equals(id2));
Assert.True(id2.Equals(id1));
Assert.True(id1.Equals(id11));
Assert.True(id11.Equals(id1));
Assert.True(id2.Equals(id22));
Assert.True(id22.Equals(id2));
Assert.False(id1.Equals(id3));
Assert.False(id1.Equals(id4));
Assert.False(id1.Equals(id5));
Assert.False(id1.Equals(id6));
Assert.False(id1.Equals(id7));
Assert.Equal((object)id1, id1);
Assert.NotNull(id1);
Assert.False(id2.Equals((AssemblyIdentity)null));
Assert.Equal(id1.GetHashCode(), id2.GetHashCode());
Assert.False(win1.Equals(win2));
Assert.False(win1.Equals(id1));
Assert.True(win1.Equals(win3));
Assert.Equal(win1.GetHashCode(), win3.GetHashCode());
}
[Fact]
public void Equality_InvariantCulture()
{
var neutral1 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "NEUtral", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var neutral2 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), null, RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var neutral3 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "neutral", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
var invariant = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
Assert.True(neutral1.Equals(invariant));
Assert.True(neutral2.Equals(invariant));
Assert.True(neutral3.Equals(invariant));
}
[Fact]
public void FromAssemblyDefinitionInvalidParameters()
{
Assembly asm = null;
Assert.Throws<ArgumentNullException>(() => { AssemblyIdentity.FromAssemblyDefinition(asm); });
}
[Fact]
public void FromAssemblyDefinition()
{
var name = new AssemblyName("goo");
name.Flags = AssemblyNameFlags.Retargetable | AssemblyNameFlags.PublicKey | AssemblyNameFlags.EnableJITcompileOptimizer | AssemblyNameFlags.EnableJITcompileTracking;
name.CultureInfo = new CultureInfo("en-US", useUserOverride: false);
name.ContentType = AssemblyContentType.Default;
name.Version = new Version(1, 2, 3, 4);
name.ProcessorArchitecture = ProcessorArchitecture.X86;
var id = AssemblyIdentity.FromAssemblyDefinition(name);
Assert.Equal("goo", id.Name);
Assert.True(id.IsRetargetable);
Assert.Equal(new Version(1, 2, 3, 4), id.Version);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
Assert.False(id.HasPublicKey);
Assert.False(id.IsStrongName);
name = new AssemblyName("goo");
name.SetPublicKey(PublicKey1);
name.Version = new Version(1, 2, 3, 4);
id = AssemblyIdentity.FromAssemblyDefinition(name);
Assert.Equal("goo", id.Name);
Assert.Equal(new Version(1, 2, 3, 4), id.Version);
Assert.True(id.HasPublicKey);
Assert.True(id.IsStrongName);
AssertEx.Equal(id.PublicKey, PublicKey1);
name = new AssemblyName("goo");
name.ContentType = AssemblyContentType.WindowsRuntime;
id = AssemblyIdentity.FromAssemblyDefinition(name);
Assert.Equal("goo", id.Name);
Assert.Equal(AssemblyContentType.WindowsRuntime, id.ContentType);
}
[Fact]
public void FromAssemblyDefinition_InvariantCulture()
{
var name = new AssemblyName("goo");
name.Flags = AssemblyNameFlags.None;
name.CultureInfo = CultureInfo.InvariantCulture;
name.ContentType = AssemblyContentType.Default;
name.Version = new Version(1, 2, 3, 4);
name.ProcessorArchitecture = ProcessorArchitecture.X86;
var id = AssemblyIdentity.FromAssemblyDefinition(name);
Assert.Equal("", id.CultureName);
}
[Fact]
public void Properties()
{
var id = new AssemblyIdentity("Goo", hasPublicKey: false, isRetargetable: false);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(0, 0, 0, 0), id.Version);
Assert.Equal(AssemblyNameFlags.None, id.Flags);
Assert.Equal("", id.CultureName);
Assert.False(id.HasPublicKey);
Assert.False(id.IsRetargetable);
Assert.Equal(0, id.PublicKey.Length);
Assert.Equal(0, id.PublicKeyToken.Length);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
id = new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKey1, hasPublicKey: true, isRetargetable: false);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(0, 0, 0, 0), id.Version);
Assert.Equal(AssemblyNameFlags.PublicKey, id.Flags);
Assert.Equal("", id.CultureName);
Assert.True(id.HasPublicKey);
Assert.False(id.IsRetargetable);
AssertEx.Equal(PublicKey1, id.PublicKey);
AssertEx.Equal(PublicKeyToken1, id.PublicKeyToken);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
id = new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKeyToken1, hasPublicKey: false, isRetargetable: true);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(0, 0, 0, 0), id.Version);
Assert.Equal(AssemblyNameFlags.Retargetable, id.Flags);
Assert.Equal("", id.CultureName);
Assert.False(id.HasPublicKey);
Assert.True(id.IsRetargetable);
Assert.Equal(0, id.PublicKey.Length);
AssertEx.Equal(PublicKeyToken1, id.PublicKeyToken);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
id = new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKey1, hasPublicKey: true, isRetargetable: true);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(0, 0, 0, 0), id.Version);
Assert.Equal(AssemblyNameFlags.PublicKey | AssemblyNameFlags.Retargetable, id.Flags);
Assert.Equal("", id.CultureName);
Assert.True(id.HasPublicKey);
Assert.True(id.IsRetargetable);
AssertEx.Equal(PublicKey1, id.PublicKey);
AssertEx.Equal(PublicKeyToken1, id.PublicKeyToken);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
id = new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKey1, hasPublicKey: true, contentType: AssemblyContentType.WindowsRuntime);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(0, 0, 0, 0), id.Version);
Assert.Equal(AssemblyNameFlags.PublicKey, id.Flags);
Assert.Equal("", id.CultureName);
Assert.True(id.HasPublicKey);
Assert.False(id.IsRetargetable);
AssertEx.Equal(PublicKey1, id.PublicKey);
AssertEx.Equal(PublicKeyToken1, id.PublicKeyToken);
Assert.Equal(AssemblyContentType.WindowsRuntime, id.ContentType);
}
[Fact]
public void IsStrongName()
{
var id1 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKey1, hasPublicKey: true, isRetargetable: false);
Assert.True(id1.IsStrongName);
var id2 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false);
Assert.True(id2.IsStrongName);
var id3 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", ImmutableArray<byte>.Empty, hasPublicKey: false, isRetargetable: false);
Assert.False(id3.IsStrongName);
// for WinRT references "strong name" doesn't make sense:
var id4 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", ImmutableArray<byte>.Empty, hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.WindowsRuntime);
Assert.False(id4.IsStrongName);
var id5 = new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", RoPublicKeyToken1, hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.WindowsRuntime);
Assert.True(id5.IsStrongName);
}
[Fact]
public void InvalidConstructorArgs()
{
Assert.Throws<ArgumentException>(() => new AssemblyIdentity("xx\0xx"));
Assert.Throws<ArgumentException>(() => new AssemblyIdentity(""));
Assert.Throws<ArgumentException>(() => new AssemblyIdentity(null));
Assert.Throws<ArgumentException>(
() => new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", ImmutableArray<byte>.Empty, hasPublicKey: true, isRetargetable: false, contentType: AssemblyContentType.Default));
Assert.Throws<ArgumentException>(
() => new AssemblyIdentity("Goo", new Version(1, 0, 0, 0), "", new byte[] { 1, 2, 3 }.AsImmutableOrNull(), hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default));
foreach (var v in new Version[]
{
new Version(),
new Version(0, 0),
new Version(0, 0, 0),
new Version(int.MaxValue, 0, 0, 0),
new Version(0, int.MaxValue, 0, 0),
new Version(0, 0, int.MaxValue, 0),
new Version(0, 0, 0, int.MaxValue),
})
{
Assert.Throws<ArgumentOutOfRangeException>(() => new AssemblyIdentity("Goo", v));
}
Assert.Throws<ArgumentOutOfRangeException>(() => new AssemblyIdentity("Goo", contentType: (AssemblyContentType)(-1)));
Assert.Throws<ArgumentOutOfRangeException>(() => new AssemblyIdentity("Goo", contentType: (AssemblyContentType)int.MaxValue));
Assert.Throws<ArgumentException>(() =>
new AssemblyIdentity("Goo", publicKeyOrToken: RoPublicKey1, hasPublicKey: true, isRetargetable: true, contentType: AssemblyContentType.WindowsRuntime));
}
[Fact]
public void MetadataConstructor()
{
var id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), "en-US", RoPublicKey1,
hasPublicKey: true, isRetargetable: true, contentType: AssemblyContentType.Default);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(1, 2, 3, 4), id.Version);
Assert.Equal(AssemblyNameFlags.PublicKey | AssemblyNameFlags.Retargetable, id.Flags);
Assert.Equal("en-US", id.CultureName);
Assert.True(id.HasPublicKey);
Assert.True(id.IsRetargetable);
AssertEx.Equal(PublicKey1, id.PublicKey);
AssertEx.Equal(PublicKeyToken1, id.PublicKeyToken);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
// invalid content type:
id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), null, ImmutableArray<byte>.Empty,
hasPublicKey: false, isRetargetable: false, contentType: (AssemblyContentType)2);
Assert.Equal(AssemblyNameFlags.None, id.Flags);
Assert.Equal("", id.CultureName);
Assert.False(id.HasPublicKey);
Assert.Equal(0, id.PublicKey.Length);
Assert.Equal(0, id.PublicKeyToken.Length);
Assert.Equal(AssemblyContentType.Default, id.ContentType);
// default Retargetable=No if content type is WinRT
id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), null, ImmutableArray<byte>.Empty,
hasPublicKey: false, isRetargetable: true, contentType: AssemblyContentType.WindowsRuntime);
Assert.Equal("Goo", id.Name);
Assert.Equal(new Version(1, 2, 3, 4), id.Version);
Assert.Equal(AssemblyNameFlags.None, id.Flags);
Assert.Equal("", id.CultureName);
Assert.False(id.HasPublicKey);
Assert.False(id.IsRetargetable);
Assert.Equal(AssemblyContentType.WindowsRuntime, id.ContentType);
// invalid culture:
// The native compiler doesn't enforce that the culture be anything in particular.
// AssemblyIdentity should preserve user input even if it is of dubious utility.
id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), "blah,", ImmutableArray<byte>.Empty,
hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default);
Assert.Equal("blah,", id.CultureName);
id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), "*", ImmutableArray<byte>.Empty,
hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default);
Assert.Equal("*", id.CultureName);
id = new AssemblyIdentity(/*noThrow:*/true, "Goo", new Version(1, 2, 3, 4), "neutral", ImmutableArray<byte>.Empty,
hasPublicKey: false, isRetargetable: false, contentType: AssemblyContentType.Default);
Assert.Equal("", id.CultureName);
}
[Fact]
public void ToAssemblyName()
{
var ai = new AssemblyIdentity("goo");
var an = ai.ToAssemblyName();
Assert.Equal("goo", an.Name);
Assert.Equal(new Version(0, 0, 0, 0), an.Version);
Assert.Equal(CultureInfo.InvariantCulture, an.CultureInfo);
AssertEx.Equal(new byte[0], an.GetPublicKeyToken());
AssertEx.Equal(null, an.GetPublicKey());
Assert.Equal(AssemblyNameFlags.None, an.Flags);
Assert.Null(an.CodeBase);
ai = new AssemblyIdentity("goo", new Version(1, 2, 3, 4), "en-US", RoPublicKey1,
hasPublicKey: true,
isRetargetable: true);
an = ai.ToAssemblyName();
Assert.Equal("goo", an.Name);
Assert.Equal(new Version(1, 2, 3, 4), an.Version);
Assert.Equal(CultureInfo.GetCultureInfo("en-US"), an.CultureInfo);
AssertEx.Equal(PublicKeyToken1, an.GetPublicKeyToken());
AssertEx.Equal(PublicKey1, an.GetPublicKey());
Assert.Equal(AssemblyNameFlags.PublicKey | AssemblyNameFlags.Retargetable, an.Flags);
Assert.Null(an.CodeBase);
// invalid characters are ok in the name, the FullName can't be built though:
foreach (char c in ClrInvalidCharacters)
{
ai = new AssemblyIdentity(c.ToString());
an = ai.ToAssemblyName();
Assert.Equal(c.ToString(), an.Name);
Assert.Equal(new Version(0, 0, 0, 0), an.Version);
Assert.Equal(CultureInfo.InvariantCulture, an.CultureInfo);
AssertEx.Equal(new byte[0], an.GetPublicKeyToken());
AssertEx.Equal(null, an.GetPublicKey());
Assert.Equal(AssemblyNameFlags.None, an.Flags);
AssertEx.Equal(null, an.CodeBase);
}
}
[ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)]
public void ToAssemblyName_Errors()
{
var ai = new AssemblyIdentity("goo", cultureName: "*");
Assert.Throws<CultureNotFoundException>(() => ai.ToAssemblyName());
}
[Fact]
public void Keys()
{
var an = new AssemblyName();
an.Name = "Goo";
an.Version = new Version(1, 0, 0, 0);
an.SetPublicKey(PublicKey1);
var anPkt = an.GetPublicKeyToken();
var aiPkt = AssemblyIdentity.CalculatePublicKeyToken(RoPublicKey1);
AssertEx.Equal(PublicKeyToken1, anPkt);
AssertEx.Equal(PublicKeyToken1, aiPkt);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsFusion)]
public void FullKeyAndToken()
{
string displayPkt = "Goo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=" + StrPublicKeyToken1;
string displayPk = "Goo, Version=1.0.0.0, Culture=neutral, PublicKey=" + StrPublicKey1;
bool equivalent;
FusionAssemblyIdentityComparer.AssemblyComparisonResult result;
int hr = FusionAssemblyIdentityComparer.DefaultModelCompareAssemblyIdentity(displayPkt, false, displayPk, false, out equivalent, out result, IntPtr.Zero);
Assert.Equal(0, hr);
Assert.True(equivalent, "Expected equivalent");
Assert.Equal(FusionAssemblyIdentityComparer.AssemblyComparisonResult.EquivalentFullMatch, result);
hr = FusionAssemblyIdentityComparer.DefaultModelCompareAssemblyIdentity(displayPk, false, displayPkt, false, out equivalent, out result, IntPtr.Zero);
Assert.Equal(0, hr);
Assert.True(equivalent, "Expected equivalent");
Assert.Equal(FusionAssemblyIdentityComparer.AssemblyComparisonResult.EquivalentFullMatch, result);
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Features/Core/Portable/RQName/Nodes/RQPropertyBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQPropertyBase : RQMethodOrProperty
{
public RQPropertyBase(
RQUnconstructedType containingType,
RQMethodPropertyOrEventName memberName,
int typeParameterCount,
IList<RQParameter> parameters)
: base(containingType, memberName, typeParameterCount, parameters)
{ }
protected override string RQKeyword
{
get { return RQNameStrings.Prop; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
internal abstract class RQPropertyBase : RQMethodOrProperty
{
public RQPropertyBase(
RQUnconstructedType containingType,
RQMethodPropertyOrEventName memberName,
int typeParameterCount,
IList<RQParameter> parameters)
: base(containingType, memberName, typeParameterCount, parameters)
{ }
protected override string RQKeyword
{
get { return RQNameStrings.Prop; }
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/VisualBasicTest/Formatting/XmlLiterals.resx | <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="EmptyElement1" xml:space="preserve">
<value>Class C
Sub Method()
Dim book = <book
$$version="goo"
/>
End Sub
End Class</value>
</data>
<data name="IndentationTest1" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim abc = <xml>
<video>video1</video>
</xml>
Dim r = From q In abc...<video> _
End Sub
End Module</value>
</data>
<data name="IndentationTest2" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim abc = <xml>
<video>video1</video>
</xml>
Dim r = From q In abc...<video> ' comment
End Sub
End Module</value>
</data>
<data name="Test1_Input" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml>
<hello>
</hello>
</xml>
End Sub
End Class</value>
</data>
<data name="Test1_Output" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml>
<hello>
</hello>
</xml>
End Sub
End Class</value>
</data>
<data name="Test2_Input" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml>
<!-- Test -->
<hello>
Test
<![CDATA[ ???? ]]>
</hello>
<!-- Test --> </xml>
End Sub
End Class</value>
</data>
<data name="Test2_Output" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml>
<!-- Test -->
<hello>
Test
<![CDATA[ ???? ]]>
</hello>
<!-- Test --></xml>
End Sub
End Class</value>
</data>
<data name="Test3_Input" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml> <!-- Test --> <hello>
Test
<![CDATA[ ???? ]]>
</hello>
<!-- Test --></xml>
End Sub
End Class</value>
</data>
<data name="Test3_Output" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml><!-- Test --><hello>
Test
<![CDATA[ ???? ]]>
</hello>
<!-- Test --></xml>
End Sub
End Class</value>
</data>
<data name="Test4_Input" xml:space="preserve">
<value>Class C
Sub Goo()
Dim xml = <xml><code><node></node></code></xml>
Dim j = From node In xml.<code>
Select node.@att
End Sub
End Class</value>
</data>
<data name="Test4_Output" xml:space="preserve">
<value>Class C
Sub Goo()
Dim xml = <xml><code><node></node></code></xml>
Dim j = From node In xml.<code>
Select node.@att
End Sub
End Class</value>
</data>
<data name="Test5_Input" xml:space="preserve">
<value>''' <summary>
'''
''' </summary>
Module Program
Sub Main(args As String())
End Sub
End Module</value>
</data>
<data name="Test5_Output" xml:space="preserve">
<value>''' <summary>
'''
''' </summary>
Module Program
Sub Main(args As String())
End Sub
End Module</value>
</data>
<data name="Test6_Input" xml:space="preserve">
<value>Class C
'''<summary>
''' Test Method
'''</summary>
Sub Method()
End Sub
End Class</value>
</data>
<data name="Test6_Output" xml:space="preserve">
<value>Class C
'''<summary>
''' Test Method
'''</summary>
Sub Method()
End Sub
End Class</value>
</data>
<data name="TokenFormatter1" xml:space="preserve">
<value>Class CL
Dim d = <Code>
$$</Code>
End Class</value>
</data>
<data name="TokenFormatter2" xml:space="preserve">
<value>Namespace NS
<ComClass("")>
$$<CLSCompliant(False)>
Public Class CL
End Class
End Namespace</value>
</data>
<data name="XmlElementStartTag1_Input" xml:space="preserve">
<value>Class C
Sub Method()
Dim book = <book
version="goo"
>
</book>
End Sub
End Class</value>
</data>
<data name="XmlElementStartTag1_Output" xml:space="preserve">
<value>Class C
Sub Method()
Dim book = <book
version="goo"
>
</book>
End Sub
End Class</value>
</data>
<data name="XmlTest1_Input" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim book = </book >
GetXml( </book >)
End Sub
End Module</value>
</data>
<data name="XmlTest1_Output" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim book = </book>
GetXml( </book>)
End Sub
End Module</value>
</data>
<data name="XmlTest1_TokenFormat" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim book = <?xml version ="1.0"?><?fff fff?><!-- ffff -->
$$<book/><!-- last comment! yeah :) -->
End Sub
End Module</value>
</data>
<data name="XmlTest2_Input" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim book = <?xml version="1.0"?>
<?fff fff?>
<!-- ffff -->
<book/>
<!-- last comment! yeah :) -->
End Sub
End Module</value>
</data>
<data name="XmlTest2_Output" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim book = <?xml version="1.0"?>
<?fff fff?>
<!-- ffff -->
<book/>
<!-- last comment! yeah :) -->
End Sub
End Module</value>
</data>
<data name="XmlTest3_Input" xml:space="preserve">
<value>Module Program
Sub Main()
Dim x = <?xml version="1.0"?>
<?blah?>
<xml></xml>
End Sub
End Module</value>
</data>
<data name="XmlTest3_Output" xml:space="preserve">
<value>Module Program
Sub Main()
Dim x = <?xml version="1.0"?>
<?blah?>
<xml></xml>
End Sub
End Module</value>
</data>
<data name="XmlTest4_Input_Output" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim goo = _
<LongBook>
<%= _
From i In <were><a><b><c></c></b></a></were> _
Where i IsNot Nothing _
Select _
<f>
<g>
<f>
</f>
</g>
</f> _
%>
</LongBook>
End Sub
End Module</value>
</data>
<data name="XmlTest5_Input" xml:space="preserve">
<value>Class C
Sub Method()
Dim q = <xml>
test <xml2><%= <xml3><xml4>
</xml4></xml3>
%></xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest5_Output" xml:space="preserve">
<value>Class C
Sub Method()
Dim q = <xml>
test <xml2><%= <xml3><xml4>
</xml4></xml3>
%></xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest6_Input" xml:space="preserve">
<value>Class C2
Sub Method()
Dim q = <xml>
tst <%= <xml2><xml3><xml4>
</xml4></xml3>
</xml2>
%>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest6_Output" xml:space="preserve">
<value>Class C2
Sub Method()
Dim q = <xml>
tst <%= <xml2><xml3><xml4>
</xml4></xml3>
</xml2>
%>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest7_Input" xml:space="preserve">
<value>Class C22
Sub Method()
Dim q = <xml>
tst
<xml2><xml3><xml4>
</xml4></xml3>
</xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest7_Output" xml:space="preserve">
<value>Class C22
Sub Method()
Dim q = <xml>
tst
<xml2><xml3><xml4>
</xml4></xml3>
</xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest8_Input" xml:space="preserve">
<value>Class C223
Sub Method()
Dim q = <xml>
<!-- -->
t
st
<xml2><xml3><xml4>
</xml4></xml3>
</xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest8_Output" xml:space="preserve">
<value>Class C223
Sub Method()
Dim q = <xml>
<!-- -->
t
st
<xml2><xml3><xml4>
</xml4></xml3>
</xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest9" xml:space="preserve">
<value>Class C
Sub Method()
Dim q = <xml>
<xml2><%= <xml3><xml4>
</xml4>
$$</xml3>
%>
</xml2>
</xml>
End Sub
End Class</value>
</data>
</root> | <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="EmptyElement1" xml:space="preserve">
<value>Class C
Sub Method()
Dim book = <book
$$version="goo"
/>
End Sub
End Class</value>
</data>
<data name="IndentationTest1" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim abc = <xml>
<video>video1</video>
</xml>
Dim r = From q In abc...<video> _
End Sub
End Module</value>
</data>
<data name="IndentationTest2" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim abc = <xml>
<video>video1</video>
</xml>
Dim r = From q In abc...<video> ' comment
End Sub
End Module</value>
</data>
<data name="Test1_Input" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml>
<hello>
</hello>
</xml>
End Sub
End Class</value>
</data>
<data name="Test1_Output" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml>
<hello>
</hello>
</xml>
End Sub
End Class</value>
</data>
<data name="Test2_Input" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml>
<!-- Test -->
<hello>
Test
<![CDATA[ ???? ]]>
</hello>
<!-- Test --> </xml>
End Sub
End Class</value>
</data>
<data name="Test2_Output" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml>
<!-- Test -->
<hello>
Test
<![CDATA[ ???? ]]>
</hello>
<!-- Test --></xml>
End Sub
End Class</value>
</data>
<data name="Test3_Input" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml> <!-- Test --> <hello>
Test
<![CDATA[ ???? ]]>
</hello>
<!-- Test --></xml>
End Sub
End Class</value>
</data>
<data name="Test3_Output" xml:space="preserve">
<value>Class C
Sub Method(Optional ByVal i As Integer = 1)
Dim q = <xml><!-- Test --><hello>
Test
<![CDATA[ ???? ]]>
</hello>
<!-- Test --></xml>
End Sub
End Class</value>
</data>
<data name="Test4_Input" xml:space="preserve">
<value>Class C
Sub Goo()
Dim xml = <xml><code><node></node></code></xml>
Dim j = From node In xml.<code>
Select node.@att
End Sub
End Class</value>
</data>
<data name="Test4_Output" xml:space="preserve">
<value>Class C
Sub Goo()
Dim xml = <xml><code><node></node></code></xml>
Dim j = From node In xml.<code>
Select node.@att
End Sub
End Class</value>
</data>
<data name="Test5_Input" xml:space="preserve">
<value>''' <summary>
'''
''' </summary>
Module Program
Sub Main(args As String())
End Sub
End Module</value>
</data>
<data name="Test5_Output" xml:space="preserve">
<value>''' <summary>
'''
''' </summary>
Module Program
Sub Main(args As String())
End Sub
End Module</value>
</data>
<data name="Test6_Input" xml:space="preserve">
<value>Class C
'''<summary>
''' Test Method
'''</summary>
Sub Method()
End Sub
End Class</value>
</data>
<data name="Test6_Output" xml:space="preserve">
<value>Class C
'''<summary>
''' Test Method
'''</summary>
Sub Method()
End Sub
End Class</value>
</data>
<data name="TokenFormatter1" xml:space="preserve">
<value>Class CL
Dim d = <Code>
$$</Code>
End Class</value>
</data>
<data name="TokenFormatter2" xml:space="preserve">
<value>Namespace NS
<ComClass("")>
$$<CLSCompliant(False)>
Public Class CL
End Class
End Namespace</value>
</data>
<data name="XmlElementStartTag1_Input" xml:space="preserve">
<value>Class C
Sub Method()
Dim book = <book
version="goo"
>
</book>
End Sub
End Class</value>
</data>
<data name="XmlElementStartTag1_Output" xml:space="preserve">
<value>Class C
Sub Method()
Dim book = <book
version="goo"
>
</book>
End Sub
End Class</value>
</data>
<data name="XmlTest1_Input" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim book = </book >
GetXml( </book >)
End Sub
End Module</value>
</data>
<data name="XmlTest1_Output" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim book = </book>
GetXml( </book>)
End Sub
End Module</value>
</data>
<data name="XmlTest1_TokenFormat" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim book = <?xml version ="1.0"?><?fff fff?><!-- ffff -->
$$<book/><!-- last comment! yeah :) -->
End Sub
End Module</value>
</data>
<data name="XmlTest2_Input" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim book = <?xml version="1.0"?>
<?fff fff?>
<!-- ffff -->
<book/>
<!-- last comment! yeah :) -->
End Sub
End Module</value>
</data>
<data name="XmlTest2_Output" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main()
Dim book = <?xml version="1.0"?>
<?fff fff?>
<!-- ffff -->
<book/>
<!-- last comment! yeah :) -->
End Sub
End Module</value>
</data>
<data name="XmlTest3_Input" xml:space="preserve">
<value>Module Program
Sub Main()
Dim x = <?xml version="1.0"?>
<?blah?>
<xml></xml>
End Sub
End Module</value>
</data>
<data name="XmlTest3_Output" xml:space="preserve">
<value>Module Program
Sub Main()
Dim x = <?xml version="1.0"?>
<?blah?>
<xml></xml>
End Sub
End Module</value>
</data>
<data name="XmlTest4_Input_Output" xml:space="preserve">
<value>Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim goo = _
<LongBook>
<%= _
From i In <were><a><b><c></c></b></a></were> _
Where i IsNot Nothing _
Select _
<f>
<g>
<f>
</f>
</g>
</f> _
%>
</LongBook>
End Sub
End Module</value>
</data>
<data name="XmlTest5_Input" xml:space="preserve">
<value>Class C
Sub Method()
Dim q = <xml>
test <xml2><%= <xml3><xml4>
</xml4></xml3>
%></xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest5_Output" xml:space="preserve">
<value>Class C
Sub Method()
Dim q = <xml>
test <xml2><%= <xml3><xml4>
</xml4></xml3>
%></xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest6_Input" xml:space="preserve">
<value>Class C2
Sub Method()
Dim q = <xml>
tst <%= <xml2><xml3><xml4>
</xml4></xml3>
</xml2>
%>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest6_Output" xml:space="preserve">
<value>Class C2
Sub Method()
Dim q = <xml>
tst <%= <xml2><xml3><xml4>
</xml4></xml3>
</xml2>
%>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest7_Input" xml:space="preserve">
<value>Class C22
Sub Method()
Dim q = <xml>
tst
<xml2><xml3><xml4>
</xml4></xml3>
</xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest7_Output" xml:space="preserve">
<value>Class C22
Sub Method()
Dim q = <xml>
tst
<xml2><xml3><xml4>
</xml4></xml3>
</xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest8_Input" xml:space="preserve">
<value>Class C223
Sub Method()
Dim q = <xml>
<!-- -->
t
st
<xml2><xml3><xml4>
</xml4></xml3>
</xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest8_Output" xml:space="preserve">
<value>Class C223
Sub Method()
Dim q = <xml>
<!-- -->
t
st
<xml2><xml3><xml4>
</xml4></xml3>
</xml2>
</xml>
End Sub
End Class</value>
</data>
<data name="XmlTest9" xml:space="preserve">
<value>Class C
Sub Method()
Dim q = <xml>
<xml2><%= <xml3><xml4>
</xml4>
$$</xml3>
%>
</xml2>
</xml>
End Sub
End Class</value>
</data>
</root> | -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/Core/Implementation/IntelliSense/QuickInfo/QuickInfoHyperLink.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo
{
internal sealed class QuickInfoHyperLink : IEquatable<QuickInfoHyperLink?>
{
private readonly Workspace _workspace;
public QuickInfoHyperLink(Workspace workspace, Uri uri)
{
_workspace = workspace;
Uri = uri;
NavigationAction = OpenLink;
}
public Action NavigationAction { get; }
public Uri Uri { get; }
public override bool Equals(object? obj)
{
return Equals(obj as QuickInfoHyperLink);
}
public bool Equals(QuickInfoHyperLink? other)
{
return EqualityComparer<Uri?>.Default.Equals(Uri, other?.Uri);
}
public override int GetHashCode()
{
return Uri.GetHashCode();
}
private void OpenLink()
{
var navigateToLinkService = _workspace.Services.GetRequiredService<INavigateToLinkService>();
_ = navigateToLinkService.TryNavigateToLinkAsync(Uri, CancellationToken.None);
}
internal readonly struct TestAccessor
{
public static Action CreateNavigationAction(Uri uri)
{
// The workspace is not validated by tests
return new QuickInfoHyperLink(null!, uri).NavigationAction;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo
{
internal sealed class QuickInfoHyperLink : IEquatable<QuickInfoHyperLink?>
{
private readonly Workspace _workspace;
public QuickInfoHyperLink(Workspace workspace, Uri uri)
{
_workspace = workspace;
Uri = uri;
NavigationAction = OpenLink;
}
public Action NavigationAction { get; }
public Uri Uri { get; }
public override bool Equals(object? obj)
{
return Equals(obj as QuickInfoHyperLink);
}
public bool Equals(QuickInfoHyperLink? other)
{
return EqualityComparer<Uri?>.Default.Equals(Uri, other?.Uri);
}
public override int GetHashCode()
{
return Uri.GetHashCode();
}
private void OpenLink()
{
var navigateToLinkService = _workspace.Services.GetRequiredService<INavigateToLinkService>();
_ = navigateToLinkService.TryNavigateToLinkAsync(Uri, CancellationToken.None);
}
internal readonly struct TestAccessor
{
public static Action CreateNavigationAction(Uri uri)
{
// The workspace is not validated by tests
return new QuickInfoHyperLink(null!, uri).NavigationAction;
}
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Features/CSharp/Portable/CodeFixes/GenerateMethod/GenerateConversionCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.GenerateMember;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.GenerateMethod
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateConversion), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateEnumMember)]
internal class GenerateConversionCodeFixProvider : AbstractGenerateMemberCodeFixProvider
{
private const string CS0029 = nameof(CS0029); // error CS0029: Cannot implicitly convert type 'type' to 'type'
private const string CS0030 = nameof(CS0030); // error CS0030: Cannot convert type 'type' to 'type'
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public GenerateConversionCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(CS0029, CS0030); }
}
protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic)
{
return node.IsKind(SyntaxKind.IdentifierName) ||
node.IsKind(SyntaxKind.MethodDeclaration) ||
node.IsKind(SyntaxKind.InvocationExpression) ||
node.IsKind(SyntaxKind.CastExpression) ||
node is LiteralExpressionSyntax ||
node is SimpleNameSyntax ||
node is ExpressionSyntax;
}
protected override SyntaxNode? GetTargetNode(SyntaxNode node)
{
if (node is InvocationExpressionSyntax invocation)
return invocation.Expression.GetRightmostName();
if (node is MemberBindingExpressionSyntax memberBindingExpression)
return memberBindingExpression.Name;
return node;
}
protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync(
Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var service = document.GetRequiredLanguageService<IGenerateConversionService>();
return service.GenerateConversionAsync(document, node, cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.GenerateMember;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.GenerateMethod
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.GenerateConversion), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.GenerateEnumMember)]
internal class GenerateConversionCodeFixProvider : AbstractGenerateMemberCodeFixProvider
{
private const string CS0029 = nameof(CS0029); // error CS0029: Cannot implicitly convert type 'type' to 'type'
private const string CS0030 = nameof(CS0030); // error CS0030: Cannot convert type 'type' to 'type'
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public GenerateConversionCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(CS0029, CS0030); }
}
protected override bool IsCandidate(SyntaxNode node, SyntaxToken token, Diagnostic diagnostic)
{
return node.IsKind(SyntaxKind.IdentifierName) ||
node.IsKind(SyntaxKind.MethodDeclaration) ||
node.IsKind(SyntaxKind.InvocationExpression) ||
node.IsKind(SyntaxKind.CastExpression) ||
node is LiteralExpressionSyntax ||
node is SimpleNameSyntax ||
node is ExpressionSyntax;
}
protected override SyntaxNode? GetTargetNode(SyntaxNode node)
{
if (node is InvocationExpressionSyntax invocation)
return invocation.Expression.GetRightmostName();
if (node is MemberBindingExpressionSyntax memberBindingExpression)
return memberBindingExpression.Name;
return node;
}
protected override Task<ImmutableArray<CodeAction>> GetCodeActionsAsync(
Document document, SyntaxNode node, CancellationToken cancellationToken)
{
var service = document.GetRequiredLanguageService<IGenerateConversionService>();
return service.GenerateConversionAsync(document, node, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticBraceCompletionTests.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.Xml.Linq
Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion
Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion
Public Class AutomaticBraceCompletionTests
Inherits AbstractAutomaticBraceCompletionTests
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestCreation()
Using session = CreateSessionASync("$$")
Assert.NotNull(session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestInvalidLocation_String()
Dim code = <code>Class C
Dim s As String = "$$
End Class</code>
Using session = CreateSession(code)
Assert.Null(session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestInvalidLocation_Comment()
Dim code = <code>Class C
' $$
End Class</code>
Using session = CreateSession(code)
Assert.Null(session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestInvalidLocation_DocComment()
Dim code = <code>Class C
''' $$
End Class</code>
Using session = CreateSession(code)
Assert.Null(session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestTypeParameterMultipleConstraint()
Dim code = <code>Class C
Sub Method(Of t As $$
End Class</code>
Using session = CreateSession(code)
Assert.NotNull(session)
CheckStart(session.Session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestObjectMemberInitializerSyntax()
Dim code = <code>Class C
Sub Method()
Dim a = New With $$
End Sub
End Class</code>
Using session = CreateSession(code)
Assert.NotNull(session)
CheckStart(session.Session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestCollectionInitializerSyntax()
Dim code = <code>Class C
Sub Method()
Dim a = New List(Of Integer) From $$
End Sub
End Class</code>
Using session = CreateSession(code)
Assert.NotNull(session)
CheckStart(session.Session)
End Using
End Sub
Friend Overloads Shared Function CreateSession(code As XElement) As Holder
Return CreateSessionASync(code.NormalizedValue())
End Function
Friend Overloads Shared Function CreateSessionASync(code As String) As Holder
Return AbstractAutomaticBraceCompletionTests.CreateSession(
TestWorkspace.CreateVisualBasic(code),
CurlyBrace.OpenCharacter, CurlyBrace.CloseCharacter)
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.Xml.Linq
Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion
Imports Microsoft.CodeAnalysis.BraceCompletion.AbstractBraceCompletionService
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion
Public Class AutomaticBraceCompletionTests
Inherits AbstractAutomaticBraceCompletionTests
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestCreation()
Using session = CreateSessionASync("$$")
Assert.NotNull(session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestInvalidLocation_String()
Dim code = <code>Class C
Dim s As String = "$$
End Class</code>
Using session = CreateSession(code)
Assert.Null(session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestInvalidLocation_Comment()
Dim code = <code>Class C
' $$
End Class</code>
Using session = CreateSession(code)
Assert.Null(session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestInvalidLocation_DocComment()
Dim code = <code>Class C
''' $$
End Class</code>
Using session = CreateSession(code)
Assert.Null(session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestTypeParameterMultipleConstraint()
Dim code = <code>Class C
Sub Method(Of t As $$
End Class</code>
Using session = CreateSession(code)
Assert.NotNull(session)
CheckStart(session.Session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestObjectMemberInitializerSyntax()
Dim code = <code>Class C
Sub Method()
Dim a = New With $$
End Sub
End Class</code>
Using session = CreateSession(code)
Assert.NotNull(session)
CheckStart(session.Session)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)>
Public Sub TestCollectionInitializerSyntax()
Dim code = <code>Class C
Sub Method()
Dim a = New List(Of Integer) From $$
End Sub
End Class</code>
Using session = CreateSession(code)
Assert.NotNull(session)
CheckStart(session.Session)
End Using
End Sub
Friend Overloads Shared Function CreateSession(code As XElement) As Holder
Return CreateSessionASync(code.NormalizedValue())
End Function
Friend Overloads Shared Function CreateSessionASync(code As String) As Holder
Return AbstractAutomaticBraceCompletionTests.CreateSession(
TestWorkspace.CreateVisualBasic(code),
CurlyBrace.OpenCharacter, CurlyBrace.CloseCharacter)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Features/Core/Portable/Debugging/IProximityExpressionsService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Debugging
{
internal interface IProximityExpressionsService : ILanguageService
{
Task<IList<string>> GetProximityExpressionsAsync(Document document, int position, CancellationToken cancellationToken);
Task<bool> IsValidAsync(Document document, int position, string expressionValue, 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.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.Debugging
{
internal interface IProximityExpressionsService : ILanguageService
{
Task<IList<string>> GetProximityExpressionsAsync(Document document, int position, CancellationToken cancellationToken);
Task<bool> IsValidAsync(Document document, int position, string expressionValue, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Features/VisualBasic/Portable/CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.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 System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.FindSymbols
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.InlineTemporary
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.InlineTemporary
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InlineTemporary), [Shared]>
Partial Friend Class InlineTemporaryCodeRefactoringProvider
Inherits AbstractInlineTemporaryCodeRefactoringProvider(Of ModifiedIdentifierSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Public Overloads Overrides Async Function ComputeRefactoringsAsync(context As CodeRefactoringContext) As Task
Dim document = context.Document
Dim cancellationToken = context.CancellationToken
Dim workspace = document.Project.Solution.Workspace
If workspace.Kind = WorkspaceKind.MiscellaneousFiles Then
Return
End If
Dim modifiedIdentifier = Await context.TryGetRelevantNodeAsync(Of ModifiedIdentifierSyntax)().ConfigureAwait(False)
If Not modifiedIdentifier.IsParentKind(SyntaxKind.VariableDeclarator) OrElse
Not modifiedIdentifier.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement) Then
Return
End If
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
Dim localDeclarationStatement = DirectCast(variableDeclarator.Parent, LocalDeclarationStatementSyntax)
If Not variableDeclarator.HasInitializer() Then
Return
End If
If localDeclarationStatement.ParentingNodeContainsDiagnostics() Then
Return
End If
Dim references = Await GetReferenceLocationsAsync(document, modifiedIdentifier, cancellationToken).ConfigureAwait(False)
If Not references.Any() Then
Return
End If
context.RegisterRefactoring(
New MyCodeAction(Function(c) InlineTemporaryAsync(document, modifiedIdentifier, c)), variableDeclarator.Span)
End Function
Private Shared Function HasConflict(
identifier As IdentifierNameSyntax,
definition As ModifiedIdentifierSyntax,
expressionToInline As ExpressionSyntax,
semanticModel As SemanticModel
) As Boolean
If identifier.SpanStart < definition.SpanStart Then
Return True
End If
Dim identifierNode = identifier _
.Ancestors() _
.TakeWhile(Function(n)
Return n.Kind = SyntaxKind.ParenthesizedExpression OrElse
TypeOf n Is CastExpressionSyntax OrElse
TypeOf n Is PredefinedCastExpressionSyntax
End Function) _
.LastOrDefault()
If identifierNode Is Nothing Then
identifierNode = identifier
End If
If TypeOf identifierNode.Parent Is AssignmentStatementSyntax Then
Dim assignment = CType(identifierNode.Parent, AssignmentStatementSyntax)
If assignment.Left Is identifierNode Then
Return True
End If
End If
If TypeOf identifierNode.Parent Is ArgumentSyntax Then
If TypeOf expressionToInline Is LiteralExpressionSyntax OrElse
TypeOf expressionToInline Is CastExpressionSyntax OrElse
TypeOf expressionToInline Is PredefinedCastExpressionSyntax Then
Dim argument = DirectCast(identifierNode.Parent, ArgumentSyntax)
Dim parameter = argument.DetermineParameter(semanticModel)
If parameter IsNot Nothing Then
Return parameter.RefKind <> RefKind.None
End If
End If
End If
Return False
End Function
Private Shared ReadOnly s_definitionAnnotation As New SyntaxAnnotation
Private Shared ReadOnly s_referenceAnnotation As New SyntaxAnnotation
Private Shared ReadOnly s_initializerAnnotation As New SyntaxAnnotation
Private Shared ReadOnly s_expressionToInlineAnnotation As New SyntaxAnnotation
Private Shared Async Function InlineTemporaryAsync(document As Document, modifiedIdentifier As ModifiedIdentifierSyntax, cancellationToken As CancellationToken) As Task(Of Document)
' First, annotate the modified identifier so that we can get back to it later.
Dim updatedDocument = Await document.ReplaceNodeAsync(modifiedIdentifier, modifiedIdentifier.WithAdditionalAnnotations(s_definitionAnnotation), cancellationToken).ConfigureAwait(False)
Dim semanticModel = Await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
' Create the expression that we're actually going to inline
Dim expressionToInline = Await CreateExpressionToInlineAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
' Collect the identifier names for each reference.
Dim references = Await GetReferenceLocationsAsync(updatedDocument, modifiedIdentifier, cancellationToken).ConfigureAwait(False)
Dim syntaxRoot = Await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
' Collect the target statement for each reference.
Dim nonConflictingIdentifierNodes = references _
.Select(Function(loc) DirectCast(syntaxRoot.FindToken(loc.Location.SourceSpan.Start).Parent, IdentifierNameSyntax)) _
.Where(Function(ident) Not HasConflict(ident, modifiedIdentifier, expressionToInline, semanticModel))
' Add referenceAnnotations to identifier nodes being replaced.
updatedDocument = Await updatedDocument.ReplaceNodesAsync(
nonConflictingIdentifierNodes,
Function(o, n) n.WithAdditionalAnnotations(s_referenceAnnotation),
cancellationToken).ConfigureAwait(False)
semanticModel = Await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
' Get the annotated reference nodes.
nonConflictingIdentifierNodes = Await FindReferenceAnnotatedNodesAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
Dim topMostStatements = nonConflictingIdentifierNodes _
.Select(Function(ident) GetTopMostStatementForExpression(ident))
' Next, get the top-most statement of the local declaration
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
Dim localDeclaration = DirectCast(variableDeclarator.Parent, LocalDeclarationStatementSyntax)
Dim originalInitializerSymbolInfo = semanticModel.GetSymbolInfo(variableDeclarator.GetInitializer(), cancellationToken)
Dim topMostStatementOfLocalDeclaration = If(localDeclaration.HasAncestor(Of ExpressionSyntax),
localDeclaration.Ancestors().OfType(Of ExpressionSyntax).Last().FirstAncestorOrSelf(Of StatementSyntax)(),
localDeclaration)
topMostStatements = topMostStatements.Concat(topMostStatementOfLocalDeclaration)
' Next get the statements before and after the top-most statement of the local declaration
Dim previousStatement = topMostStatementOfLocalDeclaration.GetPreviousStatement()
If previousStatement IsNot Nothing Then
topMostStatements = topMostStatements.Concat(previousStatement)
End If
' Now, add the statement *after* each top-level statement.
Dim nextStatements = topMostStatements _
.Select(Function(stmt) stmt.GetNextStatement()) _
.WhereNotNull()
topMostStatements = topMostStatements _
.Concat(nextStatements) _
.Distinct()
' Make each target statement semantically explicit.
updatedDocument = Await updatedDocument.ReplaceNodesAsync(
topMostStatements,
Function(o, n)
Return Simplifier.Expand(DirectCast(n, StatementSyntax), semanticModel, document.Project.Solution.Workspace, cancellationToken:=cancellationToken)
End Function,
cancellationToken).ConfigureAwait(False)
semanticModel = Await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
Dim semanticModelBeforeInline = semanticModel
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
Dim scope = GetScope(modifiedIdentifier)
Dim newScope = ReferenceRewriter.Visit(semanticModel, scope, modifiedIdentifier, expressionToInline, cancellationToken)
updatedDocument = Await updatedDocument.ReplaceNodeAsync(scope, newScope.WithAdditionalAnnotations(Formatter.Annotation), cancellationToken).ConfigureAwait(False)
semanticModel = Await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
newScope = GetScope(modifiedIdentifier)
Dim conflicts = newScope.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind)
Dim declaratorConflicts = modifiedIdentifier.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind)
' Note that we only remove the local declaration if there weren't any conflicts,
' unless those conflicts are inside the local declaration.
If conflicts.Count() = declaratorConflicts.Count() Then
' Certain semantic conflicts can be detected only after the reference rewriter has inlined the expression
Dim newDocument = Await DetectSemanticConflictsAsync(updatedDocument,
semanticModel,
semanticModelBeforeInline,
originalInitializerSymbolInfo,
cancellationToken).ConfigureAwait(False)
If updatedDocument Is newDocument Then
' No semantic conflicts, we can remove the definition.
updatedDocument = Await updatedDocument.ReplaceNodeAsync(newScope, RemoveDefinition(modifiedIdentifier, newScope), cancellationToken).ConfigureAwait(False)
Else
' There were some semantic conflicts, don't remove the definition.
updatedDocument = newDocument
End If
End If
Return updatedDocument
End Function
Private Shared Async Function FindDefinitionAsync(document As Document, cancellationToken As CancellationToken) As Task(Of ModifiedIdentifierSyntax)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim result = root _
.GetAnnotatedNodesAndTokens(s_definitionAnnotation) _
.Single() _
.AsNode()
Return DirectCast(result, ModifiedIdentifierSyntax)
End Function
Private Shared Async Function FindReferenceAnnotatedNodesAsync(document As Document, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of IdentifierNameSyntax))
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Return FindReferenceAnnotatedNodes(root)
End Function
Private Shared Iterator Function FindReferenceAnnotatedNodes(root As SyntaxNode) As IEnumerable(Of IdentifierNameSyntax)
Dim annotatedNodesAndTokens = root.GetAnnotatedNodesAndTokens(s_referenceAnnotation)
For Each nodeOrToken In annotatedNodesAndTokens
If nodeOrToken.IsKind(SyntaxKind.IdentifierName) Then
Yield DirectCast(nodeOrToken.AsNode(), IdentifierNameSyntax)
End If
Next
End Function
Private Shared Function GetScope(modifiedIdentifier As ModifiedIdentifierSyntax) As SyntaxNode
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
Dim localDeclaration = DirectCast(variableDeclarator.Parent, LocalDeclarationStatementSyntax)
Return localDeclaration.Parent
End Function
Private Shared Function GetUpdatedDeclaration(modifiedIdentifier As ModifiedIdentifierSyntax) As LocalDeclarationStatementSyntax
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
Dim localDeclaration = DirectCast(variableDeclarator.Parent, LocalDeclarationStatementSyntax)
If localDeclaration.Declarators.Count > 1 And variableDeclarator.Names.Count = 1 Then
Return localDeclaration.RemoveNode(variableDeclarator, SyntaxRemoveOptions.KeepEndOfLine)
End If
If variableDeclarator.Names.Count > 1 Then
Return localDeclaration.RemoveNode(modifiedIdentifier, SyntaxRemoveOptions.KeepEndOfLine)
End If
Throw ExceptionUtilities.Unreachable
End Function
Private Shared Function RemoveDefinition(modifiedIdentifier As ModifiedIdentifierSyntax, newBlock As SyntaxNode) As SyntaxNode
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
Dim localDeclaration = DirectCast(variableDeclarator.Parent, LocalDeclarationStatementSyntax)
If variableDeclarator.Names.Count > 1 OrElse
localDeclaration.Declarators.Count > 1 Then
' In this case, we need to remove the definition from either the declarators or the names of
' the local declaration.
Dim newDeclaration = GetUpdatedDeclaration(modifiedIdentifier) _
.WithAdditionalAnnotations(Formatter.Annotation)
Dim newStatements = newBlock.GetExecutableBlockStatements().Replace(localDeclaration, newDeclaration)
Return newBlock.ReplaceStatements(newStatements)
Else
' In this case, we're removing the local declaration. Care must be taken to move any
' non-whitespace trivia to the next statement.
Dim blockStatements = newBlock.GetExecutableBlockStatements()
Dim declarationIndex = blockStatements.IndexOf(localDeclaration)
Dim leadingTrivia = localDeclaration _
.GetLeadingTrivia() _
.Reverse() _
.SkipWhile(Function(t) t.IsKind(SyntaxKind.WhitespaceTrivia)) _
.Reverse()
Dim trailingTrivia = localDeclaration _
.GetTrailingTrivia() _
.SkipWhile(Function(t) t.IsKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia, SyntaxKind.ColonTrivia))
Dim newLeadingTrivia = leadingTrivia.Concat(trailingTrivia)
' Ensure that we leave a line break if our local declaration ended with a comment.
If newLeadingTrivia.Any() AndAlso newLeadingTrivia.Last().IsKind(SyntaxKind.CommentTrivia) Then
newLeadingTrivia = newLeadingTrivia.Concat(SyntaxFactory.CarriageReturnLineFeed)
End If
Dim nextToken = localDeclaration.GetLastToken().GetNextToken()
Dim newNextToken = nextToken _
.WithPrependedLeadingTrivia(newLeadingTrivia.ToSyntaxTriviaList()) _
.WithAdditionalAnnotations(Formatter.Annotation)
Dim previousToken = localDeclaration.GetFirstToken().GetPreviousToken()
' If the previous token has trailing colon trivia, replace it with a new line.
Dim previousTokenTrailingTrivia = previousToken.TrailingTrivia.ToList()
If previousTokenTrailingTrivia.Count > 0 AndAlso previousTokenTrailingTrivia.Last().IsKind(SyntaxKind.ColonTrivia) Then
previousTokenTrailingTrivia(previousTokenTrailingTrivia.Count - 1) = SyntaxFactory.CarriageReturnLineFeed
End If
Dim newPreviousToken = previousToken _
.WithTrailingTrivia(previousTokenTrailingTrivia) _
.WithAdditionalAnnotations(Formatter.Annotation)
newBlock = newBlock.ReplaceTokens({previousToken, nextToken},
Function(oldToken, newToken)
If oldToken = nextToken Then
Return newNextToken
ElseIf oldToken = previousToken Then
Return newPreviousToken
Else
Return newToken
End If
End Function)
Dim newBlockStatements = newBlock.GetExecutableBlockStatements()
Dim newStatements = newBlockStatements.RemoveAt(declarationIndex)
Return newBlock.ReplaceStatements(newStatements)
End If
End Function
Private Shared Function AddExplicitArgumentListIfNeeded(expression As ExpressionSyntax, semanticModel As SemanticModel) As ExpressionSyntax
If expression.IsKind(SyntaxKind.IdentifierName) OrElse
expression.IsKind(SyntaxKind.GenericName) OrElse
expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Dim symbol = semanticModel.GetSymbolInfo(expression).Symbol
If symbol IsNot Nothing AndAlso
(symbol.Kind = SymbolKind.Method OrElse symbol.Kind = SymbolKind.Property) Then
Dim trailingTrivia = expression.GetTrailingTrivia()
Return SyntaxFactory _
.InvocationExpression(
expression:=expression.WithTrailingTrivia(CType(Nothing, SyntaxTriviaList)),
argumentList:=SyntaxFactory.ArgumentList().WithTrailingTrivia(trailingTrivia)) _
.WithAdditionalAnnotations(Simplifier.Annotation)
End If
End If
Return expression
End Function
Private Shared Async Function CreateExpressionToInlineAsync(document As Document, cancellationToken As CancellationToken) As Task(Of ExpressionSyntax)
' TODO: We should be using a speculative semantic model in the method rather than forking new semantic model every time.
Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
Dim modifiedIdentifier = Await FindDefinitionAsync(document, cancellationToken).ConfigureAwait(False)
Dim initializer = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).GetInitializer()
Dim newInitializer = AddExplicitArgumentListIfNeeded(initializer, semanticModel) _
.WithAdditionalAnnotations(s_initializerAnnotation)
Dim updatedDocument = Await document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken).ConfigureAwait(False)
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
initializer = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).GetInitializer()
Dim explicitInitializer = Await Simplifier.ExpandAsync(initializer, updatedDocument, cancellationToken:=cancellationToken).ConfigureAwait(False)
Dim lastToken = explicitInitializer.GetLastToken()
explicitInitializer = explicitInitializer.ReplaceToken(lastToken, lastToken.WithTrailingTrivia(SyntaxTriviaList.Empty))
updatedDocument = Await updatedDocument.ReplaceNodeAsync(initializer, explicitInitializer, cancellationToken).ConfigureAwait(False)
semanticModel = Await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
explicitInitializer = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).GetInitializer()
Dim local = DirectCast(semanticModel.GetDeclaredSymbol(modifiedIdentifier, cancellationToken), ILocalSymbol)
Dim wasCastAdded As Boolean = False
explicitInitializer = explicitInitializer.CastIfPossible(local.Type,
modifiedIdentifier.SpanStart,
semanticModel,
wasCastAdded,
cancellationToken)
Return explicitInitializer.WithAdditionalAnnotations(s_expressionToInlineAnnotation)
End Function
Private Shared Function GetTopMostStatementForExpression(expression As ExpressionSyntax) As StatementSyntax
Return expression.AncestorsAndSelf().OfType(Of ExpressionSyntax).Last().FirstAncestorOrSelf(Of StatementSyntax)()
End Function
Private Shared Async Function DetectSemanticConflictsAsync(
inlinedDocument As Document,
newSemanticModelForInlinedDocument As SemanticModel,
semanticModelBeforeInline As SemanticModel,
originalInitializerSymbolInfo As SymbolInfo,
cancellationToken As CancellationToken
) As Task(Of Document)
' In this method we detect if inlining the expression introduced the following semantic change:
' The symbol info associated with any of the inlined expressions does not match the symbol info for original initializer expression prior to inline.
' If any semantic changes were introduced by inlining, we update the document with conflict annotations.
' Otherwise we return the given inlined document without any changes.
Dim syntaxRootBeforeInline = Await semanticModelBeforeInline.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(False)
' Get all the identifier nodes which were replaced with inlined expression.
Dim originalIdentifierNodes = FindReferenceAnnotatedNodes(syntaxRootBeforeInline).ToArray()
If originalIdentifierNodes.IsEmpty Then
' No conflicts
Return inlinedDocument
End If
' Get all the inlined expression nodes.
Dim syntaxRootAfterInline = Await inlinedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim inlinedExprNodes = syntaxRootAfterInline.GetAnnotatedNodesAndTokens(s_expressionToInlineAnnotation).ToArray()
Debug.Assert(originalIdentifierNodes.Length = inlinedExprNodes.Length)
Dim replacementNodesWithChangedSemantics As Dictionary(Of SyntaxNode, SyntaxNode) = Nothing
For i = 0 To originalIdentifierNodes.Length - 1
Dim originalNode = originalIdentifierNodes(i)
Dim inlinedNode = DirectCast(inlinedExprNodes(i).AsNode(), ExpressionSyntax)
' inlinedNode is the expanded form of the actual initializer expression in the original document.
' We have annotated the inner initializer with a special syntax annotation "_initializerAnnotation".
' Get this annotated node and compute the symbol info for this node in the inlined document.
Dim innerInitializerInInlineNode = DirectCast(inlinedNode.GetAnnotatedNodesAndTokens(s_initializerAnnotation).Single().AsNode, ExpressionSyntax)
Dim newInitializerSymbolInfo = newSemanticModelForInlinedDocument.GetSymbolInfo(innerInitializerInInlineNode, cancellationToken)
' Verification: The symbol info associated with any of the inlined expressions does not match the symbol info for original initializer expression prior to inline.
If Not SpeculationAnalyzer.SymbolInfosAreCompatible(originalInitializerSymbolInfo, newInitializerSymbolInfo, performEquivalenceCheck:=True) Then
If replacementNodesWithChangedSemantics Is Nothing Then
replacementNodesWithChangedSemantics = New Dictionary(Of SyntaxNode, SyntaxNode)
End If
replacementNodesWithChangedSemantics.Add(inlinedNode, originalNode)
End If
Next
If replacementNodesWithChangedSemantics Is Nothing Then
' No conflicts.
Return inlinedDocument
End If
' Replace the conflicting inlined nodes with the original nodes annotated with conflict annotation.
Dim conflictAnnotationAdder = Function(oldNode As SyntaxNode, newNode As SyntaxNode) As SyntaxNode
Return newNode _
.WithAdditionalAnnotations(ConflictAnnotation.Create(VBFeaturesResources.Conflict_s_detected))
End Function
Return Await inlinedDocument.ReplaceNodesAsync(replacementNodesWithChangedSemantics.Keys, conflictAnnotationAdder, cancellationToken).ConfigureAwait(False)
End Function
Private Class MyCodeAction
Inherits CodeAction.DocumentChangeAction
Public Sub New(createChangedDocument As Func(Of CancellationToken, Task(Of Document)))
MyBase.New(VBFeaturesResources.Inline_temporary_variable, createChangedDocument, NameOf(VBFeaturesResources.Inline_temporary_variable))
End Sub
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports System.Diagnostics.CodeAnalysis
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.FindSymbols
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.InlineTemporary
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.InlineTemporary
<ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.InlineTemporary), [Shared]>
Partial Friend Class InlineTemporaryCodeRefactoringProvider
Inherits AbstractInlineTemporaryCodeRefactoringProvider(Of ModifiedIdentifierSyntax)
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New()
End Sub
Public Overloads Overrides Async Function ComputeRefactoringsAsync(context As CodeRefactoringContext) As Task
Dim document = context.Document
Dim cancellationToken = context.CancellationToken
Dim workspace = document.Project.Solution.Workspace
If workspace.Kind = WorkspaceKind.MiscellaneousFiles Then
Return
End If
Dim modifiedIdentifier = Await context.TryGetRelevantNodeAsync(Of ModifiedIdentifierSyntax)().ConfigureAwait(False)
If Not modifiedIdentifier.IsParentKind(SyntaxKind.VariableDeclarator) OrElse
Not modifiedIdentifier.Parent.IsParentKind(SyntaxKind.LocalDeclarationStatement) Then
Return
End If
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
Dim localDeclarationStatement = DirectCast(variableDeclarator.Parent, LocalDeclarationStatementSyntax)
If Not variableDeclarator.HasInitializer() Then
Return
End If
If localDeclarationStatement.ParentingNodeContainsDiagnostics() Then
Return
End If
Dim references = Await GetReferenceLocationsAsync(document, modifiedIdentifier, cancellationToken).ConfigureAwait(False)
If Not references.Any() Then
Return
End If
context.RegisterRefactoring(
New MyCodeAction(Function(c) InlineTemporaryAsync(document, modifiedIdentifier, c)), variableDeclarator.Span)
End Function
Private Shared Function HasConflict(
identifier As IdentifierNameSyntax,
definition As ModifiedIdentifierSyntax,
expressionToInline As ExpressionSyntax,
semanticModel As SemanticModel
) As Boolean
If identifier.SpanStart < definition.SpanStart Then
Return True
End If
Dim identifierNode = identifier _
.Ancestors() _
.TakeWhile(Function(n)
Return n.Kind = SyntaxKind.ParenthesizedExpression OrElse
TypeOf n Is CastExpressionSyntax OrElse
TypeOf n Is PredefinedCastExpressionSyntax
End Function) _
.LastOrDefault()
If identifierNode Is Nothing Then
identifierNode = identifier
End If
If TypeOf identifierNode.Parent Is AssignmentStatementSyntax Then
Dim assignment = CType(identifierNode.Parent, AssignmentStatementSyntax)
If assignment.Left Is identifierNode Then
Return True
End If
End If
If TypeOf identifierNode.Parent Is ArgumentSyntax Then
If TypeOf expressionToInline Is LiteralExpressionSyntax OrElse
TypeOf expressionToInline Is CastExpressionSyntax OrElse
TypeOf expressionToInline Is PredefinedCastExpressionSyntax Then
Dim argument = DirectCast(identifierNode.Parent, ArgumentSyntax)
Dim parameter = argument.DetermineParameter(semanticModel)
If parameter IsNot Nothing Then
Return parameter.RefKind <> RefKind.None
End If
End If
End If
Return False
End Function
Private Shared ReadOnly s_definitionAnnotation As New SyntaxAnnotation
Private Shared ReadOnly s_referenceAnnotation As New SyntaxAnnotation
Private Shared ReadOnly s_initializerAnnotation As New SyntaxAnnotation
Private Shared ReadOnly s_expressionToInlineAnnotation As New SyntaxAnnotation
Private Shared Async Function InlineTemporaryAsync(document As Document, modifiedIdentifier As ModifiedIdentifierSyntax, cancellationToken As CancellationToken) As Task(Of Document)
' First, annotate the modified identifier so that we can get back to it later.
Dim updatedDocument = Await document.ReplaceNodeAsync(modifiedIdentifier, modifiedIdentifier.WithAdditionalAnnotations(s_definitionAnnotation), cancellationToken).ConfigureAwait(False)
Dim semanticModel = Await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
' Create the expression that we're actually going to inline
Dim expressionToInline = Await CreateExpressionToInlineAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
' Collect the identifier names for each reference.
Dim references = Await GetReferenceLocationsAsync(updatedDocument, modifiedIdentifier, cancellationToken).ConfigureAwait(False)
Dim syntaxRoot = Await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
' Collect the target statement for each reference.
Dim nonConflictingIdentifierNodes = references _
.Select(Function(loc) DirectCast(syntaxRoot.FindToken(loc.Location.SourceSpan.Start).Parent, IdentifierNameSyntax)) _
.Where(Function(ident) Not HasConflict(ident, modifiedIdentifier, expressionToInline, semanticModel))
' Add referenceAnnotations to identifier nodes being replaced.
updatedDocument = Await updatedDocument.ReplaceNodesAsync(
nonConflictingIdentifierNodes,
Function(o, n) n.WithAdditionalAnnotations(s_referenceAnnotation),
cancellationToken).ConfigureAwait(False)
semanticModel = Await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
' Get the annotated reference nodes.
nonConflictingIdentifierNodes = Await FindReferenceAnnotatedNodesAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
Dim topMostStatements = nonConflictingIdentifierNodes _
.Select(Function(ident) GetTopMostStatementForExpression(ident))
' Next, get the top-most statement of the local declaration
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
Dim localDeclaration = DirectCast(variableDeclarator.Parent, LocalDeclarationStatementSyntax)
Dim originalInitializerSymbolInfo = semanticModel.GetSymbolInfo(variableDeclarator.GetInitializer(), cancellationToken)
Dim topMostStatementOfLocalDeclaration = If(localDeclaration.HasAncestor(Of ExpressionSyntax),
localDeclaration.Ancestors().OfType(Of ExpressionSyntax).Last().FirstAncestorOrSelf(Of StatementSyntax)(),
localDeclaration)
topMostStatements = topMostStatements.Concat(topMostStatementOfLocalDeclaration)
' Next get the statements before and after the top-most statement of the local declaration
Dim previousStatement = topMostStatementOfLocalDeclaration.GetPreviousStatement()
If previousStatement IsNot Nothing Then
topMostStatements = topMostStatements.Concat(previousStatement)
End If
' Now, add the statement *after* each top-level statement.
Dim nextStatements = topMostStatements _
.Select(Function(stmt) stmt.GetNextStatement()) _
.WhereNotNull()
topMostStatements = topMostStatements _
.Concat(nextStatements) _
.Distinct()
' Make each target statement semantically explicit.
updatedDocument = Await updatedDocument.ReplaceNodesAsync(
topMostStatements,
Function(o, n)
Return Simplifier.Expand(DirectCast(n, StatementSyntax), semanticModel, document.Project.Solution.Workspace, cancellationToken:=cancellationToken)
End Function,
cancellationToken).ConfigureAwait(False)
semanticModel = Await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
Dim semanticModelBeforeInline = semanticModel
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
Dim scope = GetScope(modifiedIdentifier)
Dim newScope = ReferenceRewriter.Visit(semanticModel, scope, modifiedIdentifier, expressionToInline, cancellationToken)
updatedDocument = Await updatedDocument.ReplaceNodeAsync(scope, newScope.WithAdditionalAnnotations(Formatter.Annotation), cancellationToken).ConfigureAwait(False)
semanticModel = Await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
newScope = GetScope(modifiedIdentifier)
Dim conflicts = newScope.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind)
Dim declaratorConflicts = modifiedIdentifier.GetAnnotatedNodesAndTokens(ConflictAnnotation.Kind)
' Note that we only remove the local declaration if there weren't any conflicts,
' unless those conflicts are inside the local declaration.
If conflicts.Count() = declaratorConflicts.Count() Then
' Certain semantic conflicts can be detected only after the reference rewriter has inlined the expression
Dim newDocument = Await DetectSemanticConflictsAsync(updatedDocument,
semanticModel,
semanticModelBeforeInline,
originalInitializerSymbolInfo,
cancellationToken).ConfigureAwait(False)
If updatedDocument Is newDocument Then
' No semantic conflicts, we can remove the definition.
updatedDocument = Await updatedDocument.ReplaceNodeAsync(newScope, RemoveDefinition(modifiedIdentifier, newScope), cancellationToken).ConfigureAwait(False)
Else
' There were some semantic conflicts, don't remove the definition.
updatedDocument = newDocument
End If
End If
Return updatedDocument
End Function
Private Shared Async Function FindDefinitionAsync(document As Document, cancellationToken As CancellationToken) As Task(Of ModifiedIdentifierSyntax)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim result = root _
.GetAnnotatedNodesAndTokens(s_definitionAnnotation) _
.Single() _
.AsNode()
Return DirectCast(result, ModifiedIdentifierSyntax)
End Function
Private Shared Async Function FindReferenceAnnotatedNodesAsync(document As Document, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of IdentifierNameSyntax))
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Return FindReferenceAnnotatedNodes(root)
End Function
Private Shared Iterator Function FindReferenceAnnotatedNodes(root As SyntaxNode) As IEnumerable(Of IdentifierNameSyntax)
Dim annotatedNodesAndTokens = root.GetAnnotatedNodesAndTokens(s_referenceAnnotation)
For Each nodeOrToken In annotatedNodesAndTokens
If nodeOrToken.IsKind(SyntaxKind.IdentifierName) Then
Yield DirectCast(nodeOrToken.AsNode(), IdentifierNameSyntax)
End If
Next
End Function
Private Shared Function GetScope(modifiedIdentifier As ModifiedIdentifierSyntax) As SyntaxNode
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
Dim localDeclaration = DirectCast(variableDeclarator.Parent, LocalDeclarationStatementSyntax)
Return localDeclaration.Parent
End Function
Private Shared Function GetUpdatedDeclaration(modifiedIdentifier As ModifiedIdentifierSyntax) As LocalDeclarationStatementSyntax
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
Dim localDeclaration = DirectCast(variableDeclarator.Parent, LocalDeclarationStatementSyntax)
If localDeclaration.Declarators.Count > 1 And variableDeclarator.Names.Count = 1 Then
Return localDeclaration.RemoveNode(variableDeclarator, SyntaxRemoveOptions.KeepEndOfLine)
End If
If variableDeclarator.Names.Count > 1 Then
Return localDeclaration.RemoveNode(modifiedIdentifier, SyntaxRemoveOptions.KeepEndOfLine)
End If
Throw ExceptionUtilities.Unreachable
End Function
Private Shared Function RemoveDefinition(modifiedIdentifier As ModifiedIdentifierSyntax, newBlock As SyntaxNode) As SyntaxNode
Dim variableDeclarator = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax)
Dim localDeclaration = DirectCast(variableDeclarator.Parent, LocalDeclarationStatementSyntax)
If variableDeclarator.Names.Count > 1 OrElse
localDeclaration.Declarators.Count > 1 Then
' In this case, we need to remove the definition from either the declarators or the names of
' the local declaration.
Dim newDeclaration = GetUpdatedDeclaration(modifiedIdentifier) _
.WithAdditionalAnnotations(Formatter.Annotation)
Dim newStatements = newBlock.GetExecutableBlockStatements().Replace(localDeclaration, newDeclaration)
Return newBlock.ReplaceStatements(newStatements)
Else
' In this case, we're removing the local declaration. Care must be taken to move any
' non-whitespace trivia to the next statement.
Dim blockStatements = newBlock.GetExecutableBlockStatements()
Dim declarationIndex = blockStatements.IndexOf(localDeclaration)
Dim leadingTrivia = localDeclaration _
.GetLeadingTrivia() _
.Reverse() _
.SkipWhile(Function(t) t.IsKind(SyntaxKind.WhitespaceTrivia)) _
.Reverse()
Dim trailingTrivia = localDeclaration _
.GetTrailingTrivia() _
.SkipWhile(Function(t) t.IsKind(SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia, SyntaxKind.ColonTrivia))
Dim newLeadingTrivia = leadingTrivia.Concat(trailingTrivia)
' Ensure that we leave a line break if our local declaration ended with a comment.
If newLeadingTrivia.Any() AndAlso newLeadingTrivia.Last().IsKind(SyntaxKind.CommentTrivia) Then
newLeadingTrivia = newLeadingTrivia.Concat(SyntaxFactory.CarriageReturnLineFeed)
End If
Dim nextToken = localDeclaration.GetLastToken().GetNextToken()
Dim newNextToken = nextToken _
.WithPrependedLeadingTrivia(newLeadingTrivia.ToSyntaxTriviaList()) _
.WithAdditionalAnnotations(Formatter.Annotation)
Dim previousToken = localDeclaration.GetFirstToken().GetPreviousToken()
' If the previous token has trailing colon trivia, replace it with a new line.
Dim previousTokenTrailingTrivia = previousToken.TrailingTrivia.ToList()
If previousTokenTrailingTrivia.Count > 0 AndAlso previousTokenTrailingTrivia.Last().IsKind(SyntaxKind.ColonTrivia) Then
previousTokenTrailingTrivia(previousTokenTrailingTrivia.Count - 1) = SyntaxFactory.CarriageReturnLineFeed
End If
Dim newPreviousToken = previousToken _
.WithTrailingTrivia(previousTokenTrailingTrivia) _
.WithAdditionalAnnotations(Formatter.Annotation)
newBlock = newBlock.ReplaceTokens({previousToken, nextToken},
Function(oldToken, newToken)
If oldToken = nextToken Then
Return newNextToken
ElseIf oldToken = previousToken Then
Return newPreviousToken
Else
Return newToken
End If
End Function)
Dim newBlockStatements = newBlock.GetExecutableBlockStatements()
Dim newStatements = newBlockStatements.RemoveAt(declarationIndex)
Return newBlock.ReplaceStatements(newStatements)
End If
End Function
Private Shared Function AddExplicitArgumentListIfNeeded(expression As ExpressionSyntax, semanticModel As SemanticModel) As ExpressionSyntax
If expression.IsKind(SyntaxKind.IdentifierName) OrElse
expression.IsKind(SyntaxKind.GenericName) OrElse
expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Dim symbol = semanticModel.GetSymbolInfo(expression).Symbol
If symbol IsNot Nothing AndAlso
(symbol.Kind = SymbolKind.Method OrElse symbol.Kind = SymbolKind.Property) Then
Dim trailingTrivia = expression.GetTrailingTrivia()
Return SyntaxFactory _
.InvocationExpression(
expression:=expression.WithTrailingTrivia(CType(Nothing, SyntaxTriviaList)),
argumentList:=SyntaxFactory.ArgumentList().WithTrailingTrivia(trailingTrivia)) _
.WithAdditionalAnnotations(Simplifier.Annotation)
End If
End If
Return expression
End Function
Private Shared Async Function CreateExpressionToInlineAsync(document As Document, cancellationToken As CancellationToken) As Task(Of ExpressionSyntax)
' TODO: We should be using a speculative semantic model in the method rather than forking new semantic model every time.
Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
Dim modifiedIdentifier = Await FindDefinitionAsync(document, cancellationToken).ConfigureAwait(False)
Dim initializer = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).GetInitializer()
Dim newInitializer = AddExplicitArgumentListIfNeeded(initializer, semanticModel) _
.WithAdditionalAnnotations(s_initializerAnnotation)
Dim updatedDocument = Await document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken).ConfigureAwait(False)
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
initializer = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).GetInitializer()
Dim explicitInitializer = Await Simplifier.ExpandAsync(initializer, updatedDocument, cancellationToken:=cancellationToken).ConfigureAwait(False)
Dim lastToken = explicitInitializer.GetLastToken()
explicitInitializer = explicitInitializer.ReplaceToken(lastToken, lastToken.WithTrailingTrivia(SyntaxTriviaList.Empty))
updatedDocument = Await updatedDocument.ReplaceNodeAsync(initializer, explicitInitializer, cancellationToken).ConfigureAwait(False)
semanticModel = Await updatedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
modifiedIdentifier = Await FindDefinitionAsync(updatedDocument, cancellationToken).ConfigureAwait(False)
explicitInitializer = DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).GetInitializer()
Dim local = DirectCast(semanticModel.GetDeclaredSymbol(modifiedIdentifier, cancellationToken), ILocalSymbol)
Dim wasCastAdded As Boolean = False
explicitInitializer = explicitInitializer.CastIfPossible(local.Type,
modifiedIdentifier.SpanStart,
semanticModel,
wasCastAdded,
cancellationToken)
Return explicitInitializer.WithAdditionalAnnotations(s_expressionToInlineAnnotation)
End Function
Private Shared Function GetTopMostStatementForExpression(expression As ExpressionSyntax) As StatementSyntax
Return expression.AncestorsAndSelf().OfType(Of ExpressionSyntax).Last().FirstAncestorOrSelf(Of StatementSyntax)()
End Function
Private Shared Async Function DetectSemanticConflictsAsync(
inlinedDocument As Document,
newSemanticModelForInlinedDocument As SemanticModel,
semanticModelBeforeInline As SemanticModel,
originalInitializerSymbolInfo As SymbolInfo,
cancellationToken As CancellationToken
) As Task(Of Document)
' In this method we detect if inlining the expression introduced the following semantic change:
' The symbol info associated with any of the inlined expressions does not match the symbol info for original initializer expression prior to inline.
' If any semantic changes were introduced by inlining, we update the document with conflict annotations.
' Otherwise we return the given inlined document without any changes.
Dim syntaxRootBeforeInline = Await semanticModelBeforeInline.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(False)
' Get all the identifier nodes which were replaced with inlined expression.
Dim originalIdentifierNodes = FindReferenceAnnotatedNodes(syntaxRootBeforeInline).ToArray()
If originalIdentifierNodes.IsEmpty Then
' No conflicts
Return inlinedDocument
End If
' Get all the inlined expression nodes.
Dim syntaxRootAfterInline = Await inlinedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim inlinedExprNodes = syntaxRootAfterInline.GetAnnotatedNodesAndTokens(s_expressionToInlineAnnotation).ToArray()
Debug.Assert(originalIdentifierNodes.Length = inlinedExprNodes.Length)
Dim replacementNodesWithChangedSemantics As Dictionary(Of SyntaxNode, SyntaxNode) = Nothing
For i = 0 To originalIdentifierNodes.Length - 1
Dim originalNode = originalIdentifierNodes(i)
Dim inlinedNode = DirectCast(inlinedExprNodes(i).AsNode(), ExpressionSyntax)
' inlinedNode is the expanded form of the actual initializer expression in the original document.
' We have annotated the inner initializer with a special syntax annotation "_initializerAnnotation".
' Get this annotated node and compute the symbol info for this node in the inlined document.
Dim innerInitializerInInlineNode = DirectCast(inlinedNode.GetAnnotatedNodesAndTokens(s_initializerAnnotation).Single().AsNode, ExpressionSyntax)
Dim newInitializerSymbolInfo = newSemanticModelForInlinedDocument.GetSymbolInfo(innerInitializerInInlineNode, cancellationToken)
' Verification: The symbol info associated with any of the inlined expressions does not match the symbol info for original initializer expression prior to inline.
If Not SpeculationAnalyzer.SymbolInfosAreCompatible(originalInitializerSymbolInfo, newInitializerSymbolInfo, performEquivalenceCheck:=True) Then
If replacementNodesWithChangedSemantics Is Nothing Then
replacementNodesWithChangedSemantics = New Dictionary(Of SyntaxNode, SyntaxNode)
End If
replacementNodesWithChangedSemantics.Add(inlinedNode, originalNode)
End If
Next
If replacementNodesWithChangedSemantics Is Nothing Then
' No conflicts.
Return inlinedDocument
End If
' Replace the conflicting inlined nodes with the original nodes annotated with conflict annotation.
Dim conflictAnnotationAdder = Function(oldNode As SyntaxNode, newNode As SyntaxNode) As SyntaxNode
Return newNode _
.WithAdditionalAnnotations(ConflictAnnotation.Create(VBFeaturesResources.Conflict_s_detected))
End Function
Return Await inlinedDocument.ReplaceNodesAsync(replacementNodesWithChangedSemantics.Keys, conflictAnnotationAdder, cancellationToken).ConfigureAwait(False)
End Function
Private Class MyCodeAction
Inherits CodeAction.DocumentChangeAction
Public Sub New(createChangedDocument As Func(Of CancellationToken, Task(Of Document)))
MyBase.New(VBFeaturesResources.Inline_temporary_variable, createChangedDocument, NameOf(VBFeaturesResources.Inline_temporary_variable))
End Sub
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/VisualStudio/CSharp/Test/CodeModel/FileCodeVariableTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeVariableTests : AbstractFileCodeElementTests
{
public FileCodeVariableTests()
: base(@"using System;
public class A
{
// This is a comment.
public int intA;
/// <summary>
/// This is a summary.
/// </summary>
protected int intB;
[Serializable]
private int intC = 4;
int intD;
public static const int FORTYTWO = 42;
}
unsafe public struct DevDivBugs70194
{
fixed char buffer[100];
}")
{
}
private CodeVariable GetCodeVariable(params object[] path)
{
return (CodeVariable)GetCodeElement(path);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Access_Public()
{
var testObject = GetCodeVariable("A", "intA");
Assert.Equal(vsCMAccess.vsCMAccessPublic, testObject.Access);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Access_Protected()
{
var testObject = GetCodeVariable("A", "intB");
Assert.Equal(vsCMAccess.vsCMAccessProtected, testObject.Access);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Access_Private()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal(vsCMAccess.vsCMAccessPrivate, testObject.Access);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Attributes_Count()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal(1, testObject.Attributes.Count);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Children_Count()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal(1, testObject.Children.Count);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Comment()
{
var testObject = GetCodeVariable("A", "intA");
Assert.Equal("This is a comment.\r\n", testObject.Comment);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void DocComment()
{
var testObject = GetCodeVariable("A", "intB");
var expected = "<doc>\r\n<summary>\r\nThis is a summary.\r\n</summary>\r\n</doc>";
Assert.Equal(expected, testObject.DocComment);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void InitExpressions_NoExpression()
{
var testObject = GetCodeVariable("A", "intB");
Assert.Null(testObject.InitExpression);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void InitExpression()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal("4", testObject.InitExpression);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void InitExpression_FixedBuffer()
{
var testObject = GetCodeVariable("DevDivBugs70194", "buffer");
Assert.Null(testObject.InitExpression);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsConstant_True()
{
var testObject = GetCodeVariable("A", "FORTYTWO");
Assert.True(testObject.IsConstant);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsConstant_False()
{
var testObject = GetCodeVariable("A", "intC");
Assert.False(testObject.IsConstant);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsShared_True()
{
var testObject = GetCodeVariable("A", "FORTYTWO");
Assert.True(testObject.IsShared);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsShared_False()
{
var testObject = GetCodeVariable("A", "intC");
Assert.False(testObject.IsShared);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Kind()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal(vsCMElement.vsCMElementVariable, testObject.Kind);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Parent()
{
var testObject = GetCodeVariable("A", "intC");
var testObjectParent = testObject.Parent as CodeClass;
Assert.Equal("A", testObjectParent.Name);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Type()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal("System.Int32", testObject.Type.AsFullName);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
var testObject = GetCodeVariable("A", "intC");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(13, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<COMException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBody));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
var testObject = GetCodeVariable("A", "intC");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(14, startPoint.Line);
Assert.Equal(17, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
var testObject = GetCodeVariable("A", "intC");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(13, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
var testObject = GetCodeVariable("A", "intC");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(13, endPoint.Line);
Assert.Equal(19, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<COMException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartBody));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
var testObject = GetCodeVariable("A", "intC");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(14, endPoint.Line);
Assert.Equal(21, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
var testObject = GetCodeVariable("A", "intC");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(14, endPoint.Line);
Assert.Equal(26, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
var testObject = GetCodeVariable("A", "intC");
var startPoint = testObject.StartPoint;
Assert.Equal(13, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
var testObject = GetCodeVariable("A", "intC");
var endPoint = testObject.EndPoint;
Assert.Equal(14, endPoint.Line);
Assert.Equal(26, endPoint.LineCharOffset);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests.CodeModel
{
public class FileCodeVariableTests : AbstractFileCodeElementTests
{
public FileCodeVariableTests()
: base(@"using System;
public class A
{
// This is a comment.
public int intA;
/// <summary>
/// This is a summary.
/// </summary>
protected int intB;
[Serializable]
private int intC = 4;
int intD;
public static const int FORTYTWO = 42;
}
unsafe public struct DevDivBugs70194
{
fixed char buffer[100];
}")
{
}
private CodeVariable GetCodeVariable(params object[] path)
{
return (CodeVariable)GetCodeElement(path);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Access_Public()
{
var testObject = GetCodeVariable("A", "intA");
Assert.Equal(vsCMAccess.vsCMAccessPublic, testObject.Access);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Access_Protected()
{
var testObject = GetCodeVariable("A", "intB");
Assert.Equal(vsCMAccess.vsCMAccessProtected, testObject.Access);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Access_Private()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal(vsCMAccess.vsCMAccessPrivate, testObject.Access);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Attributes_Count()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal(1, testObject.Attributes.Count);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Children_Count()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal(1, testObject.Children.Count);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Comment()
{
var testObject = GetCodeVariable("A", "intA");
Assert.Equal("This is a comment.\r\n", testObject.Comment);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void DocComment()
{
var testObject = GetCodeVariable("A", "intB");
var expected = "<doc>\r\n<summary>\r\nThis is a summary.\r\n</summary>\r\n</doc>";
Assert.Equal(expected, testObject.DocComment);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void InitExpressions_NoExpression()
{
var testObject = GetCodeVariable("A", "intB");
Assert.Null(testObject.InitExpression);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void InitExpression()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal("4", testObject.InitExpression);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void InitExpression_FixedBuffer()
{
var testObject = GetCodeVariable("DevDivBugs70194", "buffer");
Assert.Null(testObject.InitExpression);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsConstant_True()
{
var testObject = GetCodeVariable("A", "FORTYTWO");
Assert.True(testObject.IsConstant);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsConstant_False()
{
var testObject = GetCodeVariable("A", "intC");
Assert.False(testObject.IsConstant);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsShared_True()
{
var testObject = GetCodeVariable("A", "FORTYTWO");
Assert.True(testObject.IsShared);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void IsShared_False()
{
var testObject = GetCodeVariable("A", "intC");
Assert.False(testObject.IsShared);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Kind()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal(vsCMElement.vsCMElementVariable, testObject.Kind);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Parent()
{
var testObject = GetCodeVariable("A", "intC");
var testObjectParent = testObject.Parent as CodeClass;
Assert.Equal("A", testObjectParent.Name);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void Type()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Equal("System.Int32", testObject.Type.AsFullName);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Attributes()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_AttributesWithDelimiter()
{
var testObject = GetCodeVariable("A", "intC");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(13, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Body()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<COMException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBody));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_BodyWithDelimiter()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Header()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_HeaderWithAttributes()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Name()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Navigate()
{
var testObject = GetCodeVariable("A", "intC");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(14, startPoint.Line);
Assert.Equal(17, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_Whole()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetStartPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetStartPoint_WholeWithAttributes()
{
var testObject = GetCodeVariable("A", "intC");
var startPoint = testObject.GetStartPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(13, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Attributes()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_AttributesWithDelimiter()
{
var testObject = GetCodeVariable("A", "intC");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartAttributesWithDelimiter);
Assert.Equal(13, endPoint.Line);
Assert.Equal(19, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Body()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<COMException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartBody));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_BodyWithDelimiter()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartBodyWithDelimiter));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Header()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeader));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_HeaderWithAttributes()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartHeaderWithAttributes));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Name()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartName));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Navigate()
{
var testObject = GetCodeVariable("A", "intC");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartNavigate);
Assert.Equal(14, endPoint.Line);
Assert.Equal(21, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_Whole()
{
var testObject = GetCodeVariable("A", "intC");
Assert.Throws<NotImplementedException>(() => testObject.GetEndPoint(vsCMPart.vsCMPartWhole));
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void GetEndPoint_WholeWithAttributes()
{
var testObject = GetCodeVariable("A", "intC");
var endPoint = testObject.GetEndPoint(vsCMPart.vsCMPartWholeWithAttributes);
Assert.Equal(14, endPoint.Line);
Assert.Equal(26, endPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void StartPoint()
{
var testObject = GetCodeVariable("A", "intC");
var startPoint = testObject.StartPoint;
Assert.Equal(13, startPoint.Line);
Assert.Equal(5, startPoint.LineCharOffset);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.CodeModel)]
public void EndPoint()
{
var testObject = GetCodeVariable("A", "intC");
var endPoint = testObject.EndPoint;
Assert.Equal(14, endPoint.Line);
Assert.Equal(26, endPoint.LineCharOffset);
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/CSharpTest/MakeRefStruct/MakeRefStructTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.MakeRefStruct;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeRefStruct
{
public class MakeRefStructTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
private static readonly CSharpParseOptions s_parseOptions =
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3);
public MakeRefStructTests(ITestOutputHelper logger)
: base(logger)
{
}
private const string SpanDeclarationSourceText = @"
using System;
namespace System
{
public readonly ref struct Span<T>
{
unsafe public Span(void* pointer, int length) { }
}
}
";
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new MakeRefStructCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task FieldInNotRefStruct()
{
var text = CreateTestSource(@"
struct S
{
Span<int>[||] m;
}
");
var expected = CreateTestSource(@"
ref struct S
{
Span<int> m;
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task FieldInRecordStruct()
{
var text = CreateTestSource(@"
record struct S
{
Span<int>[||] m;
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task FieldInNestedClassInsideNotRefStruct()
{
var text = CreateTestSource(@"
struct S
{
class C
{
Span<int>[||] m;
}
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(s_parseOptions));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task FieldStaticInRefStruct()
{
// Note: does not compile
var text = CreateTestSource(@"
ref struct S
{
static Span<int>[||] m;
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(s_parseOptions));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task FieldStaticInNotRefStruct()
{
var text = CreateTestSource(@"
struct S
{
static Span<int>[||] m;
}
");
// Note: still does not compile after fix
var expected = CreateTestSource(@"
ref struct S
{
static Span<int> m;
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PropInNotRefStruct()
{
var text = CreateTestSource(@"
struct S
{
Span<int>[||] M { get; }
}
");
var expected = CreateTestSource(@"
ref struct S
{
Span<int> M { get; }
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PropInNestedClassInsideNotRefStruct()
{
// Note: does not compile
var text = CreateTestSource(@"
struct S
{
class C
{
Span<int>[||] M { get; }
}
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(s_parseOptions));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PropStaticInRefStruct()
{
// Note: does not compile
var text = CreateTestSource(@"
ref struct S
{
static Span<int>[||] M { get; }
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(s_parseOptions));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PropStaticInNotRefStruct()
{
var text = CreateTestSource(@"
struct S
{
static Span<int>[||] M { get; }
}
");
// Note: still does not compile after fix
var expected = CreateTestSource(@"
ref struct S
{
static Span<int> M { get; }
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PartialByRefStruct()
{
var text = CreateTestSource(@"
ref partial struct S
{
}
struct S
{
Span<int>[||] M { get; }
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(s_parseOptions));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PartialStruct()
{
var text = CreateTestSource(@"
partial struct S
{
}
partial struct S
{
Span<int>[||] M { get; }
}
");
var expected = CreateTestSource(@"
partial struct S
{
}
ref partial struct S
{
Span<int>[||] M { get; }
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task ReadonlyPartialStruct()
{
var text = CreateTestSource(@"
partial struct S
{
}
readonly partial struct S
{
Span<int>[||] M { get; }
}
");
var expected = CreateTestSource(@"
partial struct S
{
}
readonly ref partial struct S
{
Span<int>[||] M { get; }
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
private static string CreateTestSource(string testSource) => SpanDeclarationSourceText + testSource;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.MakeRefStruct;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.MakeRefStruct
{
public class MakeRefStructTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
private static readonly CSharpParseOptions s_parseOptions =
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3);
public MakeRefStructTests(ITestOutputHelper logger)
: base(logger)
{
}
private const string SpanDeclarationSourceText = @"
using System;
namespace System
{
public readonly ref struct Span<T>
{
unsafe public Span(void* pointer, int length) { }
}
}
";
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new MakeRefStructCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task FieldInNotRefStruct()
{
var text = CreateTestSource(@"
struct S
{
Span<int>[||] m;
}
");
var expected = CreateTestSource(@"
ref struct S
{
Span<int> m;
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task FieldInRecordStruct()
{
var text = CreateTestSource(@"
record struct S
{
Span<int>[||] m;
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task FieldInNestedClassInsideNotRefStruct()
{
var text = CreateTestSource(@"
struct S
{
class C
{
Span<int>[||] m;
}
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(s_parseOptions));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task FieldStaticInRefStruct()
{
// Note: does not compile
var text = CreateTestSource(@"
ref struct S
{
static Span<int>[||] m;
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(s_parseOptions));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task FieldStaticInNotRefStruct()
{
var text = CreateTestSource(@"
struct S
{
static Span<int>[||] m;
}
");
// Note: still does not compile after fix
var expected = CreateTestSource(@"
ref struct S
{
static Span<int> m;
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PropInNotRefStruct()
{
var text = CreateTestSource(@"
struct S
{
Span<int>[||] M { get; }
}
");
var expected = CreateTestSource(@"
ref struct S
{
Span<int> M { get; }
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PropInNestedClassInsideNotRefStruct()
{
// Note: does not compile
var text = CreateTestSource(@"
struct S
{
class C
{
Span<int>[||] M { get; }
}
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(s_parseOptions));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PropStaticInRefStruct()
{
// Note: does not compile
var text = CreateTestSource(@"
ref struct S
{
static Span<int>[||] M { get; }
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(s_parseOptions));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PropStaticInNotRefStruct()
{
var text = CreateTestSource(@"
struct S
{
static Span<int>[||] M { get; }
}
");
// Note: still does not compile after fix
var expected = CreateTestSource(@"
ref struct S
{
static Span<int> M { get; }
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PartialByRefStruct()
{
var text = CreateTestSource(@"
ref partial struct S
{
}
struct S
{
Span<int>[||] M { get; }
}
");
await TestMissingInRegularAndScriptAsync(text, new TestParameters(s_parseOptions));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task PartialStruct()
{
var text = CreateTestSource(@"
partial struct S
{
}
partial struct S
{
Span<int>[||] M { get; }
}
");
var expected = CreateTestSource(@"
partial struct S
{
}
ref partial struct S
{
Span<int>[||] M { get; }
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMakeRefStruct)]
public async Task ReadonlyPartialStruct()
{
var text = CreateTestSource(@"
partial struct S
{
}
readonly partial struct S
{
Span<int>[||] M { get; }
}
");
var expected = CreateTestSource(@"
partial struct S
{
}
readonly ref partial struct S
{
Span<int>[||] M { get; }
}
");
await TestInRegularAndScriptAsync(text, expected, parseOptions: s_parseOptions);
}
private static string CreateTestSource(string testSource) => SpanDeclarationSourceText + testSource;
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptDebugLocationInfoWrapper.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal readonly struct VSTypeScriptDebugLocationInfoWrapper
{
internal readonly DebugLocationInfo UnderlyingObject;
public VSTypeScriptDebugLocationInfoWrapper(string name, int lineOffset)
=> UnderlyingObject = new DebugLocationInfo(name, lineOffset);
public readonly string Name => UnderlyingObject.Name;
public readonly int LineOffset => UnderlyingObject.LineOffset;
internal 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;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal readonly struct VSTypeScriptDebugLocationInfoWrapper
{
internal readonly DebugLocationInfo UnderlyingObject;
public VSTypeScriptDebugLocationInfoWrapper(string name, int lineOffset)
=> UnderlyingObject = new DebugLocationInfo(name, lineOffset);
public readonly string Name => UnderlyingObject.Name;
public readonly int LineOffset => UnderlyingObject.LineOffset;
internal bool IsDefault => UnderlyingObject.IsDefault;
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/InterfaceKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class InterfaceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.InternalKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.UnsafeKeyword
};
public InterfaceKeywordRecommender()
: base(SyntaxKind.InterfaceKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsGlobalStatementContext ||
context.IsTypeDeclarationContext(
validModifiers: s_validModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: true,
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.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class InterfaceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer)
{
SyntaxKind.InternalKeyword,
SyntaxKind.PublicKeyword,
SyntaxKind.PrivateKeyword,
SyntaxKind.ProtectedKeyword,
SyntaxKind.UnsafeKeyword
};
public InterfaceKeywordRecommender()
: base(SyntaxKind.InterfaceKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsGlobalStatementContext ||
context.IsTypeDeclarationContext(
validModifiers: s_validModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: true,
cancellationToken: cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 55,866 | Remove langver == preview restriction for incremental generators | Fixes https://github.com/dotnet/roslyn/issues/55848 | chsienki | 2021-08-24T20:29:36Z | 2021-08-26T06:49:51Z | 4b78a9f2f2bea5e2960066c1915f26dc26f3819a | b1e9f5c997a29f0f2b9a320314ae2c9054d80168 | Remove langver == preview restriction for incremental generators. Fixes https://github.com/dotnet/roslyn/issues/55848 | ./src/Features/CSharp/Portable/ExtractMethod/CSharpMethodExtractor.CSharpCodeGenerator.CallSiteContainerRewriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private abstract partial class CSharpCodeGenerator
{
private class CallSiteContainerRewriter : CSharpSyntaxRewriter
{
private readonly SyntaxNode _outmostCallSiteContainer;
private readonly IEnumerable<SyntaxNode> _statementsOrMemberOrAccessorToInsert;
private readonly HashSet<SyntaxAnnotation> _variableToRemoveMap;
private readonly SyntaxNode _firstStatementOrFieldToReplace;
private readonly SyntaxNode _lastStatementOrFieldToReplace;
public CallSiteContainerRewriter(
SyntaxNode outmostCallSiteContainer,
HashSet<SyntaxAnnotation> variableToRemoveMap,
SyntaxNode firstStatementOrFieldToReplace,
SyntaxNode lastStatementOrFieldToReplace,
IEnumerable<SyntaxNode> statementsOrFieldToInsert)
{
Contract.ThrowIfNull(outmostCallSiteContainer);
Contract.ThrowIfNull(variableToRemoveMap);
Contract.ThrowIfNull(firstStatementOrFieldToReplace);
Contract.ThrowIfNull(lastStatementOrFieldToReplace);
Contract.ThrowIfNull(statementsOrFieldToInsert);
Contract.ThrowIfTrue(statementsOrFieldToInsert.IsEmpty());
_outmostCallSiteContainer = outmostCallSiteContainer;
_variableToRemoveMap = variableToRemoveMap;
_statementsOrMemberOrAccessorToInsert = statementsOrFieldToInsert;
_firstStatementOrFieldToReplace = firstStatementOrFieldToReplace;
_lastStatementOrFieldToReplace = lastStatementOrFieldToReplace;
Contract.ThrowIfFalse(_firstStatementOrFieldToReplace.Parent == _lastStatementOrFieldToReplace.Parent);
}
public SyntaxNode Generate()
=> Visit(_outmostCallSiteContainer);
private SyntaxNode ContainerOfStatementsOrFieldToReplace => _firstStatementOrFieldToReplace.Parent;
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);
var list = new List<VariableDeclaratorSyntax>();
var triviaList = new List<SyntaxTrivia>();
// go through each var decls in decl statement
foreach (var variable in node.Declaration.Variables)
{
if (_variableToRemoveMap.HasSyntaxAnnotation(variable))
{
// if it had initialization, it shouldn't reach here.
Contract.ThrowIfFalse(variable.Initializer == null);
// we don't remove trivia around tokens we remove
triviaList.AddRange(variable.GetLeadingTrivia());
triviaList.AddRange(variable.GetTrailingTrivia());
continue;
}
if (triviaList.Count > 0)
{
list.Add(variable.WithPrependedLeadingTrivia(triviaList));
triviaList.Clear();
continue;
}
list.Add(variable);
}
if (list.Count == 0)
{
// nothing has survived. remove this from the list
if (triviaList.Count == 0)
{
return null;
}
// well, there are trivia associated with the node.
// we can't just delete the node since then, we will lose
// the trivia. unfortunately, it is not easy to attach the trivia
// to next token. for now, create an empty statement and associate the
// trivia to the statement
// TODO : think about a way to move the trivia to next token.
return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)));
}
if (list.Count == node.Declaration.Variables.Count)
{
// nothing has changed, return as it is
return node;
}
// TODO : fix how it manipulate trivia later
// if there is left over syntax trivia, it will be attached to leading trivia
// of semicolon
return
SyntaxFactory.LocalDeclarationStatement(
node.Modifiers,
SyntaxFactory.VariableDeclaration(
node.Declaration.Type,
SyntaxFactory.SeparatedList(list)),
node.SemicolonToken.WithPrependedLeadingTrivia(triviaList));
}
// for every kind of extract methods
public override SyntaxNode VisitBlock(BlockSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
// make sure we visit nodes under the block
return base.VisitBlock(node);
}
return node.WithStatements(VisitList(ReplaceStatements(node.Statements)).ToSyntaxList());
}
public override SyntaxNode VisitSwitchSection(SwitchSectionSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
// make sure we visit nodes under the switch section
return base.VisitSwitchSection(node);
}
return node.WithStatements(VisitList(ReplaceStatements(node.Statements)).ToSyntaxList());
}
// only for single statement or expression
public override SyntaxNode VisitLabeledStatement(LabeledStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitLabeledStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitElseClause(ElseClauseSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitElseClause(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitIfStatement(IfStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitIfStatement(node);
}
return node.WithCondition(VisitNode(node.Condition))
.WithStatement(ReplaceStatementIfNeeded(node.Statement))
.WithElse(VisitNode(node.Else));
}
public override SyntaxNode VisitLockStatement(LockStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitLockStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitFixedStatement(FixedStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitFixedStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitUsingStatement(UsingStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitUsingStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForEachStatement(ForEachStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForEachStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForEachVariableStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForStatement(ForStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithInitializers(VisitList(node.Initializers))
.WithCondition(VisitNode(node.Condition))
.WithIncrementors(VisitList(node.Incrementors))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitDoStatement(DoStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitDoStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement))
.WithCondition(VisitNode(node.Condition));
}
public override SyntaxNode VisitWhileStatement(WhileStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitWhileStatement(node);
}
return node.WithCondition(VisitNode(node.Condition))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
private TNode VisitNode<TNode>(TNode node) where TNode : SyntaxNode
=> (TNode)Visit(node);
private StatementSyntax ReplaceStatementIfNeeded(StatementSyntax statement)
{
Contract.ThrowIfNull(statement);
// if all three same
if ((statement != _firstStatementOrFieldToReplace) || (_firstStatementOrFieldToReplace != _lastStatementOrFieldToReplace))
{
return statement;
}
// replace one statement with another
if (_statementsOrMemberOrAccessorToInsert.Count() == 1)
{
return _statementsOrMemberOrAccessorToInsert.Cast<StatementSyntax>().Single();
}
// replace one statement with multiple statements (see bug # 6310)
return SyntaxFactory.Block(SyntaxFactory.List(_statementsOrMemberOrAccessorToInsert.Cast<StatementSyntax>()));
}
private SyntaxList<TSyntax> ReplaceList<TSyntax>(SyntaxList<TSyntax> list)
where TSyntax : SyntaxNode
{
// okay, this visit contains the statement
var newList = new List<TSyntax>(list);
var firstIndex = newList.FindIndex(s => s == _firstStatementOrFieldToReplace);
Contract.ThrowIfFalse(firstIndex >= 0);
var lastIndex = newList.FindIndex(s => s == _lastStatementOrFieldToReplace);
Contract.ThrowIfFalse(lastIndex >= 0);
Contract.ThrowIfFalse(firstIndex <= lastIndex);
// remove statement that must be removed
newList.RemoveRange(firstIndex, lastIndex - firstIndex + 1);
// add new statements to replace
newList.InsertRange(firstIndex, _statementsOrMemberOrAccessorToInsert.Cast<TSyntax>());
return newList.ToSyntaxList();
}
private SyntaxList<StatementSyntax> ReplaceStatements(SyntaxList<StatementSyntax> statements)
=> ReplaceList(statements);
private SyntaxList<AccessorDeclarationSyntax> ReplaceAccessors(SyntaxList<AccessorDeclarationSyntax> accessors)
=> ReplaceList(accessors);
private SyntaxList<MemberDeclarationSyntax> ReplaceMembers(SyntaxList<MemberDeclarationSyntax> members, bool global)
{
// okay, this visit contains the statement
var newMembers = new List<MemberDeclarationSyntax>(members);
var firstMemberIndex = newMembers.FindIndex(s => s == (global ? _firstStatementOrFieldToReplace.Parent : _firstStatementOrFieldToReplace));
Contract.ThrowIfFalse(firstMemberIndex >= 0);
var lastMemberIndex = newMembers.FindIndex(s => s == (global ? _lastStatementOrFieldToReplace.Parent : _lastStatementOrFieldToReplace));
Contract.ThrowIfFalse(lastMemberIndex >= 0);
Contract.ThrowIfFalse(firstMemberIndex <= lastMemberIndex);
// remove statement that must be removed
newMembers.RemoveRange(firstMemberIndex, lastMemberIndex - firstMemberIndex + 1);
// add new statements to replace
newMembers.InsertRange(firstMemberIndex,
_statementsOrMemberOrAccessorToInsert.Select(s => global ? SyntaxFactory.GlobalStatement((StatementSyntax)s) : (MemberDeclarationSyntax)s));
return newMembers.ToSyntaxList();
}
public override SyntaxNode VisitGlobalStatement(GlobalStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitGlobalStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitInterfaceDeclaration(InterfaceDeclarationSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitInterfaceDeclaration(node);
}
return GetUpdatedTypeDeclaration(node);
}
public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitConstructorDeclaration(node);
}
Contract.ThrowIfFalse(_firstStatementOrFieldToReplace == _lastStatementOrFieldToReplace);
return node.WithInitializer((ConstructorInitializerSyntax)_statementsOrMemberOrAccessorToInsert.Single());
}
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitClassDeclaration(node);
}
return GetUpdatedTypeDeclaration(node);
}
public override SyntaxNode VisitRecordDeclaration(RecordDeclarationSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitRecordDeclaration(node);
}
return GetUpdatedTypeDeclaration(node);
}
public override SyntaxNode VisitStructDeclaration(StructDeclarationSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitStructDeclaration(node);
}
return GetUpdatedTypeDeclaration(node);
}
public override SyntaxNode VisitAccessorList(AccessorListSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitAccessorList(node);
}
var newAccessors = VisitList(ReplaceAccessors(node.Accessors));
return node.WithAccessors(newAccessors);
}
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace.Parent)
{
// make sure we visit nodes under the block
return base.VisitCompilationUnit(node);
}
var newMembers = VisitList(ReplaceMembers(node.Members, global: true));
return node.WithMembers(newMembers);
}
private SyntaxNode GetUpdatedTypeDeclaration(TypeDeclarationSyntax node)
{
var newMembers = VisitList(ReplaceMembers(node.Members, global: false));
return node.WithMembers(newMembers);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private abstract partial class CSharpCodeGenerator
{
private class CallSiteContainerRewriter : CSharpSyntaxRewriter
{
private readonly SyntaxNode _outmostCallSiteContainer;
private readonly IEnumerable<SyntaxNode> _statementsOrMemberOrAccessorToInsert;
private readonly HashSet<SyntaxAnnotation> _variableToRemoveMap;
private readonly SyntaxNode _firstStatementOrFieldToReplace;
private readonly SyntaxNode _lastStatementOrFieldToReplace;
public CallSiteContainerRewriter(
SyntaxNode outmostCallSiteContainer,
HashSet<SyntaxAnnotation> variableToRemoveMap,
SyntaxNode firstStatementOrFieldToReplace,
SyntaxNode lastStatementOrFieldToReplace,
IEnumerable<SyntaxNode> statementsOrFieldToInsert)
{
Contract.ThrowIfNull(outmostCallSiteContainer);
Contract.ThrowIfNull(variableToRemoveMap);
Contract.ThrowIfNull(firstStatementOrFieldToReplace);
Contract.ThrowIfNull(lastStatementOrFieldToReplace);
Contract.ThrowIfNull(statementsOrFieldToInsert);
Contract.ThrowIfTrue(statementsOrFieldToInsert.IsEmpty());
_outmostCallSiteContainer = outmostCallSiteContainer;
_variableToRemoveMap = variableToRemoveMap;
_statementsOrMemberOrAccessorToInsert = statementsOrFieldToInsert;
_firstStatementOrFieldToReplace = firstStatementOrFieldToReplace;
_lastStatementOrFieldToReplace = lastStatementOrFieldToReplace;
Contract.ThrowIfFalse(_firstStatementOrFieldToReplace.Parent == _lastStatementOrFieldToReplace.Parent);
}
public SyntaxNode Generate()
=> Visit(_outmostCallSiteContainer);
private SyntaxNode ContainerOfStatementsOrFieldToReplace => _firstStatementOrFieldToReplace.Parent;
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);
var list = new List<VariableDeclaratorSyntax>();
var triviaList = new List<SyntaxTrivia>();
// go through each var decls in decl statement
foreach (var variable in node.Declaration.Variables)
{
if (_variableToRemoveMap.HasSyntaxAnnotation(variable))
{
// if it had initialization, it shouldn't reach here.
Contract.ThrowIfFalse(variable.Initializer == null);
// we don't remove trivia around tokens we remove
triviaList.AddRange(variable.GetLeadingTrivia());
triviaList.AddRange(variable.GetTrailingTrivia());
continue;
}
if (triviaList.Count > 0)
{
list.Add(variable.WithPrependedLeadingTrivia(triviaList));
triviaList.Clear();
continue;
}
list.Add(variable);
}
if (list.Count == 0)
{
// nothing has survived. remove this from the list
if (triviaList.Count == 0)
{
return null;
}
// well, there are trivia associated with the node.
// we can't just delete the node since then, we will lose
// the trivia. unfortunately, it is not easy to attach the trivia
// to next token. for now, create an empty statement and associate the
// trivia to the statement
// TODO : think about a way to move the trivia to next token.
return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)));
}
if (list.Count == node.Declaration.Variables.Count)
{
// nothing has changed, return as it is
return node;
}
// TODO : fix how it manipulate trivia later
// if there is left over syntax trivia, it will be attached to leading trivia
// of semicolon
return
SyntaxFactory.LocalDeclarationStatement(
node.Modifiers,
SyntaxFactory.VariableDeclaration(
node.Declaration.Type,
SyntaxFactory.SeparatedList(list)),
node.SemicolonToken.WithPrependedLeadingTrivia(triviaList));
}
// for every kind of extract methods
public override SyntaxNode VisitBlock(BlockSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
// make sure we visit nodes under the block
return base.VisitBlock(node);
}
return node.WithStatements(VisitList(ReplaceStatements(node.Statements)).ToSyntaxList());
}
public override SyntaxNode VisitSwitchSection(SwitchSectionSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
// make sure we visit nodes under the switch section
return base.VisitSwitchSection(node);
}
return node.WithStatements(VisitList(ReplaceStatements(node.Statements)).ToSyntaxList());
}
// only for single statement or expression
public override SyntaxNode VisitLabeledStatement(LabeledStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitLabeledStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitElseClause(ElseClauseSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitElseClause(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitIfStatement(IfStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitIfStatement(node);
}
return node.WithCondition(VisitNode(node.Condition))
.WithStatement(ReplaceStatementIfNeeded(node.Statement))
.WithElse(VisitNode(node.Else));
}
public override SyntaxNode VisitLockStatement(LockStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitLockStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitFixedStatement(FixedStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitFixedStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitUsingStatement(UsingStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitUsingStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForEachStatement(ForEachStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForEachStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForEachVariableStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForStatement(ForStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithInitializers(VisitList(node.Initializers))
.WithCondition(VisitNode(node.Condition))
.WithIncrementors(VisitList(node.Incrementors))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitDoStatement(DoStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitDoStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement))
.WithCondition(VisitNode(node.Condition));
}
public override SyntaxNode VisitWhileStatement(WhileStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitWhileStatement(node);
}
return node.WithCondition(VisitNode(node.Condition))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
private TNode VisitNode<TNode>(TNode node) where TNode : SyntaxNode
=> (TNode)Visit(node);
private StatementSyntax ReplaceStatementIfNeeded(StatementSyntax statement)
{
Contract.ThrowIfNull(statement);
// if all three same
if ((statement != _firstStatementOrFieldToReplace) || (_firstStatementOrFieldToReplace != _lastStatementOrFieldToReplace))
{
return statement;
}
// replace one statement with another
if (_statementsOrMemberOrAccessorToInsert.Count() == 1)
{
return _statementsOrMemberOrAccessorToInsert.Cast<StatementSyntax>().Single();
}
// replace one statement with multiple statements (see bug # 6310)
return SyntaxFactory.Block(SyntaxFactory.List(_statementsOrMemberOrAccessorToInsert.Cast<StatementSyntax>()));
}
private SyntaxList<TSyntax> ReplaceList<TSyntax>(SyntaxList<TSyntax> list)
where TSyntax : SyntaxNode
{
// okay, this visit contains the statement
var newList = new List<TSyntax>(list);
var firstIndex = newList.FindIndex(s => s == _firstStatementOrFieldToReplace);
Contract.ThrowIfFalse(firstIndex >= 0);
var lastIndex = newList.FindIndex(s => s == _lastStatementOrFieldToReplace);
Contract.ThrowIfFalse(lastIndex >= 0);
Contract.ThrowIfFalse(firstIndex <= lastIndex);
// remove statement that must be removed
newList.RemoveRange(firstIndex, lastIndex - firstIndex + 1);
// add new statements to replace
newList.InsertRange(firstIndex, _statementsOrMemberOrAccessorToInsert.Cast<TSyntax>());
return newList.ToSyntaxList();
}
private SyntaxList<StatementSyntax> ReplaceStatements(SyntaxList<StatementSyntax> statements)
=> ReplaceList(statements);
private SyntaxList<AccessorDeclarationSyntax> ReplaceAccessors(SyntaxList<AccessorDeclarationSyntax> accessors)
=> ReplaceList(accessors);
private SyntaxList<MemberDeclarationSyntax> ReplaceMembers(SyntaxList<MemberDeclarationSyntax> members, bool global)
{
// okay, this visit contains the statement
var newMembers = new List<MemberDeclarationSyntax>(members);
var firstMemberIndex = newMembers.FindIndex(s => s == (global ? _firstStatementOrFieldToReplace.Parent : _firstStatementOrFieldToReplace));
Contract.ThrowIfFalse(firstMemberIndex >= 0);
var lastMemberIndex = newMembers.FindIndex(s => s == (global ? _lastStatementOrFieldToReplace.Parent : _lastStatementOrFieldToReplace));
Contract.ThrowIfFalse(lastMemberIndex >= 0);
Contract.ThrowIfFalse(firstMemberIndex <= lastMemberIndex);
// remove statement that must be removed
newMembers.RemoveRange(firstMemberIndex, lastMemberIndex - firstMemberIndex + 1);
// add new statements to replace
newMembers.InsertRange(firstMemberIndex,
_statementsOrMemberOrAccessorToInsert.Select(s => global ? SyntaxFactory.GlobalStatement((StatementSyntax)s) : (MemberDeclarationSyntax)s));
return newMembers.ToSyntaxList();
}
public override SyntaxNode VisitGlobalStatement(GlobalStatementSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitGlobalStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitInterfaceDeclaration(InterfaceDeclarationSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitInterfaceDeclaration(node);
}
return GetUpdatedTypeDeclaration(node);
}
public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitConstructorDeclaration(node);
}
Contract.ThrowIfFalse(_firstStatementOrFieldToReplace == _lastStatementOrFieldToReplace);
return node.WithInitializer((ConstructorInitializerSyntax)_statementsOrMemberOrAccessorToInsert.Single());
}
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitClassDeclaration(node);
}
return GetUpdatedTypeDeclaration(node);
}
public override SyntaxNode VisitRecordDeclaration(RecordDeclarationSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitRecordDeclaration(node);
}
return GetUpdatedTypeDeclaration(node);
}
public override SyntaxNode VisitStructDeclaration(StructDeclarationSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitStructDeclaration(node);
}
return GetUpdatedTypeDeclaration(node);
}
public override SyntaxNode VisitAccessorList(AccessorListSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace)
{
return base.VisitAccessorList(node);
}
var newAccessors = VisitList(ReplaceAccessors(node.Accessors));
return node.WithAccessors(newAccessors);
}
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
if (node != ContainerOfStatementsOrFieldToReplace.Parent)
{
// make sure we visit nodes under the block
return base.VisitCompilationUnit(node);
}
var newMembers = VisitList(ReplaceMembers(node.Members, global: true));
return node.WithMembers(newMembers);
}
private SyntaxNode GetUpdatedTypeDeclaration(TypeDeclarationSyntax node)
{
var newMembers = VisitList(ReplaceMembers(node.Members, global: false));
return node.WithMembers(newMembers);
}
}
}
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.