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,876 | EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime | Fixes https://github.com/dotnet/roslyn/issues/54676
Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all. | davidwengier | 2021-08-25T03:54:26Z | 2021-08-25T23:32:55Z | cb18669598e9b49e5cba0ef6439e1c9ac3df97ac | 18556e82c3c4e4a861987b4cb5379764d6c17422 | EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676
Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceServices/SemanticModelReuse/SemanticModelReuseWorkspaceServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.SemanticModelReuse
{
[ExportWorkspaceServiceFactory(typeof(ISemanticModelReuseWorkspaceService), ServiceLayer.Default), Shared]
internal partial class SemanticModelReuseWorkspaceServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SemanticModelReuseWorkspaceServiceFactory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new SemanticModelReuseWorkspaceService(workspaceServices.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.
using System;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.SemanticModelReuse
{
[ExportWorkspaceServiceFactory(typeof(ISemanticModelReuseWorkspaceService), ServiceLayer.Default), Shared]
internal partial class SemanticModelReuseWorkspaceServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SemanticModelReuseWorkspaceServiceFactory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new SemanticModelReuseWorkspaceService(workspaceServices.Workspace);
}
}
| -1 |
dotnet/roslyn | 55,876 | EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime | Fixes https://github.com/dotnet/roslyn/issues/54676
Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all. | davidwengier | 2021-08-25T03:54:26Z | 2021-08-25T23:32:55Z | cb18669598e9b49e5cba0ef6439e1c9ac3df97ac | 18556e82c3c4e4a861987b4cb5379764d6c17422 | EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676
Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all. | ./src/Workspaces/Core/Portable/Workspace/Host/DocumentService/IDocumentService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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>
/// Empty interface just to mark document services.
/// </summary>
internal interface IDocumentService
{
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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>
/// Empty interface just to mark document services.
/// </summary>
internal interface IDocumentService
{
}
}
| -1 |
dotnet/roslyn | 55,876 | EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime | Fixes https://github.com/dotnet/roslyn/issues/54676
Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all. | davidwengier | 2021-08-25T03:54:26Z | 2021-08-25T23:32:55Z | cb18669598e9b49e5cba0ef6439e1c9ac3df97ac | 18556e82c3c4e4a861987b4cb5379764d6c17422 | EnC - Report diagnostic when compiler synthesizes new types on unsupported runtime. Fixes https://github.com/dotnet/roslyn/issues/54676
Could follow up with more specific rude edit based diagnostics for specific scenarios, but I like this as a safety net to catch them all. | ./src/Test/Perf/StackDepthTest/runner.csx | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
var args = System.Environment.GetCommandLineArgs();
if (args.Length != 4)
{
Console.WriteLine("Usage: runner.csx <path/to/StackDepthTest.exe> <upper bound>");
foreach (var s in args)
{
Console.WriteLine(s);
}
return -1;
}
var testerLocation = args[2];
var upperBound = 0;
if (int.TryParse(args[3], out var ub))
{
upperBound = ub;
}
else
{
Console.WriteLine("<upper bound> must be an integer");
return -1;
}
bool runTest(int n)
{
var proc = System.Diagnostics.Process.Start(testerLocation, $"{n}");
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();
return proc.ExitCode == 0;
}
// Sanity check
if (!runTest(0))
{
Console.WriteLine("Test failed on the lower bound!");
return -1;
}
if (runTest(upperBound))
{
Console.WriteLine("Test passed on the upper bound!");
return -1;
}
var low = 0;
var high = upperBound;
while (low != high)
{
var mid = (low + high) / 2;
if (mid == low || mid == high) { break; }
Console.Write($"Running {mid}: ");
if (runTest(mid))
{
low = mid;
Console.WriteLine("pass");
}
else
{
high = mid;
Console.WriteLine("fail");
}
}
Console.WriteLine($"Break even point: {low}");
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
var args = System.Environment.GetCommandLineArgs();
if (args.Length != 4)
{
Console.WriteLine("Usage: runner.csx <path/to/StackDepthTest.exe> <upper bound>");
foreach (var s in args)
{
Console.WriteLine(s);
}
return -1;
}
var testerLocation = args[2];
var upperBound = 0;
if (int.TryParse(args[3], out var ub))
{
upperBound = ub;
}
else
{
Console.WriteLine("<upper bound> must be an integer");
return -1;
}
bool runTest(int n)
{
var proc = System.Diagnostics.Process.Start(testerLocation, $"{n}");
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();
return proc.ExitCode == 0;
}
// Sanity check
if (!runTest(0))
{
Console.WriteLine("Test failed on the lower bound!");
return -1;
}
if (runTest(upperBound))
{
Console.WriteLine("Test passed on the upper bound!");
return -1;
}
var low = 0;
var high = upperBound;
while (low != high)
{
var mid = (low + high) / 2;
if (mid == low || mid == high) { break; }
Console.Write($"Running {mid}: ");
if (runTest(mid))
{
low = mid;
Console.WriteLine("pass");
}
else
{
high = mid;
Console.WriteLine("fail");
}
}
Console.WriteLine($"Break even point: {low}");
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Features/Core/Portable/UnusedReferences/ReferenceInfo.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.UnusedReferences
{
[DataContract]
internal class ReferenceInfo
{
/// <summary>
/// Indicates the type of reference.
/// </summary>
[DataMember(Order = 0)]
public ReferenceType ReferenceType { get; }
/// <summary>
/// Uniquely identifies the reference.
/// </summary>
/// <remarks>
/// Should match the Include or Name attribute used in the project file.
/// </remarks>
[DataMember(Order = 1)]
public string ItemSpecification { get; }
/// <summary>
/// Indicates that this reference should be treated as if it were used.
/// </summary>
[DataMember(Order = 2)]
public bool TreatAsUsed { get; }
/// <summary>
/// The full assembly paths that this reference directly adds to the compilation.
/// </summary>
[DataMember(Order = 3)]
public ImmutableArray<string> CompilationAssemblies { get; }
/// <summary>
/// The dependencies that this reference transitively brings in to the compilation.
/// </summary>
[DataMember(Order = 4)]
public ImmutableArray<ReferenceInfo> Dependencies { get; }
public ReferenceInfo(ReferenceType referenceType, string itemSpecification, bool treatAsUsed, ImmutableArray<string> compilationAssemblies, ImmutableArray<ReferenceInfo> dependencies)
{
ReferenceType = referenceType;
ItemSpecification = itemSpecification;
TreatAsUsed = treatAsUsed;
CompilationAssemblies = compilationAssemblies;
Dependencies = dependencies;
}
public ReferenceInfo WithItemSpecification(string itemSpecification)
=> new(ReferenceType, itemSpecification, TreatAsUsed, CompilationAssemblies, Dependencies);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Runtime.Serialization;
namespace Microsoft.CodeAnalysis.UnusedReferences
{
[DataContract]
internal class ReferenceInfo
{
/// <summary>
/// Indicates the type of reference.
/// </summary>
[DataMember(Order = 0)]
public ReferenceType ReferenceType { get; }
/// <summary>
/// Uniquely identifies the reference.
/// </summary>
/// <remarks>
/// Should match the Include or Name attribute used in the project file.
/// </remarks>
[DataMember(Order = 1)]
public string ItemSpecification { get; }
/// <summary>
/// Indicates that this reference should be treated as if it were used.
/// </summary>
[DataMember(Order = 2)]
public bool TreatAsUsed { get; }
/// <summary>
/// The full assembly paths that this reference directly adds to the compilation.
/// </summary>
[DataMember(Order = 3)]
public ImmutableArray<string> CompilationAssemblies { get; }
/// <summary>
/// The dependencies that this reference transitively brings in to the compilation.
/// </summary>
[DataMember(Order = 4)]
public ImmutableArray<ReferenceInfo> Dependencies { get; }
public ReferenceInfo(ReferenceType referenceType, string itemSpecification, bool treatAsUsed, ImmutableArray<string> compilationAssemblies, ImmutableArray<ReferenceInfo> dependencies)
{
ReferenceType = referenceType;
ItemSpecification = itemSpecification;
TreatAsUsed = treatAsUsed;
CompilationAssemblies = compilationAssemblies;
Dependencies = dependencies;
}
public ReferenceInfo WithItemSpecification(string itemSpecification)
=> new(ReferenceType, itemSpecification, TreatAsUsed, CompilationAssemblies, Dependencies);
public ReferenceInfo WithDependencies(IEnumerable<ReferenceInfo>? dependencies)
=> new(ReferenceType, ItemSpecification, TreatAsUsed, CompilationAssemblies, dependencies.AsImmutableOrEmpty());
}
}
| 1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/VisualStudio/Core/Def/Implementation/UnusedReferences/UnusedReferenceAnalysisService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets;
namespace Microsoft.CodeAnalysis.UnusedReferences
{
[ExportWorkspaceService(typeof(IUnusedReferenceAnalysisService)), Shared]
internal partial class UnusedReferenceAnalysisService : IUnusedReferenceAnalysisService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UnusedReferenceAnalysisService()
{
}
public async Task<ImmutableArray<ReferenceInfo>> GetUnusedReferencesAsync(Solution solution, string projectFilePath, string projectAssetsFilePath, ImmutableArray<ReferenceInfo> projectReferences, CancellationToken cancellationToken)
{
using var logger = Logger.LogBlock(FunctionId.UnusedReferences_GetUnusedReferences, message: null, cancellationToken, LogLevel.Information);
var client = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false);
if (client != null)
{
var result = await client.TryInvokeAsync<IRemoteUnusedReferenceAnalysisService, ImmutableArray<ReferenceInfo>>(
solution,
(service, solutionInfo, cancellationToken) => service.GetUnusedReferencesAsync(solutionInfo, projectFilePath, projectAssetsFilePath, projectReferences, cancellationToken),
cancellationToken).ConfigureAwait(false);
if (!result.HasValue)
{
return ImmutableArray<ReferenceInfo>.Empty;
}
return result.Value;
}
var references = await ProjectAssetsFileReader.ReadReferencesAsync(projectReferences, projectAssetsFilePath).ConfigureAwait(false);
return await UnusedReferencesRemover.GetUnusedReferencesAsync(solution, projectFilePath, references, cancellationToken).ConfigureAwait(false);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets;
namespace Microsoft.CodeAnalysis.UnusedReferences
{
[ExportWorkspaceService(typeof(IUnusedReferenceAnalysisService)), Shared]
internal partial class UnusedReferenceAnalysisService : IUnusedReferenceAnalysisService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UnusedReferenceAnalysisService()
{
}
public async Task<ImmutableArray<ReferenceInfo>> GetUnusedReferencesAsync(Solution solution, string projectFilePath, string projectAssetsFilePath, ImmutableArray<ReferenceInfo> projectReferences, CancellationToken cancellationToken)
{
using var logger = Logger.LogBlock(FunctionId.UnusedReferences_GetUnusedReferences, message: null, cancellationToken, LogLevel.Information);
var client = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false);
if (client != null)
{
var result = await client.TryInvokeAsync<IRemoteUnusedReferenceAnalysisService, ImmutableArray<ReferenceInfo>>(
solution,
(service, solutionInfo, cancellationToken) => service.GetUnusedReferencesAsync(solutionInfo, projectFilePath, projectAssetsFilePath, projectReferences, cancellationToken),
cancellationToken).ConfigureAwait(false);
if (!result.HasValue)
{
return ImmutableArray<ReferenceInfo>.Empty;
}
return result.Value;
}
// Read specified references with dependency information from the project assets file.
var references = await ProjectAssetsFileReader.ReadReferencesAsync(projectReferences, projectAssetsFilePath).ConfigureAwait(false);
// Determine unused references
var unusedReferences = await UnusedReferencesRemover.GetUnusedReferencesAsync(solution, projectFilePath, references, cancellationToken).ConfigureAwait(false);
// Remove dependency information before returning.
return unusedReferences.SelectAsArray(reference => reference.WithDependencies(null));
}
}
}
| 1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Workspaces/Remote/ServiceHub/Services/UnusedReferences/RemoteUnusedReferenceAnalysisService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.UnusedReferences;
using Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets;
namespace Microsoft.CodeAnalysis.Remote
{
internal sealed class RemoteUnusedReferenceAnalysisService : BrokeredServiceBase, IRemoteUnusedReferenceAnalysisService
{
internal sealed class Factory : FactoryBase<IRemoteUnusedReferenceAnalysisService>
{
protected override IRemoteUnusedReferenceAnalysisService CreateService(in ServiceConstructionArguments arguments)
=> new RemoteUnusedReferenceAnalysisService(arguments);
}
public RemoteUnusedReferenceAnalysisService(ServiceConstructionArguments arguments)
: base(arguments)
{
}
public ValueTask<ImmutableArray<ReferenceInfo>> GetUnusedReferencesAsync(PinnedSolutionInfo solutionInfo, string projectFilePath, string projectAssetsFilePath, ImmutableArray<ReferenceInfo> projectReferences, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
var references = await ProjectAssetsFileReader.ReadReferencesAsync(projectReferences, projectAssetsFilePath).ConfigureAwait(false);
return await UnusedReferencesRemover.GetUnusedReferencesAsync(solution, projectFilePath, references, cancellationToken).ConfigureAwait(false);
}, 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.UnusedReferences;
using Microsoft.CodeAnalysis.UnusedReferences.ProjectAssets;
namespace Microsoft.CodeAnalysis.Remote
{
internal sealed class RemoteUnusedReferenceAnalysisService : BrokeredServiceBase, IRemoteUnusedReferenceAnalysisService
{
internal sealed class Factory : FactoryBase<IRemoteUnusedReferenceAnalysisService>
{
protected override IRemoteUnusedReferenceAnalysisService CreateService(in ServiceConstructionArguments arguments)
=> new RemoteUnusedReferenceAnalysisService(arguments);
}
public RemoteUnusedReferenceAnalysisService(ServiceConstructionArguments arguments)
: base(arguments)
{
}
public ValueTask<ImmutableArray<ReferenceInfo>> GetUnusedReferencesAsync(PinnedSolutionInfo solutionInfo, string projectFilePath, string projectAssetsFilePath, ImmutableArray<ReferenceInfo> projectReferences, CancellationToken cancellationToken)
{
return RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false);
// Read specified references with dependency information from the project assets file.
var references = await ProjectAssetsFileReader.ReadReferencesAsync(projectReferences, projectAssetsFilePath).ConfigureAwait(false);
// Determine unused references
var unusedReferences = await UnusedReferencesRemover.GetUnusedReferencesAsync(solution, projectFilePath, references, cancellationToken).ConfigureAwait(false);
// Remove dependency information before returning.
return unusedReferences.SelectAsArray(reference => reference.WithDependencies(null));
}, cancellationToken);
}
}
}
| 1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Workspaces/Core/Portable/Options/PerLanguageOption2_operators.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Options
{
internal partial class PerLanguageOption2<T>
{
[return: NotNullIfNotNull("option")]
public static explicit operator PerLanguageOption<T>?(PerLanguageOption2<T>? option)
{
if (option is null)
{
return null;
}
return new PerLanguageOption<T>(option.OptionDefinition, option.StorageLocations.As<OptionStorageLocation>());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Options
{
internal partial class PerLanguageOption2<T>
{
[return: NotNullIfNotNull("option")]
public static explicit operator PerLanguageOption<T>?(PerLanguageOption2<T>? option)
{
if (option is null)
{
return null;
}
return new PerLanguageOption<T>(option.OptionDefinition, option.StorageLocations.As<OptionStorageLocation>());
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter.DecisionDagRewriter.ValueDispatchNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
private abstract partial class DecisionDagRewriter
{
/// <summary>
/// A node in a tree representing the form of a generated decision tree for classifying an input value.
/// </summary>
private abstract class ValueDispatchNode
{
protected virtual int Height => 1;
#if DEBUG
protected virtual int Weight => 1;
#endif
public readonly SyntaxNode Syntax;
public ValueDispatchNode(SyntaxNode syntax) => Syntax = syntax;
/// <summary>
/// A node representing the dispatch by value (equality). This corresponds to a classical C switch
/// statement, except that it also handles values of type float, double, decimal, and string.
/// </summary>
internal sealed class SwitchDispatch : ValueDispatchNode
{
public readonly ImmutableArray<(ConstantValue value, LabelSymbol label)> Cases;
public readonly LabelSymbol Otherwise;
public SwitchDispatch(SyntaxNode syntax, ImmutableArray<(ConstantValue value, LabelSymbol label)> dispatches, LabelSymbol otherwise) : base(syntax)
{
this.Cases = dispatches;
this.Otherwise = otherwise;
}
public override string ToString() => "[" + string.Join(",", Cases.Select(c => c.value)) + "]";
}
/// <summary>
/// A node representing a final destination that requires no further dispatch.
/// </summary>
internal sealed class LeafDispatchNode : ValueDispatchNode
{
public readonly LabelSymbol Label;
public LeafDispatchNode(SyntaxNode syntax, LabelSymbol Label) : base(syntax) => this.Label = Label;
public override string ToString() => "Leaf";
}
/// <summary>
/// A node representing a dispatch based on a relational test of the input value by some constant.
/// Nodes of this kind are required to be height-balanced when constructed, so that when the full
/// decision tree is produced it generates a balanced tree of comparisons. The shape of the tree
/// keeps tests for lower values on the left and tests for higher values on the right:
/// For <see cref="BinaryOperatorKind.LessThan"/> and <see cref="BinaryOperatorKind.LessThanOrEqual"/>,
/// the <see cref="WhenTrue"/> branch is <see cref="Left"/> and the <see cref="WhenFalse"/> branch
/// is <see cref="Right"/>; for <see cref="BinaryOperatorKind.GreaterThan"/> and
/// <see cref="BinaryOperatorKind.GreaterThanOrEqual"/> it is reversed.
/// See <see cref="IsReversed(BinaryOperatorKind)"/> for where that is computed.
/// </summary>
internal sealed class RelationalDispatch : ValueDispatchNode
{
private int _height;
#if DEBUG
private int _weight;
#endif
protected override int Height => _height;
#if DEBUG
protected override int Weight => _weight;
#endif
public readonly ConstantValue Value;
public readonly BinaryOperatorKind Operator;
/// <summary>The side of the test handling lower values. The true side for < and <=, the false side for > and >=.</summary>
private ValueDispatchNode Left { get; set; }
/// <summary>The side of the test handling higher values. The false side for < and <=, the true side for > and >=.</summary>
private ValueDispatchNode Right { get; set; }
private RelationalDispatch(SyntaxNode syntax, ConstantValue value, BinaryOperatorKind op, ValueDispatchNode left, ValueDispatchNode right) : base(syntax)
{
Debug.Assert(op.OperandTypes() != 0);
this.Value = value;
this.Operator = op;
WithLeftAndRight(left, right);
}
public ValueDispatchNode WhenTrue => IsReversed(Operator) ? Right : Left;
public ValueDispatchNode WhenFalse => IsReversed(Operator) ? Left : Right;
public override string ToString() => $"RelationalDispatch.{Height}({Left} {Operator.Operator()} {Value} {Right})";
/// <summary>
/// Is the operator among those for which <see cref="WhenTrue"/> is <see cref="Right"/>?
/// </summary>
private static bool IsReversed(BinaryOperatorKind op) => op.Operator() switch { BinaryOperatorKind.GreaterThan => true, BinaryOperatorKind.GreaterThanOrEqual => true, _ => false };
private RelationalDispatch WithLeftAndRight(ValueDispatchNode left, ValueDispatchNode right)
{
// Note that this is a destructive implementation to reduce GC garbage.
// That requires clients to stop using the input node once this has been called.
int l = left.Height;
int r = right.Height;
Debug.Assert(Math.Abs(l - r) <= 1);
this.Left = left;
this.Right = right;
_height = Math.Max(l, r) + 1;
#if DEBUG
_weight = left.Weight + right.Weight + 1;
// Assert that the node is approximately balanced
Debug.Assert(_height < 2 * Math.Log(_weight));
#endif
return this;
}
public RelationalDispatch WithTrueAndFalseChildren(ValueDispatchNode whenTrue, ValueDispatchNode whenFalse)
{
if (whenTrue == this.WhenTrue && whenFalse == this.WhenFalse)
return this;
Debug.Assert(whenTrue.Height == this.WhenTrue.Height);
Debug.Assert(whenFalse.Height == this.WhenFalse.Height);
var (left, right) = IsReversed(Operator) ? (whenFalse, whenTrue) : (whenTrue, whenFalse);
return WithLeftAndRight(left, right);
}
public static ValueDispatchNode CreateBalanced(SyntaxNode syntax, ConstantValue value, BinaryOperatorKind op, ValueDispatchNode whenTrue, ValueDispatchNode whenFalse)
{
// Keep the lower numbers on the left and the higher numbers on the right.
var (left, right) = IsReversed(op) ? (whenFalse, whenTrue) : (whenTrue, whenFalse);
return CreateBalancedCore(syntax, value, op, left: left, right: right);
}
private static ValueDispatchNode CreateBalancedCore(SyntaxNode syntax, ConstantValue value, BinaryOperatorKind op, ValueDispatchNode left, ValueDispatchNode right)
{
Debug.Assert(op.OperandTypes() != 0);
// Build a height-balanced tree node that is semantically equivalent to a node with the given parameters.
// See http://www.cs.ecu.edu/karl/3300/spr16/Notes/DataStructure/Tree/balance.html
// First, build an approximately balanced left and right bottom-up.
if (left.Height > (right.Height + 1))
{
var l = (RelationalDispatch)left;
var newRight = CreateBalancedCore(syntax, value, op, left: l.Right, right: right);
(syntax, value, op, left, right) = (l.Syntax, l.Value, l.Operator, l.Left, newRight);
}
else if (right.Height > (left.Height + 1))
{
var r = (RelationalDispatch)right;
var newLeft = CreateBalancedCore(syntax, value, op, left: left, right: r.Left);
(syntax, value, op, left, right) = (r.Syntax, r.Value, r.Operator, newLeft, r.Right);
}
// That should have brought the two sides within a height difference of two.
Debug.Assert(Math.Abs(left.Height - right.Height) <= 2);
// Now see if a final rotation is needed.
#region Rebalance the top of the tree if necessary
if (left.Height == right.Height + 2)
{
var leftDispatch = (RelationalDispatch)left;
if (leftDispatch.Left.Height == right.Height)
{
//
// z
// / \ y
// x D / \
// / \ --> x z
// A y /| |\
// / \ A B C D
// B C
//
var x = leftDispatch;
var A = x.Left;
var y = (RelationalDispatch)x.Right;
var B = y.Left;
var C = y.Right;
var D = right;
return y.WithLeftAndRight(x.WithLeftAndRight(A, B), new RelationalDispatch(syntax, value, op, C, D));
}
else
{
Debug.Assert(leftDispatch.Right.Height == right.Height);
//
// z
// / \ y
// y D / \
// / \ --> x z
// x C /| |\
// / \ A B C D
// A B
//
var y = leftDispatch;
var x = y.Left;
var C = y.Right;
var D = right;
return y.WithLeftAndRight(x, new RelationalDispatch(syntax, value, op, C, D));
}
}
else if (right.Height == left.Height + 2)
{
var rightDispatch = (RelationalDispatch)right;
if (rightDispatch.Right.Height == left.Height)
{
//
// x
// / \ y
// A z / \
// / \ --> x z
// y D /| |\
// / \ A B C D
// B C
//
var A = left;
var z = rightDispatch;
var y = (RelationalDispatch)z.Left;
var B = y.Left;
var C = y.Right;
var D = z.Right;
return y.WithLeftAndRight(new RelationalDispatch(syntax, value, op, A, B), z.WithLeftAndRight(C, D));
}
else
{
Debug.Assert(rightDispatch.Left.Height == left.Height);
//
// x
// / \ y
// A y / \
// / \ --> x z
// B z /| |\
// / \ A B C D
// C D
//
var A = left;
var y = rightDispatch;
var B = y.Left;
var z = y.Right;
return y.WithLeftAndRight(new RelationalDispatch(syntax, value, op, A, B), z);
}
}
#endregion Rebalance the top of the tree if necessary
// that should have been sufficient to balance the tree.
Debug.Assert(Math.Abs(left.Height - right.Height) < 2);
return new RelationalDispatch(syntax, value, op, left: left, right: right);
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class LocalRewriter
{
private abstract partial class DecisionDagRewriter
{
/// <summary>
/// A node in a tree representing the form of a generated decision tree for classifying an input value.
/// </summary>
private abstract class ValueDispatchNode
{
protected virtual int Height => 1;
#if DEBUG
protected virtual int Weight => 1;
#endif
public readonly SyntaxNode Syntax;
public ValueDispatchNode(SyntaxNode syntax) => Syntax = syntax;
/// <summary>
/// A node representing the dispatch by value (equality). This corresponds to a classical C switch
/// statement, except that it also handles values of type float, double, decimal, and string.
/// </summary>
internal sealed class SwitchDispatch : ValueDispatchNode
{
public readonly ImmutableArray<(ConstantValue value, LabelSymbol label)> Cases;
public readonly LabelSymbol Otherwise;
public SwitchDispatch(SyntaxNode syntax, ImmutableArray<(ConstantValue value, LabelSymbol label)> dispatches, LabelSymbol otherwise) : base(syntax)
{
this.Cases = dispatches;
this.Otherwise = otherwise;
}
public override string ToString() => "[" + string.Join(",", Cases.Select(c => c.value)) + "]";
}
/// <summary>
/// A node representing a final destination that requires no further dispatch.
/// </summary>
internal sealed class LeafDispatchNode : ValueDispatchNode
{
public readonly LabelSymbol Label;
public LeafDispatchNode(SyntaxNode syntax, LabelSymbol Label) : base(syntax) => this.Label = Label;
public override string ToString() => "Leaf";
}
/// <summary>
/// A node representing a dispatch based on a relational test of the input value by some constant.
/// Nodes of this kind are required to be height-balanced when constructed, so that when the full
/// decision tree is produced it generates a balanced tree of comparisons. The shape of the tree
/// keeps tests for lower values on the left and tests for higher values on the right:
/// For <see cref="BinaryOperatorKind.LessThan"/> and <see cref="BinaryOperatorKind.LessThanOrEqual"/>,
/// the <see cref="WhenTrue"/> branch is <see cref="Left"/> and the <see cref="WhenFalse"/> branch
/// is <see cref="Right"/>; for <see cref="BinaryOperatorKind.GreaterThan"/> and
/// <see cref="BinaryOperatorKind.GreaterThanOrEqual"/> it is reversed.
/// See <see cref="IsReversed(BinaryOperatorKind)"/> for where that is computed.
/// </summary>
internal sealed class RelationalDispatch : ValueDispatchNode
{
private int _height;
#if DEBUG
private int _weight;
#endif
protected override int Height => _height;
#if DEBUG
protected override int Weight => _weight;
#endif
public readonly ConstantValue Value;
public readonly BinaryOperatorKind Operator;
/// <summary>The side of the test handling lower values. The true side for < and <=, the false side for > and >=.</summary>
private ValueDispatchNode Left { get; set; }
/// <summary>The side of the test handling higher values. The false side for < and <=, the true side for > and >=.</summary>
private ValueDispatchNode Right { get; set; }
private RelationalDispatch(SyntaxNode syntax, ConstantValue value, BinaryOperatorKind op, ValueDispatchNode left, ValueDispatchNode right) : base(syntax)
{
Debug.Assert(op.OperandTypes() != 0);
this.Value = value;
this.Operator = op;
WithLeftAndRight(left, right);
}
public ValueDispatchNode WhenTrue => IsReversed(Operator) ? Right : Left;
public ValueDispatchNode WhenFalse => IsReversed(Operator) ? Left : Right;
public override string ToString() => $"RelationalDispatch.{Height}({Left} {Operator.Operator()} {Value} {Right})";
/// <summary>
/// Is the operator among those for which <see cref="WhenTrue"/> is <see cref="Right"/>?
/// </summary>
private static bool IsReversed(BinaryOperatorKind op) => op.Operator() switch { BinaryOperatorKind.GreaterThan => true, BinaryOperatorKind.GreaterThanOrEqual => true, _ => false };
private RelationalDispatch WithLeftAndRight(ValueDispatchNode left, ValueDispatchNode right)
{
// Note that this is a destructive implementation to reduce GC garbage.
// That requires clients to stop using the input node once this has been called.
int l = left.Height;
int r = right.Height;
Debug.Assert(Math.Abs(l - r) <= 1);
this.Left = left;
this.Right = right;
_height = Math.Max(l, r) + 1;
#if DEBUG
_weight = left.Weight + right.Weight + 1;
// Assert that the node is approximately balanced
Debug.Assert(_height < 2 * Math.Log(_weight));
#endif
return this;
}
public RelationalDispatch WithTrueAndFalseChildren(ValueDispatchNode whenTrue, ValueDispatchNode whenFalse)
{
if (whenTrue == this.WhenTrue && whenFalse == this.WhenFalse)
return this;
Debug.Assert(whenTrue.Height == this.WhenTrue.Height);
Debug.Assert(whenFalse.Height == this.WhenFalse.Height);
var (left, right) = IsReversed(Operator) ? (whenFalse, whenTrue) : (whenTrue, whenFalse);
return WithLeftAndRight(left, right);
}
public static ValueDispatchNode CreateBalanced(SyntaxNode syntax, ConstantValue value, BinaryOperatorKind op, ValueDispatchNode whenTrue, ValueDispatchNode whenFalse)
{
// Keep the lower numbers on the left and the higher numbers on the right.
var (left, right) = IsReversed(op) ? (whenFalse, whenTrue) : (whenTrue, whenFalse);
return CreateBalancedCore(syntax, value, op, left: left, right: right);
}
private static ValueDispatchNode CreateBalancedCore(SyntaxNode syntax, ConstantValue value, BinaryOperatorKind op, ValueDispatchNode left, ValueDispatchNode right)
{
Debug.Assert(op.OperandTypes() != 0);
// Build a height-balanced tree node that is semantically equivalent to a node with the given parameters.
// See http://www.cs.ecu.edu/karl/3300/spr16/Notes/DataStructure/Tree/balance.html
// First, build an approximately balanced left and right bottom-up.
if (left.Height > (right.Height + 1))
{
var l = (RelationalDispatch)left;
var newRight = CreateBalancedCore(syntax, value, op, left: l.Right, right: right);
(syntax, value, op, left, right) = (l.Syntax, l.Value, l.Operator, l.Left, newRight);
}
else if (right.Height > (left.Height + 1))
{
var r = (RelationalDispatch)right;
var newLeft = CreateBalancedCore(syntax, value, op, left: left, right: r.Left);
(syntax, value, op, left, right) = (r.Syntax, r.Value, r.Operator, newLeft, r.Right);
}
// That should have brought the two sides within a height difference of two.
Debug.Assert(Math.Abs(left.Height - right.Height) <= 2);
// Now see if a final rotation is needed.
#region Rebalance the top of the tree if necessary
if (left.Height == right.Height + 2)
{
var leftDispatch = (RelationalDispatch)left;
if (leftDispatch.Left.Height == right.Height)
{
//
// z
// / \ y
// x D / \
// / \ --> x z
// A y /| |\
// / \ A B C D
// B C
//
var x = leftDispatch;
var A = x.Left;
var y = (RelationalDispatch)x.Right;
var B = y.Left;
var C = y.Right;
var D = right;
return y.WithLeftAndRight(x.WithLeftAndRight(A, B), new RelationalDispatch(syntax, value, op, C, D));
}
else
{
Debug.Assert(leftDispatch.Right.Height == right.Height);
//
// z
// / \ y
// y D / \
// / \ --> x z
// x C /| |\
// / \ A B C D
// A B
//
var y = leftDispatch;
var x = y.Left;
var C = y.Right;
var D = right;
return y.WithLeftAndRight(x, new RelationalDispatch(syntax, value, op, C, D));
}
}
else if (right.Height == left.Height + 2)
{
var rightDispatch = (RelationalDispatch)right;
if (rightDispatch.Right.Height == left.Height)
{
//
// x
// / \ y
// A z / \
// / \ --> x z
// y D /| |\
// / \ A B C D
// B C
//
var A = left;
var z = rightDispatch;
var y = (RelationalDispatch)z.Left;
var B = y.Left;
var C = y.Right;
var D = z.Right;
return y.WithLeftAndRight(new RelationalDispatch(syntax, value, op, A, B), z.WithLeftAndRight(C, D));
}
else
{
Debug.Assert(rightDispatch.Left.Height == left.Height);
//
// x
// / \ y
// A y / \
// / \ --> x z
// B z /| |\
// / \ A B C D
// C D
//
var A = left;
var y = rightDispatch;
var B = y.Left;
var z = y.Right;
return y.WithLeftAndRight(new RelationalDispatch(syntax, value, op, A, B), z);
}
}
#endregion Rebalance the top of the tree if necessary
// that should have been sufficient to balance the tree.
Debug.Assert(Math.Abs(left.Height - right.Height) < 2);
return new RelationalDispatch(syntax, value, op, left: left, right: right);
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ICoalesceOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ICoalesceOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_01()
{
var source = @"
class C
{
void F(int? input, int alternative, int result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_02()
{
var source = @"
class C
{
void F(int? input, long alternative, long result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_03()
{
var source = @"
class C
{
void F(int? input, long? alternative, long? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64?, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_04()
{
var source = @"
class C
{
void F(string input, object alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Object) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_05()
{
var source = @"
class C
{
void F(int? input, System.DateTime alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'int?' and 'DateTime'
// result = input ?? alternative;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "input ?? alternative").WithArguments("??", "int?", "System.DateTime").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_06()
{
var source = @"
class C
{
void F(int? input, dynamic alternative, dynamic result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_07()
{
var source = @"
class C
{
void F(dynamic alternative, dynamic result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_08()
{
var source = @"
class C
{
void F(int alternative, int result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'int'
// result = null ?? alternative;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? alternative").WithArguments("??", "<null>", "int").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsInvalid, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null')
Value:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_09()
{
var source = @"
class C
{
void F(int? alternative, int? result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_10()
{
var source = @"
class C
{
void F(int? input, byte? alternative, int? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_11()
{
var source = @"
class C
{
void F(int? input, int? alternative, int? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_12()
{
var source = @"
class C
{
void F(int? input1, int? alternative1, int? input2, int? alternative2, int? result)
/*<bind>*/{
result = (input1 ?? alternative1) ?? (input2 ?? alternative2);
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.locals {R2}
{
CaptureIds: [2]
.locals {R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Leaving: {R3}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative1')
Value:
IParameterReferenceOperation: alternative1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative1')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1 ?? alternative1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1')
Leaving: {R2}
Entering: {R4}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1 ?? alternative1')
Value:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1')
Next (Regular) Block[B10]
Leaving: {R2}
}
.locals {R4}
{
CaptureIds: [4]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input2')
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2')
Operand:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2')
Leaving: {R4}
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2')
Next (Regular) Block[B10]
Leaving: {R4}
}
Block[B9] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative2')
Value:
IParameterReferenceOperation: alternative2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative2')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B6] [B8] [B9]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = (i ... ernative2);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = (i ... ternative2)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: '(input1 ?? ... ternative2)')
Next (Regular) Block[B11]
Leaving: {R1}
}
Block[B11] - Exit
Predecessors: [B10]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_13()
{
var source = @"
class C
{
const string input = ""a"";
void F(object alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IFieldReferenceOperation: System.String C.input (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""a"") (Syntax: 'input')
Instance Receiver:
null
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_14()
{
string source = @"
class P
{
void M1(int? i, int j, int result)
/*<bind>*/{
result = i ?? j;
}/*</bind>*/
}
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i ?? j;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i ?? j')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i ?? j')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_ICoalesceOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_01()
{
var source = @"
class C
{
void F(int? input, int alternative, int result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_02()
{
var source = @"
class C
{
void F(int? input, long alternative, long result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNumeric)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_03()
{
var source = @"
class C
{
void F(int? input, long? alternative, long? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int64?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64?, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int64?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int64?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int64?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_04()
{
var source = @"
class C
{
void F(string input, object alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Object) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.String) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_05()
{
var source = @"
class C
{
void F(int? input, System.DateTime alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'int?' and 'DateTime'
// result = input ?? alternative;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "input ?? alternative").WithArguments("??", "int?", "System.DateTime").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input')
Value:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.DateTime, IsInvalid) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsInvalid) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_06()
{
var source = @"
class C
{
void F(int? input, dynamic alternative, dynamic result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Boxing)
Operand:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_07()
{
var source = @"
class C
{
void F(dynamic alternative, dynamic result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source, references: new[] { CSharpRef }, targetFramework: TargetFramework.Mscorlib40AndSystemCore);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: dynamic) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: dynamic, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: dynamic) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_08()
{
var source = @"
class C
{
void F(int alternative, int result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics(
// (6,18): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and 'int'
// result = null ?? alternative;
Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? alternative").WithArguments("??", "<null>", "int").WithLocation(6, 18)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: ?, IsInvalid) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsInvalid, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'null')
Value:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NoConversion)
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_09()
{
var source = @"
class C
{
void F(int? alternative, int? result)
/*<bind>*/{
result = null ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'null ?? alternative')
Expression:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ValueConversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: True, IsImplicit) (Syntax: 'null')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'null')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(NullLiteral)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: null, Constant: null, IsImplicit) (Syntax: 'null')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = nu ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = nu ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'null ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_10()
{
var source = @"
class C
{
void F(int? input, byte? alternative, int? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: 'alternative')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Byte?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_11()
{
var source = @"
class C
{
void F(int? input, int? alternative, int? result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single();
compilation.VerifyOperationTree(node, expectedOperationTree:
@"
ICoalesceOperation (OperationKind.Coalesce, Type: System.Int32?) (Syntax: 'input ?? alternative')
Expression:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
ValueConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
WhenNull:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
");
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_12()
{
var source = @"
class C
{
void F(int? input1, int? alternative1, int? input2, int? alternative2, int? result)
/*<bind>*/{
result = (input1 ?? alternative1) ?? (input2 ?? alternative2);
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2} {R3}
.locals {R2}
{
CaptureIds: [2]
.locals {R3}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Leaving: {R3}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1')
Value:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1')
Next (Regular) Block[B5]
Leaving: {R3}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative1')
Value:
IParameterReferenceOperation: alternative1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative1')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (0)
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1 ?? alternative1')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1')
Leaving: {R2}
Entering: {R4}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1 ?? alternative1')
Value:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1 ?? alternative1')
Next (Regular) Block[B10]
Leaving: {R2}
}
.locals {R4}
{
CaptureIds: [4]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input2')
Jump if True (Regular) to Block[B9]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2')
Operand:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2')
Leaving: {R4}
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2')
Value:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input2')
Next (Regular) Block[B10]
Leaving: {R4}
}
Block[B9] - Block
Predecessors: [B7]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative2')
Value:
IParameterReferenceOperation: alternative2 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'alternative2')
Next (Regular) Block[B10]
Block[B10] - Block
Predecessors: [B6] [B8] [B9]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = (i ... ernative2);')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32?) (Syntax: 'result = (i ... ternative2)')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: '(input1 ?? ... ternative2)')
Next (Regular) Block[B11]
Leaving: {R1}
}
Block[B11] - Exit
Predecessors: [B10]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_13()
{
var source = @"
class C
{
const string input = ""a"";
void F(object alternative, object result)
/*<bind>*/{
result = input ?? alternative;
}/*</bind>*/
}";
var compilation = CreateCompilation(source);
compilation.VerifyDiagnostics();
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IFieldReferenceOperation: System.String C.input (Static) (OperationKind.FieldReference, Type: System.String, Constant: ""a"") (Syntax: 'input')
Instance Receiver:
null
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, Constant: False, IsImplicit) (Syntax: 'input')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'input')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
(ImplicitReference)
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, Constant: ""a"", IsImplicit) (Syntax: 'input')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block [UnReachable]
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'alternative')
Value:
IParameterReferenceOperation: alternative (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'alternative')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... lternative;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'result = in ... alternative')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input ?? alternative')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void CoalesceOperation_14()
{
string source = @"
class P
{
void M1(int? i, int j, int result)
/*<bind>*/{
result = i ?? j;
}/*</bind>*/
}
";
var compilation = CreateCompilationWithMscorlib45(source);
compilation.MakeMemberMissing(SpecialMember.System_Nullable_T_GetValueOrDefault);
string expectedGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result')
Value:
IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [1]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i')
Value:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: 'i')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i ?? j;')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i ?? j')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i ?? j')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(compilation, expectedGraph, expectedDiagnostics);
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/EditorFeatures/Core/Shared/Extensions/ITextBufferExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static partial class ITextBufferExtensions
{
internal static bool GetFeatureOnOffOption(this ITextBuffer buffer, Option2<bool> option)
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option);
}
return option.DefaultValue;
}
internal static T GetFeatureOnOffOption<T>(this ITextBuffer buffer, PerLanguageOption2<T> option)
{
// Add a FailFast to help diagnose 984249. Hopefully this will let us know what the issue is.
try
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option, document.Project.Language);
}
return option.DefaultValue;
}
catch (Exception e) when (FatalError.ReportAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool? GetOptionalFeatureOnOffOption(this ITextBuffer buffer, PerLanguageOption2<bool?> option)
{
// Add a FailFast to help diagnose 984249. Hopefully this will let us know what the issue is.
try
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option, document.Project.Language);
}
return option.DefaultValue;
}
catch (Exception e) when (FatalError.ReportAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool IsInLspEditorContext(this ITextBuffer buffer)
{
if (buffer.TryGetWorkspace(out var workspace))
{
var workspaceContextService = workspace.Services.GetRequiredService<IWorkspaceContextService>();
return workspaceContextService.IsInLspEditorContext();
}
return false;
}
internal static bool TryGetWorkspace(this ITextBuffer buffer, [NotNullWhen(true)] out Workspace? workspace)
=> Workspace.TryGetWorkspace(buffer.AsTextContainer(), out workspace);
/// <summary>
/// Checks if a buffer supports refactorings.
/// </summary>
internal static bool SupportsRefactorings(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsRefactorings(buffer);
/// <summary>
/// Checks if a buffer supports rename.
/// </summary>
internal static bool SupportsRename(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsRename(buffer);
/// <summary>
/// Checks if a buffer supports code fixes.
/// </summary>
internal static bool SupportsCodeFixes(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsCodeFixes(buffer);
/// <summary>
/// Checks if a buffer supports navigation.
/// </summary>
internal static bool SupportsNavigationToAnyPosition(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsNavigationToAnyPosition(buffer);
private static bool TryGetSupportsFeatureService(ITextBuffer buffer, [NotNullWhen(true)] out ITextBufferSupportsFeatureService? service)
{
service = null;
if (buffer.TryGetWorkspace(out var workspace))
{
service = workspace.Services.GetService<ITextBufferSupportsFeatureService>();
}
return service != null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static partial class ITextBufferExtensions
{
internal static bool GetFeatureOnOffOption(this ITextBuffer buffer, Option2<bool> option)
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option);
}
return option.DefaultValue;
}
internal static T GetFeatureOnOffOption<T>(this ITextBuffer buffer, PerLanguageOption2<T> option)
{
// Add a FailFast to help diagnose 984249. Hopefully this will let us know what the issue is.
try
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option, document.Project.Language);
}
return option.DefaultValue;
}
catch (Exception e) when (FatalError.ReportAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool? GetOptionalFeatureOnOffOption(this ITextBuffer buffer, PerLanguageOption2<bool?> option)
{
// Add a FailFast to help diagnose 984249. Hopefully this will let us know what the issue is.
try
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option, document.Project.Language);
}
return option.DefaultValue;
}
catch (Exception e) when (FatalError.ReportAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool IsInLspEditorContext(this ITextBuffer buffer)
{
if (buffer.TryGetWorkspace(out var workspace))
{
var workspaceContextService = workspace.Services.GetRequiredService<IWorkspaceContextService>();
return workspaceContextService.IsInLspEditorContext();
}
return false;
}
internal static bool TryGetWorkspace(this ITextBuffer buffer, [NotNullWhen(true)] out Workspace? workspace)
=> Workspace.TryGetWorkspace(buffer.AsTextContainer(), out workspace);
/// <summary>
/// Checks if a buffer supports refactorings.
/// </summary>
internal static bool SupportsRefactorings(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsRefactorings(buffer);
/// <summary>
/// Checks if a buffer supports rename.
/// </summary>
internal static bool SupportsRename(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsRename(buffer);
/// <summary>
/// Checks if a buffer supports code fixes.
/// </summary>
internal static bool SupportsCodeFixes(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsCodeFixes(buffer);
/// <summary>
/// Checks if a buffer supports navigation.
/// </summary>
internal static bool SupportsNavigationToAnyPosition(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsNavigationToAnyPosition(buffer);
private static bool TryGetSupportsFeatureService(ITextBuffer buffer, [NotNullWhen(true)] out ITextBufferSupportsFeatureService? service)
{
service = null;
if (buffer.TryGetWorkspace(out var workspace))
{
service = workspace.Services.GetService<ITextBufferSupportsFeatureService>();
}
return service != null;
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicF1Help.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicF1Help : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicF1Help(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicF1Help))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
private void F1Help()
{
var text = @"
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program$$
Sub Main(args As String())
Dim query = From arg In args
Select args.Any(Function(a) a.Length > 5)
Dim x = 0
x += 1
End Sub
Public Function F() As Object
Return Nothing
End Function
End Module";
SetUpEditor(text);
Verify("Linq", "System.Linq");
Verify("String", "vb.String");
Verify("Any", "System.Linq.Enumerable.Any");
Verify("From", "vb.QueryFrom");
Verify("+=", "vb.+=");
Verify("Nothing", "vb.Nothing");
}
private void Verify(string word, string expectedKeyword)
{
VisualStudio.Editor.PlaceCaret(word, charsOffset: -1);
Assert.Contains(expectedKeyword, VisualStudio.Editor.GetF1Keyword());
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.IntegrationTest.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic
{
[Collection(nameof(SharedIntegrationHostFixture))]
public class BasicF1Help : AbstractEditorTest
{
protected override string LanguageName => LanguageNames.VisualBasic;
public BasicF1Help(VisualStudioInstanceFactory instanceFactory)
: base(instanceFactory, nameof(BasicF1Help))
{
}
[WpfFact, Trait(Traits.Feature, Traits.Features.F1Help)]
private void F1Help()
{
var text = @"
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program$$
Sub Main(args As String())
Dim query = From arg In args
Select args.Any(Function(a) a.Length > 5)
Dim x = 0
x += 1
End Sub
Public Function F() As Object
Return Nothing
End Function
End Module";
SetUpEditor(text);
Verify("Linq", "System.Linq");
Verify("String", "vb.String");
Verify("Any", "System.Linq.Enumerable.Any");
Verify("From", "vb.QueryFrom");
Verify("+=", "vb.+=");
Verify("Nothing", "vb.Nothing");
}
private void Verify(string word, string expectedKeyword)
{
VisualStudio.Editor.PlaceCaret(word, charsOffset: -1);
Assert.Contains(expectedKeyword, VisualStudio.Editor.GetF1Keyword());
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueClosureTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Linq;
using System.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
{
public class EditAndContinueClosureTests : EditAndContinueTestBase
{
[Fact]
public void MethodToMethodWithClosure()
{
var source0 =
@"delegate object D();
class C
{
static object F(object o)
{
return o;
}
}";
var source1 =
@"delegate object D();
class C
{
static object F(object o)
{
return ((D)(() => o))();
}
}";
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.Update, compilation0.GetMember<MethodSymbol>("C.F"), compilation1.GetMember<MethodSymbol>("C.F"))));
using (var md1 = diff1.GetMetadata())
{
var reader1 = md1.Reader;
// Field 'o'
// Methods: 'F', '.ctor', '<F>b__1'
// Type: display class
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default));
}
}
[Fact]
public void MethodWithStaticLambda1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
Func<int> x = <N:0>() => 1</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
Func<int> x = <N:0>() => 2</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithSwitchExpression()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(object o)
{
<N:0>return o switch
{
int i => new Func<int>(<N:1>() => i + 1</N:1>)(),
_ => 0
}</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(object o)
{
<N:0>return o switch
{
int i => new Func<int>(<N:1>() => i + 2</N:1>)(),
_ => 0
}</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {<i>5__2, <F>b__0}",
"C: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var x = Visualize(generation0.OriginalMetadata, md1);
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithNestedSwitchExpression()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(object o)
<N:0>{
<N:1>return o switch
{
int i => new Func<int>(<N:2>() => i + (int)o + i switch
{
1 => 1,
_ => new Func<int>(<N:3>() => (int)o + 1</N:3>)()
}</N:2>)(),
_ => 0
}</N:1>;
}</N:0>
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(object o)
<N:0>{
<N:1>return o switch
{
int i => new Func<int>(<N:2>() => i + (int)o + i switch
{
1 => 1,
_ => new Func<int>(<N:3>() => (int)o + 2</N:3>)()
}</N:2>)(),
_ => 0
}</N:1>;
}</N:0>
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_1: {<i>5__2, CS$<>8__locals2, <F>b__0}",
"C.<>c__DisplayClass0_0: {o, <>9__1, <F>b__1}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunction1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 1;</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 2;</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunction_ChangeStatic()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 1;</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>static int x() => 1;</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
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.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var localFunction0 = testData0.GetMethodData("C.<F>g__x|0_0").Method;
Assert.True(((Symbol)localFunction0).IsStatic);
var localFunction1 = diff1.TestData.GetMethodData("C.<F>g__x|0_0").Method;
Assert.True(((Symbol)localFunction1).IsStatic);
}
[Fact]
public void MethodWithStaticLambdaGeneric1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
Func<T> x = <N:0>() => default(T)</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
Func<T> x = <N:0>() => default(T)</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__0}",
"C.<>c__0<T>: {<>9__0_0, <F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunctionGeneric1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
<N:0>T x() => default(T);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
<N:0>T x() => default(T);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithThisOnlyClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
Func<int> x = <N:0>() => F(1)</N:0>;
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
Func<int> x = <N:0>() => F(2)</N:0>;
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithThisOnlyLocalFunctionClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
<N:0>int x() => F(1);</N:0>
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
<N:0>int x() => F(2);</N:0>
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
Func<int> x = <N:1>() => F(a + 1)</N:1>;
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
Func<int> x = <N:1>() => F(a + 2)</N:1>;
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {<>4__this, a, <F>b__0}",
"C: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithNullable_AddingNullCheck()
{
var source0 = MarkedSource(@"
using System;
#nullable enable
class C
{
static T id<T>(T t) => t;
static T G<T>(Func<T> f) => f();
public void F(string? x)
<N:0>{</N:0>
var <N:1>y1</N:1> = new { A = id(x) };
var <N:2>y2</N:2> = G(<N:3>() => new { B = id(x) }</N:3>);
var <N:4>z</N:4> = G(<N:5>() => y1.A + y2.B</N:5>);
}
}", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
var source1 = MarkedSource(@"
using System;
#nullable enable
class C
{
static T id<T>(T t) => t;
static T G<T>(Func<T> f) => f();
public void F(string? x)
<N:0>{</N:0>
if (x is null) throw new Exception();
var <N:1>y1</N:1> = new { A = id(x) };
var <N:2>y2</N:2> = G(<N:3>() => new { B = id(x) }</N:3>);
var <N:4>z</N:4> = G(<N:5>() => y1.A + y2.B</N:5>);
}
}", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
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.VerifySynthesizedMembers(
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"Microsoft: {CodeAnalysis}",
"System.Runtime: {CompilerServices, CompilerServices}",
"<global namespace>: {Microsoft, System, System}",
"C: {<>c__DisplayClass2_0}",
"System: {Runtime, Runtime}",
"C.<>c__DisplayClass2_0: {x, y1, y2, <F>b__0, <F>b__1}",
"<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.<>c__DisplayClass2_0.<F>b__1()", @"
{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""<anonymous type: string A> C.<>c__DisplayClass2_0.y1""
IL_0006: callvirt ""string <>f__AnonymousType0<string>.A.get""
IL_000b: ldarg.0
IL_000c: ldfld ""<anonymous type: string B> C.<>c__DisplayClass2_0.y2""
IL_0011: callvirt ""string <>f__AnonymousType1<string>.B.get""
IL_0016: call ""string string.Concat(string, string)""
IL_001b: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass2_0.<F>b__0()", @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""string C.<>c__DisplayClass2_0.x""
IL_0006: call ""string C.id<string>(string)""
IL_000b: newobj ""<>f__AnonymousType1<string>..ctor(string)""
IL_0010: ret
}");
}
[Fact]
public void MethodWithLocalFunctionClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
<N:1>int x() => F(a + 1);</N:1>
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
<N:1>int x() => F(a + 2);</N:1>
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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.VerifySynthesizedMembers(
"C: {<F>g__x|0_0, <>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {<>4__this, a}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ConstructorWithClosure1()
{
var source0 = MarkedSource(@"
using System;
class D { public D(Func<int> f) { } }
class C : D
{
<N:0>public C(int a, int b)</N:0>
: base(<N:8>() => a</N:8>)
<N:1>{</N:1>
int c = 0;
Func<int> f1 = <N:2>() => a + 1</N:2>;
Func<int> f2 = <N:3>() => b + 2</N:3>;
Func<int> f3 = <N:4>() => c + 3</N:4>;
Func<int> f4 = <N:5>() => a + b + c</N:5>;
Func<int> f5 = <N:6>() => a + c</N:6>;
Func<int> f6 = <N:7>() => b + c</N:7>;
}
}");
var source1 = MarkedSource(@"
using System;
class D { public D(Func<int> f) { } }
class C : D
{
<N:0>public C(int a, int b)</N:0>
: base(<N:8>() => a * 10</N:8>)
<N:1>{</N:1>
int c = 0;
Func<int> f1 = <N:2>() => a * 10 + 1</N:2>;
Func<int> f2 = <N:3>() => b * 10 + 2</N:3>;
Func<int> f3 = <N:4>() => c * 10 + 3</N:4>;
Func<int> f4 = <N:5>() => a * 10 + b + c</N:5>;
Func<int> f5 = <N:6>() => a * 10 + c</N:6>;
Func<int> f6 = <N:7>() => b * 10 + c</N:7>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var ctor1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_0: {a, b, <.ctor>b__0, <.ctor>b__1, <.ctor>b__2}",
"C.<>c__DisplayClass0_1: {c, CS$<>8__locals1, <.ctor>b__3, <.ctor>b__4, <.ctor>b__5, <.ctor>b__6}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, 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(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void PartialClass()
{
var source0 = MarkedSource(@"
using System;
partial class C
{
Func<int> m1 = <N:0>() => 1</N:0>;
}
partial class C
{
Func<int> m2 = <N:1>() => 1</N:1>;
}
");
var source1 = MarkedSource(@"
using System;
partial class C
{
Func<int> m1 = <N:0>() => 10</N:0>;
}
partial class C
{
Func<int> m2 = <N:1>() => 10</N:1>;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var ctor1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <.ctor>b__2_0, <.ctor>b__2_1}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void JoinAndGroupByClauses()
{
var source0 = MarkedSource(@"
using System.Linq;
class C
{
void F()
{
var result = <N:0>from a in new[] { 1, 2, 3 }</N:0>
<N:1>join b in new[] { 5 } on a + 1 equals b - 1</N:1>
<N:2>group</N:2> new { a, b = a + 5 } by new { c = a + 4 } into d
<N:3>select d.Key</N:3>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
class C
{
void F()
{
var result = <N:0>from a in new[] { 10, 20, 30 }</N:0>
<N:1>join b in new[] { 50 } on a + 10 equals b - 10</N:1>
<N:2>group</N:2> new { a, b = a + 50 } by new { c = a + 40 } into d
<N:3>select d.Key</N:3>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <>9__0_4, <>9__0_5, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3, <F>b__0_4, <F>b__0_5}",
"<>f__AnonymousType1<<c>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(16, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(17, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(20, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(21, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(10, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.Param, EditAndContinueOperation.Default),
Row(12, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_FromClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var <N:10>result = <N:0>from a in new[] { 1 }</N:0>
<N:1>from b in <N:9>new[] { 1 }</N:9></N:1>
<N:2>where <N:7>Z(<N:5>() => a</N:5>) > 0</N:7></N:2>
<N:3>where <N:8>Z(<N:6>() => b</N:6>) > 0</N:8></N:3>
<N:4>select a</N:4></N:10>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var <N:10>result = <N:0>from a in new[] { 1 }</N:0>
<N:1>from b in <N:9>new[] { 2 }</N:9></N:1>
<N:2>where <N:7>Z(<N:5>() => a</N:5>) > 1</N:7></N:2>
<N:3>where <N:8>Z(<N:6>() => b</N:6>) > 2</N:8></N:3>
<N:4>select a</N:4></N:10>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_1: {<>h__TransparentIdentifier0, <F>b__6}",
"C.<>c__DisplayClass1_0: {<>h__TransparentIdentifier0, <F>b__5}",
"C.<>c: {<>9__1_0, <>9__1_1, <>9__1_4, <F>b__1_0, <F>b__1_1, <F>b__1_4}",
"C: {<F>b__1_2, <F>b__1_3, <>c__DisplayClass1_0, <>c__DisplayClass1_1, <>c}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(20, TableIndex.MethodDef, 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(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(10, TableIndex.Param, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_LetClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = <N:0>from a in new[] { 1 }</N:0>
<N:1>let b = <N:2>Z(<N:3>() => a</N:3>)</N:2></N:1>
<N:4>select <N:5>a + b</N:5></N:4>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = <N:0>from a in new[] { 1 }</N:0>
<N:1>let b = <N:2>Z(<N:3>() => a</N:3>) + 1</N:2></N:1>
<N:4>select <N:5>a + b</N:5></N:4>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c: {<>9__1_1, <F>b__1_1}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}",
"C.<>c__DisplayClass1_0: {a, <F>b__2}",
"C: {<F>b__1_0, <>c__DisplayClass1_0, <>c}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_JoinClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>Z(<N:4>() => <N:5>a + 1</N:5></N:4>)</N:3>
equals
<N:6>Z(<N:7>() => <N:8>b - 1</N:8></N:7>)</N:6></N:2>
<N:9>select <N:10>Z(<N:11>() => <N:12>a + b</N:12></N:11>)</N:10></N:9>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>Z(<N:4>() => <N:5>a + 1</N:5></N:4>)</N:3>
equals
<N:6>Z(<N:7>() => <N:8>b - 1</N:8></N:7>)</N:6></N:2>
<N:9>select <N:10>Z(<N:11>() => <N:12>a - b</N:12></N:11>)</N:10></N:9>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_1: {b, <F>b__4}",
"C.<>c__DisplayClass1_2: {a, b, <F>b__5}",
"C.<>c__DisplayClass1_0: {a, <F>b__3}",
"C: {<F>b__1_0, <F>b__1_1, <F>b__1_2, <>c__DisplayClass1_0, <>c__DisplayClass1_1, <>c__DisplayClass1_2}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_JoinIntoClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>a + 1</N:3> equals <N:4>b - 1</N:4>
into g</N:2>
<N:5>select <N:6>Z(<N:7>() => <N:8>g.First()</N:8></N:7>)</N:6></N:5>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>a + 1</N:3> equals <N:4>b - 1</N:4>
into g</N:2>
<N:5>select <N:6>Z(<N:7>() => <N:8>g.Last()</N:8></N:7>)</N:6></N:5>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__1_2, <>c__DisplayClass1_0, <>c}",
"C.<>c: {<>9__1_0, <>9__1_1, <F>b__1_0, <F>b__1_1}",
"C.<>c__DisplayClass1_0: {g, <F>b__3}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_QueryContinuation()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>group a by <N:3>a + 1</N:3></N:2>
<N:4>into g
<N:5>select <N:6>Z(<N:7>() => <N:8>g.First()</N:8></N:7>)</N:6></N:5></N:4>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>group a by <N:3>a + 1</N:3></N:2>
<N:4>into g
<N:5>select <N:6>Z(<N:7>() => <N:8>g.Last()</N:8></N:7>)</N:6></N:5></N:4>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__1_1, <>c__DisplayClass1_0, <>c}",
"C.<>c: {<>9__1_0, <F>b__1_0}",
"C.<>c__DisplayClass1_0: {g, <F>b__2}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void Lambdas_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(null);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 1</N:0>);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 2</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);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0#1, <F>b__0#1}");
// added:
diff1.VerifyIL("C.<>c.<F>b__0#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
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#1, <F>b__0#1}");
// updated:
diff2.VerifyIL("C.<>c.<F>b__0#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LocalFunctions_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(null);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f(int a) => a + 1;</N:0>
return G(f);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f(int a) => a + 2;</N:0>
return G(f);
}
}");
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);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// added:
diff1.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// updated:
diff2.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LocalFunctions_UpdateAfterAdd_NoDelegatePassing()
{
var source0 = MarkedSource(@"
using System;
class C
{
static object F()
{
return 0;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static object F()
{
<N:0>int f(int a) => a + 1;</N:0>
return 1;
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static object F()
{
<N:0>int f(int a) => a + 2;</N:0>
return 2;
}
}");
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);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// added:
diff1.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// updated:
diff2.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LambdasMultipleGenerations1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 1</N:0>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 2</N:0>) + G(<N:1>b => b + 20</N:1>);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 3</N:0>) + G(<N:1>b => b + 30</N:1>) + G(<N:2>c => c + 0x300</N:2>);
}
}");
var source3 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 4</N:0>) + G(<N:1>b => b + 40</N:1>) + G(<N:2>c => c + 0x400</N:2>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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 f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var f3 = compilation3.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();
var reader1 = md1.Reader;
// new lambda "<F>b__1_1#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <F>b__1_0, <F>b__1_1#1}");
// updated:
diff1.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
// added:
diff1.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 20
IL_0003: add
IL_0004: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// new lambda "<F>b__1_2#2" has been added:
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <>9__1_2#2, <F>b__1_0, <F>b__1_1#1, <F>b__1_2#2}");
// updated:
diff2.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.3
IL_0002: add
IL_0003: ret
}
");
// updated:
diff2.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 30
IL_0003: add
IL_0004: ret
}
");
// added:
diff2.VerifyIL("C.<>c.<F>b__1_2#2", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4 0x300
IL_0006: add
IL_0007: ret
}
");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <>9__1_2#2, <F>b__1_0, <F>b__1_1#1, <F>b__1_2#2}");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.4
IL_0002: add
IL_0003: ret
}
");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 40
IL_0003: add
IL_0004: ret
}
");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_2#2", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4 0x400
IL_0006: add
IL_0007: ret
}
");
}
[Fact]
public void LocalFunctionsMultipleGenerations1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 1;</N:0>
return G(f1);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 2;</N:0>
<N:1>int f2(int b) => b + 20;</N:1>
return G(f1) + G(f2);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 3;</N:0>
<N:1>int f2(int b) => b + 30;</N:1>
<N:2>int f3(int c) => c + 0x300;</N:2>
return G(f1) + G(f2) + G(f3);
}
}");
var source3 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 4;</N:0>
<N:1>int f2(int b) => b + 40;</N:1>
<N:2>int f3(int c) => c + 0x400;</N:2>
return G(f1) + G(f2) + G(f3);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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 f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var f3 = compilation3.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();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1}");
// updated:
diff1.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
// added:
diff1.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 20
IL_0003: add
IL_0004: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1, <F>g__f3|1_2#2}");
// updated:
diff2.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.3
IL_0002: add
IL_0003: ret
}
");
// updated:
diff2.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 30
IL_0003: add
IL_0004: ret
}
");
// added:
diff2.VerifyIL("C.<F>g__f3|1_2#2(int)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x300
IL_0006: add
IL_0007: ret
}
");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1, <F>g__f3|1_2#2}");
// updated:
diff3.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.4
IL_0002: add
IL_0003: ret
}
");
// updated:
diff3.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 40
IL_0003: add
IL_0004: ret
}
");
// updated:
diff3.VerifyIL("C.<F>g__f3|1_2#2(int)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x400
IL_0006: add
IL_0007: ret
}
");
}
[Fact, WorkItem(2284, "https://github.com/dotnet/roslyn/issues/2284")]
public void LambdasMultipleGenerations2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
// var z = from title in _titles
// where title > 0
// select title;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
// Console.WriteLine(2);
}</N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
var <N:3>z = from title in _titles
<N:2>where title > 0</N:2>
select title</N:3>;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
// Console.WriteLine(2);
}</N:1></N:0>;
}
}");
var source2 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
var <N:3>z = from title in _titles
<N:2>where title > 0</N:2>
select title</N:3>;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
Console.WriteLine(2);
}</N:1></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);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__2_0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <F>b__2_0#1, <F>b__2_0}");
// lambda body unchanged:
diff1.VerifyIL("C.<>c.<F>b__2_0", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// no new members:
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <F>b__2_0#1, <F>b__2_0}");
// lambda body updated:
diff2.VerifyIL("C.<>c.<F>b__2_0", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ldc.i4.2
IL_0009: call ""void System.Console.WriteLine(int)""
IL_000e: nop
IL_000f: ret
}");
}
[Fact]
public void UniqueSynthesizedNames1()
{
var source0 = @"
using System;
public class C
{
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source1 = @"
using System;
public class C
{
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F(byte x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f_int1 = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c__DisplayClass0_0", "<>c");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor", "<F>b__1", "<F>b__2", ".cctor", ".ctor", "<F>b__0_0");
CheckNames(reader0, reader0.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0_0");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>c__DisplayClass0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetMethodDefNames(), ".ctor", "F", ".ctor", "<F>b__1#1", "<F>b__2#1", "<F>b__0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetFieldDefNames(), "<>4__this", "a", "<>9__0#1_0#1");
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0#1_0#1, <>c}",
"C.<>c__DisplayClass0#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C.<>c: {<>9__0#1_0#1, <F>b__0#1_0#1}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>c__DisplayClass1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetMethodDefNames(), ".ctor", "F", ".ctor", "<F>b__1#2", "<F>b__2#2", "<F>b__1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetFieldDefNames(), "<>4__this", "a", "<>9__1#2_0#2");
}
[Fact]
public void UniqueSynthesizedNames1_Generic()
{
var source0 = @"
using System;
public class C
{
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source1 = @"
using System;
public class C
{
public int F<T>(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public int F<T>(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>(byte x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f_int1 = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F<T>(int)");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F<T>(byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c__DisplayClass0_0`1", "<>c__0`1");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor", "<F>b__1", "<F>b__2", ".cctor", ".ctor", "<F>b__0_0");
CheckNames(reader0, reader0.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0_0");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>c__DisplayClass0#1_0#1`1", "<>c__0#1`1");
CheckNames(new[] { reader0, reader1 }, reader1.GetMethodDefNames(), "F", ".ctor", "<F>b__1#1", "<F>b__2#1", ".cctor", ".ctor", "<F>b__0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0#1_0#1");
diff1.VerifySynthesizedMembers(
"C.<>c__0#1<T>: {<>9__0#1_0#1, <F>b__0#1_0#1}",
"C: {<>c__DisplayClass0#1_0#1, <>c__0#1}",
"C.<>c__DisplayClass0#1_0#1<T>: {<>4__this, a, <F>b__1#1, <F>b__2#1}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>c__DisplayClass1#2_0#2`1", "<>c__1#2`1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetMethodDefNames(), "F", ".ctor", "<F>b__1#2", "<F>b__2#2", ".cctor", ".ctor", "<F>b__1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__1#2_0#2");
}
[Fact]
public void UniqueSynthesizedNames2()
{
var source0 = @"
using System;
public class C
{
public static void Main()
{
}
}";
var source1 = @"
using System;
public class C
{
public static void Main()
{
new C().F();
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public static void Main()
{
new C().F(1);
new C().F();
}
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source3 = @"
using System;
public class C
{
public static void Main()
{
}
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var main0 = compilation0.GetMember<MethodSymbol>("C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("C.Main");
var main2 = compilation2.GetMember<MethodSymbol>("C.Main");
var main3 = compilation3.GetMember<MethodSymbol>("C.Main");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f_int2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)");
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.Insert, null, f1),
SemanticEdit.Create(SemanticEditKind.Update, main0, main1, preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>c: {<>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C: {<>c__DisplayClass1#1_0#1, <>c}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int2),
SemanticEdit.Create(SemanticEditKind.Update, main1, main2, preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C.<>c__DisplayClass1#2_0#2: {<>4__this, a, <F>b__1#2, <F>b__2#2}",
"C: {<>c__DisplayClass1#2_0#2, <>c, <>c__DisplayClass1#1_0#1}",
"C.<>c: {<>9__1#2_0#2, <F>b__1#2_0#2, <>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main2, main3, preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C.<>c: {<>9__1#2_0#2, <F>b__1#2_0#2, <>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#2_0#2: {<>4__this, a, <F>b__1#2, <F>b__2#2}",
"C: {<>c__DisplayClass1#2_0#2, <>c, <>c__DisplayClass1#1_0#1}");
}
[Fact]
public void NestedLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + G(<N:1>b => 1</N:1>)</N:0>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + G(<N:1>b => 2</N:1>)</N:0>);
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// 3 method updates:
// Note that even if the change is in the inner lambda such a change will usually impact sequence point
// spans in outer lambda and the method body. So although the IL doesn't change we usually need to update the outer methods.
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void LambdasInInitializers1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => a + 1</N:0>);
public C() : this(G(<N:1>a => a + 2</N:1>))
{
G(<N:2>a => a + 3</N:2>);
}
public C(int x)
{
G(<N:3>a => a + 4</N:3>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => a - 1</N:0>);
public C() : this(G(<N:1>a => a - 2</N:1>))
{
G(<N:2>a => a - 3</N:2>);
}
public C(int x)
{
G(<N:3>a => a - 4</N:3>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor00 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor10 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var ctor01 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor11 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor00, ctor01, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, ctor10, ctor11, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <>9__3_0, <>9__3_1, <.ctor>b__2_0, <.ctor>b__2_1, <.ctor>b__3_0, <.ctor>b__3_1}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.3
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.4
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: ret
}");
}
[Fact]
public void LambdasInInitializers2()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => { int <N:4>v1 = 1</N:4>; return 1; }</N:0>);
public C() : this(G(<N:1>a => { int <N:5>v2 = 1</N:5>; return 2; }</N:1>))
{
G(<N:2>a => { int <N:6>v3 = 1</N:6>; return 3; }</N:2>);
}
public C(int x)
{
G(<N:3>a => { int <N:7>v4 = 1</N:7>; return 4; }</N:3>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => { int <N:4>v1 = 10</N:4>; return 1; }</N:0>);
public C() : this(G(<N:1>a => { int <N:5>v2 = 10</N:5>; return 2; }</N:1>))
{
G(<N:2>a => { int <N:6>v3 = 10</N:6>; return 3; }</N:2>);
}
public C(int x)
{
G(<N:3>a => { int <N:7>v4 = 10</N:7>; return 4; }</N:3>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor00 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor10 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var ctor01 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor11 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor00, ctor01, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, ctor10, ctor11, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <>9__3_0, <>9__3_1, <.ctor>b__2_0, <.ctor>b__2_1, <.ctor>b__3_0, <.ctor>b__3_1}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_0", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v2
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.2
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_1", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v3
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_0", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v4
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.4
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_1", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v1
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.1
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
}
[Fact]
public void UpdateParameterlessConstructorInPresenceOfFieldInitializersWithLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
int B = F(b => b + 1); // new field
public C() // new ctor
{
F(c => c + 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 b1 = compilation1.GetMember<FieldSymbol>("C.B");
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, b1),
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <>9__2_2#1, <.ctor>b__2_0#1, <.ctor>b__2_0, <.ctor>b__2_2#1}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 130 (0x82)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldsfld ""System.Func<int, int> C.<>c.<>9__2_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.<.ctor>b__2_0(int)""
IL_0015: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_001a: dup
IL_001b: stsfld ""System.Func<int, int> C.<>c.<>9__2_0""
IL_0020: call ""int C.F(System.Func<int, int>)""
IL_0025: stfld ""int C.A""
IL_002a: ldarg.0
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__2_2#1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<.ctor>b__2_2#1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__2_2#1""
IL_004a: call ""int C.F(System.Func<int, int>)""
IL_004f: stfld ""int C.B""
IL_0054: ldarg.0
IL_0055: call ""object..ctor()""
IL_005a: nop
IL_005b: nop
IL_005c: ldsfld ""System.Func<int, int> C.<>c.<>9__2_0#1""
IL_0061: dup
IL_0062: brtrue.s IL_007b
IL_0064: pop
IL_0065: ldsfld ""C.<>c C.<>c.<>9""
IL_006a: ldftn ""int C.<>c.<.ctor>b__2_0#1(int)""
IL_0070: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0075: dup
IL_0076: stsfld ""System.Func<int, int> C.<>c.<>9__2_0#1""
IL_007b: call ""int C.F(System.Func<int, int>)""
IL_0080: pop
IL_0081: ret
}
");
}
[Fact(Skip = "2504"), WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void InsertConstructorInPresenceOfFieldInitializersWithLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
int B = F(b => b + 1); // new field
public C(int x) // new ctor
{
F(c => c + 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 b1 = compilation1.GetMember<FieldSymbol>("C.B");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, b1),
SemanticEdit.Create(SemanticEditKind.Insert, null, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<> c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <>9__2_2#1, <.ctor>b__2_0#1, <.ctor>b__2_0, <.ctor>b__2_2#1}");
}
[Fact]
public void Queries_Select_Reduced1()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a</N:2></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a + 1</N:2></N:0>;
}
int[] array = null;
}
");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda for Select(a => a + 1)
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <F>b__0_0, <F>b__0_1#1}");
diff1.VerifyIL("C.<>c.<F>b__0_1#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: stloc.0
IL_002c: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<F>b__0_1#1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_004a: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_004f: stloc.0
IL_0050: ret
}
");
}
[Fact]
public void Queries_Select_Reduced2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a + 1</N:2></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a</N:2></N:0>;
}
int[] array = null;
}
");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// lambda for Select(a => a + 1) is gone
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<F>b__0_1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_004a: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_004f: stloc.0
IL_0050: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: stloc.0
IL_002c: ret
}
");
}
[Fact]
public void Queries_GroupBy_Reduced1()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a by a</N:1></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a + 1 by a</N:1></N:0>;
}
int[] array = null;
}
");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda for GroupBy(..., a => a + 1)
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <F>b__0_0, <F>b__0_1#1}");
diff1.VerifyIL("C.<>c.<F>b__0_1#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_002b: stloc.0
IL_002c: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""int C.<>c.<F>b__0_1#1(int)""
IL_003a: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_0045: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>, System.Func<int, int>)""
IL_004a: stloc.0
IL_004b: ret
}
");
}
[Fact]
public void Queries_GroupBy_Reduced2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a + 1 by a</N:1></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a by a</N:1></N:0>;
}
int[] array = null;
}
");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// lambda for GroupBy(..., a => a + 1) is gone
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: ldsfld ""System.Func<int, int> 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 ""int C.<>c.<F>b__0_1(int)""
IL_003a: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>, System.Func<int, int>)""
IL_004a: stloc.0
IL_004b: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_002b: stloc.0
IL_002c: ret
}
");
}
[Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")]
public void CapturedAnonymousTypes1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(1);
}</N:0>
}
");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(2);
}</N:0>
}
");
var source2 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(3);
}</N:0>
}
");
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 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 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.1
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
var diff1 = compilation1.EmitDifference(generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.2
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
var diff2 = compilation2.EmitDifference(diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.3
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
}
[Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")]
public void CapturedAnonymousTypes2()
{
var template = @"
using System;
class C
{
static void F()
<N:0>{
var x = new { X = <<VALUE>> };
Func<int> <N:2>y = <N:1>() => x.X</N:1></N:2>;
Console.WriteLine(y());
}</N:0>
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
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 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);
string expectedIL = @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.<<VALUE>>
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int X> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: callvirt ""int System.Func<int>.Invoke()""
IL_0026: call ""void System.Console.WriteLine(int)""
IL_002b: nop
IL_002c: 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__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<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__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<X>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[WorkItem(179990, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/179990")]
[Fact]
public void SynthesizedDelegates()
{
var template =
@"class C
{
static void F(dynamic d, out object x, object y)
<N:0>{
<<CALL>>;
}</N:0>
}";
var source0 = MarkedSource(template.Replace("<<CALL>>", "d.F(out x, new { })"));
var source1 = MarkedSource(template.Replace("<<CALL>>", "d.F(out x, new { y })"));
var source2 = MarkedSource(template.Replace("<<CALL>>", "d.F(new { y }, out x)"));
var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, references: new[] { SystemCoreRef, CSharpRef }, 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 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 112 (0x70)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.s 17
IL_0033: ldnull
IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldc.i4.1
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0058: ldfld ""<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>> System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.1
IL_0064: newobj ""<>f__AnonymousType0..ctor()""
IL_0069: callvirt ""void <>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref object, <empty anonymous type>)""
IL_006e: nop
IL_006f: ret
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F",
@"{
// Code size 113 (0x71)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.s 17
IL_0033: ldnull
IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldc.i4.1
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0058: ldfld ""<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>> System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.1
IL_0064: ldarg.2
IL_0065: newobj ""<>f__AnonymousType1<object>..ctor(object)""
IL_006a: callvirt ""void <>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref object, <anonymous type: object y>)""
IL_006f: nop
IL_0070: 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 113 (0x71)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0038: stelem.ref
IL_0039: dup
IL_003a: ldc.i4.2
IL_003b: ldc.i4.s 17
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0058: ldfld ""<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object> System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.2
IL_0064: newobj ""<>f__AnonymousType1<object>..ctor(object)""
IL_0069: ldarg.1
IL_006a: callvirt ""void <>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, ref object)""
IL_006f: nop
IL_0070: ret
}");
}
[Fact]
public void TwoStructClosures()
{
var source0 = MarkedSource(@"
public class C
{
public void F()
<N:0>{</N:0>
int <N:1>x</N:1> = 0;
<N:2>{</N:2>
int <N:3>y</N:3> = 0;
// Captures two struct closures
<N:4>int L() => x + y;</N:4>
}
}
}");
var source1 = MarkedSource(@"
public class C
{
public void F()
<N:0>{</N:0>
int <N:1>x</N:1> = 0;
<N:2>{</N:2>
int <N:3>y</N:3> = 0;
// Captures two struct closures
<N:4>int L() => x + y + 1;</N:4>
}
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {x}",
"C.<>c__DisplayClass0_1: {y}",
"C: {<F>g__L|0_0, <>c__DisplayClass0_0, <>c__DisplayClass0_1}");
v0.VerifyIL("C.<F>g__L|0_0(ref C.<>c__DisplayClass0_0, ref C.<>c__DisplayClass0_1)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ret
}");
diff1.VerifyIL("C.<F>g__L|0_0(ref C.<>c__DisplayClass0_0, ref C.<>c__DisplayClass0_1)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ThisClosureAndStructClosure()
{
var source0 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
// This + struct closures
<N:3>int L() => x + y;</N:3>
L();
}
}");
var source1 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
// This + struct closures
<N:3>int L() => x + y + 1;</N:3>
L();
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_0: {<>4__this, y}",
"C: {<F>g__L|1_0, <>c__DisplayClass1_0}");
v0.VerifyIL("C.<F>g__L|1_0(ref C.<>c__DisplayClass1_0)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass1_0.y""
IL_000c: add
IL_000d: ret
}
");
diff1.VerifyIL("C.<F>g__L|1_0(ref C.<>c__DisplayClass1_0)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass1_0.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ThisOnlyClosure()
{
var source0 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
// This-only closure
<N:2>int L() => x;</N:2>
L();
}
}");
var source1 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
// This-only closure
<N:2>int L() => x + 1;</N:2>
L();
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<F>g__L|1_0}");
v0.VerifyIL("C.<F>g__L|1_0()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ret
}");
diff1.VerifyIL("C.<F>g__L|1_0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void LocatedInSameClosureEnvironment()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
Func<int> f = <N:1>() => x</N:1>;
// Located in same closure environment
<N:2>int L() => x;</N:2>
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
Func<int> f = <N:1>() => x</N:1>;
// Located in same closure environment
<N:2>int L() => x + 1;</N:2>
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {x, <F>b__0, <F>g__L|1}",
"C: {<>c__DisplayClass0_0}");
v0.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1()", @"
{
// 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
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void SameClassEnvironmentWithStruct()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
// Same class environment, with struct env
<N:4>int L() => x + y;</N:4>
}
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
// Same class environment, with struct env
<N:4>int L() => x + y + 1;</N:4>
}
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_0: {x, <F>b__0, <F>g__L|1}",
"C.<>c__DisplayClass0_1: {y}");
v0.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1(ref C.<>c__DisplayClass0_1)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1(ref C.<>c__DisplayClass0_1)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void CaptureStructAndThroughClassEnvChain()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
<N:4>{</N:4>
Func<int> f2 = <N:5>() => x + y</N:5>;
int <N:6>z</N:6> = 0;
// Capture struct and through class env chain
<N:7>int L() => x + y + z;</N:7>
}
}
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
<N:4>{</N:4>
Func<int> f2 = <N:5>() => x + y</N:5>;
int <N:6>z</N:6> = 0;
// Capture struct and through class env chain
<N:7>int L() => x + y + z + 1;</N:7>
}
}
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_2: {z}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1, <>c__DisplayClass0_2}",
"C.<>c__DisplayClass0_1: {y, CS$<>8__locals1, <F>b__1, <F>g__L|2}");
v0.VerifyIL("C.<>c__DisplayClass0_1.<F>g__L|2(ref C.<>c__DisplayClass0_2)", @"
{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_0006: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_000b: ldarg.0
IL_000c: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_0011: add
IL_0012: ldarg.1
IL_0013: ldfld ""int C.<>c__DisplayClass0_2.z""
IL_0018: add
IL_0019: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_1.<F>g__L|2(ref C.<>c__DisplayClass0_2)", @"
{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_0006: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_000b: ldarg.0
IL_000c: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_0011: add
IL_0012: ldarg.1
IL_0013: ldfld ""int C.<>c__DisplayClass0_2.z""
IL_0018: add
IL_0019: ldc.i4.1
IL_001a: add
IL_001b: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void TopLevelStatement_Closure()
{
var source0 = MarkedSource(@"
<N:0>
using System;
Func<string> x = <N:1>() => args[0]</N:1>;
Console.WriteLine(x());
</N:0>
");
var source1 = MarkedSource(@"
<N:0>
using System;
Func<string> x = <N:1>() => args[1]</N:1>;
Console.WriteLine(x());
</N:0>
");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$");
var f1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$");
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"Program.<>c__DisplayClass0_0: {args, <<Main>$>b__0}",
"Program: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
[WorkItem(55381, "https://github.com/dotnet/roslyn/issues/55381")]
public void HiddenMethodClosure()
{
var source0 = MarkedSource(@"
#line hidden
using System;
class C
{
public static void F(int arg)
<N:0>{</N:0>
Func<int> x = <N:1>() => arg</N:1>;
}
}
");
var source1 = MarkedSource(@"
#line hidden
using System;
class C
{
public static void F(int arg)
<N:0>{</N:0>
Func<int> x = <N:1>() => arg + 1</N:1>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll);
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {arg, <F>b__0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.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.Collections.Immutable;
using System.Linq;
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
{
public class EditAndContinueClosureTests : EditAndContinueTestBase
{
[Fact]
public void MethodToMethodWithClosure()
{
var source0 =
@"delegate object D();
class C
{
static object F(object o)
{
return o;
}
}";
var source1 =
@"delegate object D();
class C
{
static object F(object o)
{
return ((D)(() => o))();
}
}";
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.Update, compilation0.GetMember<MethodSymbol>("C.F"), compilation1.GetMember<MethodSymbol>("C.F"))));
using (var md1 = diff1.GetMetadata())
{
var reader1 = md1.Reader;
// Field 'o'
// Methods: 'F', '.ctor', '<F>b__1'
// Type: display class
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField),
Row(1, TableIndex.Field, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(1, TableIndex.NestedClass, EditAndContinueOperation.Default));
}
}
[Fact]
public void MethodWithStaticLambda1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
Func<int> x = <N:0>() => 1</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
Func<int> x = <N:0>() => 2</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithSwitchExpression()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(object o)
{
<N:0>return o switch
{
int i => new Func<int>(<N:1>() => i + 1</N:1>)(),
_ => 0
}</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(object o)
{
<N:0>return o switch
{
int i => new Func<int>(<N:1>() => i + 2</N:1>)(),
_ => 0
}</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {<i>5__2, <F>b__0}",
"C: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
var x = Visualize(generation0.OriginalMetadata, md1);
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithNestedSwitchExpression()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(object o)
<N:0>{
<N:1>return o switch
{
int i => new Func<int>(<N:2>() => i + (int)o + i switch
{
1 => 1,
_ => new Func<int>(<N:3>() => (int)o + 1</N:3>)()
}</N:2>)(),
_ => 0
}</N:1>;
}</N:0>
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(object o)
<N:0>{
<N:1>return o switch
{
int i => new Func<int>(<N:2>() => i + (int)o + i switch
{
1 => 1,
_ => new Func<int>(<N:3>() => (int)o + 2</N:3>)()
}</N:2>)(),
_ => 0
}</N:1>;
}</N:0>
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_1: {<i>5__2, CS$<>8__locals2, <F>b__0}",
"C.<>c__DisplayClass0_0: {o, <>9__1, <F>b__1}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunction1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 1;</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 2;</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunction_ChangeStatic()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>int x() => 1;</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F()
{
<N:0>static int x() => 1;</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
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.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
var testData0 = new CompilationTestData();
var bytes0 = compilation0.EmitToArray(testData: testData0);
var localFunction0 = testData0.GetMethodData("C.<F>g__x|0_0").Method;
Assert.True(((Symbol)localFunction0).IsStatic);
var localFunction1 = diff1.TestData.GetMethodData("C.<F>g__x|0_0").Method;
Assert.True(((Symbol)localFunction1).IsStatic);
}
[Fact]
public void MethodWithStaticLambdaGeneric1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
Func<T> x = <N:0>() => default(T)</N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
Func<T> x = <N:0>() => default(T)</N:0>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__0}",
"C.<>c__0<T>: {<>9__0_0, <F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithStaticLocalFunctionGeneric1()
{
var source0 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
<N:0>T x() => default(T);</N:0>
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
void F<T>()
{
<N:0>T x() => default(T);</N:0>
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithThisOnlyClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
Func<int> x = <N:0>() => F(1)</N:0>;
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
Func<int> x = <N:0>() => F(2)</N:0>;
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithThisOnlyLocalFunctionClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
<N:0>int x() => F(1);</N:0>
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
{
<N:0>int x() => F(2);</N:0>
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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.VerifySynthesizedMembers(
"C: {<F>g__x|0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
Func<int> x = <N:1>() => F(a + 1)</N:1>;
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
Func<int> x = <N:1>() => F(a + 2)</N:1>;
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {<>4__this, a, <F>b__0}",
"C: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void MethodWithNullable_AddingNullCheck()
{
var source0 = MarkedSource(@"
using System;
#nullable enable
class C
{
static T id<T>(T t) => t;
static T G<T>(Func<T> f) => f();
public void F(string? x)
<N:0>{</N:0>
var <N:1>y1</N:1> = new { A = id(x) };
var <N:2>y2</N:2> = G(<N:3>() => new { B = id(x) }</N:3>);
var <N:4>z</N:4> = G(<N:5>() => y1.A + y2.B</N:5>);
}
}", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
var source1 = MarkedSource(@"
using System;
#nullable enable
class C
{
static T id<T>(T t) => t;
static T G<T>(Func<T> f) => f();
public void F(string? x)
<N:0>{</N:0>
if (x is null) throw new Exception();
var <N:1>y1</N:1> = new { A = id(x) };
var <N:2>y2</N:2> = G(<N:3>() => new { B = id(x) }</N:3>);
var <N:4>z</N:4> = G(<N:5>() => y1.A + y2.B</N:5>);
}
}", options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp9));
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.VerifySynthesizedMembers(
"Microsoft.CodeAnalysis: {EmbeddedAttribute}",
"Microsoft: {CodeAnalysis}",
"System.Runtime: {CompilerServices, CompilerServices}",
"<global namespace>: {Microsoft, System, System}",
"C: {<>c__DisplayClass2_0}",
"System: {Runtime, Runtime}",
"C.<>c__DisplayClass2_0: {x, y1, y2, <F>b__0, <F>b__1}",
"<>f__AnonymousType1<<B>j__TPar>: {Equals, GetHashCode, ToString}",
"System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.<>c__DisplayClass2_0.<F>b__1()", @"
{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""<anonymous type: string A> C.<>c__DisplayClass2_0.y1""
IL_0006: callvirt ""string <>f__AnonymousType0<string>.A.get""
IL_000b: ldarg.0
IL_000c: ldfld ""<anonymous type: string B> C.<>c__DisplayClass2_0.y2""
IL_0011: callvirt ""string <>f__AnonymousType1<string>.B.get""
IL_0016: call ""string string.Concat(string, string)""
IL_001b: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass2_0.<F>b__0()", @"
{
// Code size 17 (0x11)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""string C.<>c__DisplayClass2_0.x""
IL_0006: call ""string C.id<string>(string)""
IL_000b: newobj ""<>f__AnonymousType1<string>..ctor(string)""
IL_0010: ret
}");
}
[Fact]
public void MethodWithLocalFunctionClosure1()
{
var source0 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
<N:1>int x() => F(a + 1);</N:1>
return 1;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
int F(int a)
<N:0>{</N:0>
<N:1>int x() => F(a + 2);</N:1>
return 2;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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.VerifySynthesizedMembers(
"C: {<F>g__x|0_0, <>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {<>4__this, a}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ConstructorWithClosure1()
{
var source0 = MarkedSource(@"
using System;
class D { public D(Func<int> f) { } }
class C : D
{
<N:0>public C(int a, int b)</N:0>
: base(<N:8>() => a</N:8>)
<N:1>{</N:1>
int c = 0;
Func<int> f1 = <N:2>() => a + 1</N:2>;
Func<int> f2 = <N:3>() => b + 2</N:3>;
Func<int> f3 = <N:4>() => c + 3</N:4>;
Func<int> f4 = <N:5>() => a + b + c</N:5>;
Func<int> f5 = <N:6>() => a + c</N:6>;
Func<int> f6 = <N:7>() => b + c</N:7>;
}
}");
var source1 = MarkedSource(@"
using System;
class D { public D(Func<int> f) { } }
class C : D
{
<N:0>public C(int a, int b)</N:0>
: base(<N:8>() => a * 10</N:8>)
<N:1>{</N:1>
int c = 0;
Func<int> f1 = <N:2>() => a * 10 + 1</N:2>;
Func<int> f2 = <N:3>() => b * 10 + 2</N:3>;
Func<int> f3 = <N:4>() => c * 10 + 3</N:4>;
Func<int> f4 = <N:5>() => a * 10 + b + c</N:5>;
Func<int> f5 = <N:6>() => a * 10 + c</N:6>;
Func<int> f6 = <N:7>() => b * 10 + c</N:7>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var ctor1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_0: {a, b, <.ctor>b__0, <.ctor>b__1, <.ctor>b__2}",
"C.<>c__DisplayClass0_1: {c, CS$<>8__locals1, <.ctor>b__3, <.ctor>b__4, <.ctor>b__5, <.ctor>b__6}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, 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(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void PartialClass()
{
var source0 = MarkedSource(@"
using System;
partial class C
{
Func<int> m1 = <N:0>() => 1</N:0>;
}
partial class C
{
Func<int> m2 = <N:1>() => 1</N:1>;
}
");
var source1 = MarkedSource(@"
using System;
partial class C
{
Func<int> m1 = <N:0>() => 10</N:0>;
}
partial class C
{
Func<int> m2 = <N:1>() => 10</N:1>;
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
var ctor1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single();
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <.ctor>b__2_0, <.ctor>b__2_1}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default));
}
[Fact]
public void JoinAndGroupByClauses()
{
var source0 = MarkedSource(@"
using System.Linq;
class C
{
void F()
{
var result = <N:0>from a in new[] { 1, 2, 3 }</N:0>
<N:1>join b in new[] { 5 } on a + 1 equals b - 1</N:1>
<N:2>group</N:2> new { a, b = a + 5 } by new { c = a + 4 } into d
<N:3>select d.Key</N:3>;
}
}");
var source1 = MarkedSource(@"
using System.Linq;
class C
{
void F()
{
var result = <N:0>from a in new[] { 10, 20, 30 }</N:0>
<N:1>join b in new[] { 50 } on a + 10 equals b - 10</N:1>
<N:2>group</N:2> new { a, b = a + 50 } by new { c = a + 40 } into d
<N:3>select d.Key</N:3>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <>9__0_4, <>9__0_5, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3, <F>b__0_4, <F>b__0_5}",
"<>f__AnonymousType1<<c>j__TPar>: {Equals, GetHashCode, ToString}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(16, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(17, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(20, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(21, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(7, TableIndex.Param, EditAndContinueOperation.Default),
Row(8, TableIndex.Param, EditAndContinueOperation.Default),
Row(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(10, TableIndex.Param, EditAndContinueOperation.Default),
Row(11, TableIndex.Param, EditAndContinueOperation.Default),
Row(12, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_FromClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var <N:10>result = <N:0>from a in new[] { 1 }</N:0>
<N:1>from b in <N:9>new[] { 1 }</N:9></N:1>
<N:2>where <N:7>Z(<N:5>() => a</N:5>) > 0</N:7></N:2>
<N:3>where <N:8>Z(<N:6>() => b</N:6>) > 0</N:8></N:3>
<N:4>select a</N:4></N:10>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var <N:10>result = <N:0>from a in new[] { 1 }</N:0>
<N:1>from b in <N:9>new[] { 2 }</N:9></N:1>
<N:2>where <N:7>Z(<N:5>() => a</N:5>) > 1</N:7></N:2>
<N:3>where <N:8>Z(<N:6>() => b</N:6>) > 2</N:8></N:3>
<N:4>select a</N:4></N:10>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_1: {<>h__TransparentIdentifier0, <F>b__6}",
"C.<>c__DisplayClass1_0: {<>h__TransparentIdentifier0, <F>b__5}",
"C.<>c: {<>9__1_0, <>9__1_1, <>9__1_4, <F>b__1_0, <F>b__1_1, <F>b__1_4}",
"C: {<F>b__1_2, <F>b__1_3, <>c__DisplayClass1_0, <>c__DisplayClass1_1, <>c}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(18, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(19, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(20, TableIndex.MethodDef, 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(9, TableIndex.Param, EditAndContinueOperation.Default),
Row(10, TableIndex.Param, EditAndContinueOperation.Default),
Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_LetClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = <N:0>from a in new[] { 1 }</N:0>
<N:1>let b = <N:2>Z(<N:3>() => a</N:3>)</N:2></N:1>
<N:4>select <N:5>a + b</N:5></N:4>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
void F()
{
var result = <N:0>from a in new[] { 1 }</N:0>
<N:1>let b = <N:2>Z(<N:3>() => a</N:3>) + 1</N:2></N:1>
<N:4>select <N:5>a + b</N:5></N:4>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c: {<>9__1_1, <F>b__1_1}",
"<>f__AnonymousType0<<a>j__TPar, <b>j__TPar>: {Equals, GetHashCode, ToString}",
"C.<>c__DisplayClass1_0: {a, <F>b__2}",
"C: {<F>b__1_0, <>c__DisplayClass1_0, <>c}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(6, TableIndex.Param, EditAndContinueOperation.Default),
Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_JoinClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>Z(<N:4>() => <N:5>a + 1</N:5></N:4>)</N:3>
equals
<N:6>Z(<N:7>() => <N:8>b - 1</N:8></N:7>)</N:6></N:2>
<N:9>select <N:10>Z(<N:11>() => <N:12>a + b</N:12></N:11>)</N:10></N:9>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>Z(<N:4>() => <N:5>a + 1</N:5></N:4>)</N:3>
equals
<N:6>Z(<N:7>() => <N:8>b - 1</N:8></N:7>)</N:6></N:2>
<N:9>select <N:10>Z(<N:11>() => <N:12>a - b</N:12></N:11>)</N:10></N:9>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_1: {b, <F>b__4}",
"C.<>c__DisplayClass1_2: {a, b, <F>b__5}",
"C.<>c__DisplayClass1_0: {a, <F>b__3}",
"C: {<F>b__1_0, <F>b__1_1, <F>b__1_2, <>c__DisplayClass1_0, <>c__DisplayClass1_1, <>c__DisplayClass1_2}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(7, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(8, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(9, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default),
Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_JoinIntoClause()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>a + 1</N:3> equals <N:4>b - 1</N:4>
into g</N:2>
<N:5>select <N:6>Z(<N:7>() => <N:8>g.First()</N:8></N:7>)</N:6></N:5>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>join b in new[] { 3 } on
<N:3>a + 1</N:3> equals <N:4>b - 1</N:4>
into g</N:2>
<N:5>select <N:6>Z(<N:7>() => <N:8>g.Last()</N:8></N:7>)</N:6></N:5>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__1_2, <>c__DisplayClass1_0, <>c}",
"C.<>c: {<>9__1_0, <>9__1_1, <F>b__1_0, <F>b__1_1}",
"C.<>c__DisplayClass1_0: {g, <F>b__3}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(4, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void TransparentIdentifiers_QueryContinuation()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>group a by <N:3>a + 1</N:3></N:2>
<N:4>into g
<N:5>select <N:6>Z(<N:7>() => <N:8>g.First()</N:8></N:7>)</N:6></N:5></N:4>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
int Z(Func<int> f)
{
return 1;
}
public void F()
{
var result = <N:0>from a in <N:1>new[] { 1 }</N:1></N:0>
<N:2>group a by <N:3>a + 1</N:3></N:2>
<N:4>into g
<N:5>select <N:6>Z(<N:7>() => <N:8>g.Last()</N:8></N:7>)</N:6></N:5></N:4>;
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<F>b__1_1, <>c__DisplayClass1_0, <>c}",
"C.<>c: {<>9__1_0, <F>b__1_0}",
"C.<>c__DisplayClass1_0: {g, <F>b__2}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates for lambdas:
CheckEncLogDefinitions(reader1,
Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default),
Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void Lambdas_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(null);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 1</N:0>);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 2</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);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0#1, <F>b__0#1}");
// added:
diff1.VerifyIL("C.<>c.<F>b__0#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
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#1, <F>b__0#1}");
// updated:
diff2.VerifyIL("C.<>c.<F>b__0#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LocalFunctions_UpdateAfterAdd()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(null);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f(int a) => a + 1;</N:0>
return G(f);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f(int a) => a + 2;</N:0>
return G(f);
}
}");
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);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// added:
diff1.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// updated:
diff2.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LocalFunctions_UpdateAfterAdd_NoDelegatePassing()
{
var source0 = MarkedSource(@"
using System;
class C
{
static object F()
{
return 0;
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static object F()
{
<N:0>int f(int a) => a + 1;</N:0>
return 1;
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static object F()
{
<N:0>int f(int a) => a + 2;</N:0>
return 2;
}
}");
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);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// added:
diff1.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f|0#1}");
// updated:
diff2.VerifyIL("C.<F>g__f|0#1(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
}
[Fact]
public void LambdasMultipleGenerations1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 1</N:0>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 2</N:0>) + G(<N:1>b => b + 20</N:1>);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 3</N:0>) + G(<N:1>b => b + 30</N:1>) + G(<N:2>c => c + 0x300</N:2>);
}
}");
var source3 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + 4</N:0>) + G(<N:1>b => b + 40</N:1>) + G(<N:2>c => c + 0x400</N:2>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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 f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var f3 = compilation3.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();
var reader1 = md1.Reader;
// new lambda "<F>b__1_1#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <F>b__1_0, <F>b__1_1#1}");
// updated:
diff1.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
// added:
diff1.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 20
IL_0003: add
IL_0004: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// new lambda "<F>b__1_2#2" has been added:
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <>9__1_2#2, <F>b__1_0, <F>b__1_1#1, <F>b__1_2#2}");
// updated:
diff2.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.3
IL_0002: add
IL_0003: ret
}
");
// updated:
diff2.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 30
IL_0003: add
IL_0004: ret
}
");
// added:
diff2.VerifyIL("C.<>c.<F>b__1_2#2", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4 0x300
IL_0006: add
IL_0007: ret
}
");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__1_0, <>9__1_1#1, <>9__1_2#2, <F>b__1_0, <F>b__1_1#1, <F>b__1_2#2}");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.4
IL_0002: add
IL_0003: ret
}
");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_1#1", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.s 40
IL_0003: add
IL_0004: ret
}
");
// updated:
diff3.VerifyIL("C.<>c.<F>b__1_2#2", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4 0x400
IL_0006: add
IL_0007: ret
}
");
}
[Fact]
public void LocalFunctionsMultipleGenerations1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 1;</N:0>
return G(f1);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 2;</N:0>
<N:1>int f2(int b) => b + 20;</N:1>
return G(f1) + G(f2);
}
}");
var source2 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 3;</N:0>
<N:1>int f2(int b) => b + 30;</N:1>
<N:2>int f3(int c) => c + 0x300;</N:2>
return G(f1) + G(f2) + G(f3);
}
}");
var source3 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
<N:0>int f1(int a) => a + 4;</N:0>
<N:1>int f2(int b) => b + 40;</N:1>
<N:2>int f3(int c) => c + 0x400;</N:2>
return G(f1) + G(f2) + G(f3);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
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 f0 = compilation0.GetMember<MethodSymbol>("C.F");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f2 = compilation2.GetMember<MethodSymbol>("C.F");
var f3 = compilation3.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();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1}");
// updated:
diff1.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.2
IL_0002: add
IL_0003: ret
}
");
// added:
diff1.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 20
IL_0003: add
IL_0004: ret
}
");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1, <F>g__f3|1_2#2}");
// updated:
diff2.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.3
IL_0002: add
IL_0003: ret
}
");
// updated:
diff2.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 30
IL_0003: add
IL_0004: ret
}
");
// added:
diff2.VerifyIL("C.<F>g__f3|1_2#2(int)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x300
IL_0006: add
IL_0007: ret
}
");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f2, f3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C: {<F>g__f1|1_0, <F>g__f2|1_1#1, <F>g__f3|1_2#2}");
// updated:
diff3.VerifyIL("C.<F>g__f1|1_0(int)", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.4
IL_0002: add
IL_0003: ret
}
");
// updated:
diff3.VerifyIL("C.<F>g__f2|1_1#1(int)", @"
{
// Code size 5 (0x5)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 40
IL_0003: add
IL_0004: ret
}
");
// updated:
diff3.VerifyIL("C.<F>g__f3|1_2#2(int)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4 0x400
IL_0006: add
IL_0007: ret
}
");
}
[Fact, WorkItem(2284, "https://github.com/dotnet/roslyn/issues/2284")]
public void LambdasMultipleGenerations2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
// var z = from title in _titles
// where title > 0
// select title;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
// Console.WriteLine(2);
}</N:1></N:0>;
}
}");
var source1 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
var <N:3>z = from title in _titles
<N:2>where title > 0</N:2>
select title</N:3>;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
// Console.WriteLine(2);
}</N:1></N:0>;
}
}");
var source2 = MarkedSource(@"
using System;
using System.Linq;
class C
{
private int[] _titles = new int[] { 1, 2 };
Action A;
private void F()
{
// edit 1
var <N:3>z = from title in _titles
<N:2>where title > 0</N:2>
select title</N:3>;
A += <N:0>() =>
<N:1>{
Console.WriteLine(1);
// edit 2
Console.WriteLine(2);
}</N:1></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);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda "<F>b__2_0#1" has been added:
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <F>b__2_0#1, <F>b__2_0}");
// lambda body unchanged:
diff1.VerifyIL("C.<>c.<F>b__2_0", @"
{
// Code size 9 (0x9)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ret
}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
// no new members:
diff2.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <F>b__2_0#1, <F>b__2_0}");
// lambda body updated:
diff2.VerifyIL("C.<>c.<F>b__2_0", @"
{
// Code size 16 (0x10)
.maxstack 1
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: call ""void System.Console.WriteLine(int)""
IL_0007: nop
IL_0008: ldc.i4.2
IL_0009: call ""void System.Console.WriteLine(int)""
IL_000e: nop
IL_000f: ret
}");
}
[Fact]
public void UniqueSynthesizedNames1()
{
var source0 = @"
using System;
public class C
{
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source1 = @"
using System;
public class C
{
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F(byte x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f_int1 = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c__DisplayClass0_0", "<>c");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor", "<F>b__1", "<F>b__2", ".cctor", ".ctor", "<F>b__0_0");
CheckNames(reader0, reader0.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0_0");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>c__DisplayClass0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetMethodDefNames(), ".ctor", "F", ".ctor", "<F>b__1#1", "<F>b__2#1", "<F>b__0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetFieldDefNames(), "<>4__this", "a", "<>9__0#1_0#1");
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0#1_0#1, <>c}",
"C.<>c__DisplayClass0#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C.<>c: {<>9__0#1_0#1, <F>b__0#1_0#1}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>c__DisplayClass1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetMethodDefNames(), ".ctor", "F", ".ctor", "<F>b__1#2", "<F>b__2#2", "<F>b__1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetFieldDefNames(), "<>4__this", "a", "<>9__1#2_0#2");
}
[Fact]
public void UniqueSynthesizedNames1_Generic()
{
var source0 = @"
using System;
public class C
{
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source1 = @"
using System;
public class C
{
public int F<T>(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public int F<T>(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>(byte x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
public int F<T>()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F<T>());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var f_int1 = compilation1.GetMembers("C.F").Single(m => m.ToString() == "C.F<T>(int)");
var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F<T>(byte)");
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var reader0 = md0.MetadataReader;
CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c__DisplayClass0_0`1", "<>c__0`1");
CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor", "<F>b__1", "<F>b__2", ".cctor", ".ctor", "<F>b__0_0");
CheckNames(reader0, reader0.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0_0");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int1)));
var reader1 = diff1.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>c__DisplayClass0#1_0#1`1", "<>c__0#1`1");
CheckNames(new[] { reader0, reader1 }, reader1.GetMethodDefNames(), "F", ".ctor", "<F>b__1#1", "<F>b__2#1", ".cctor", ".ctor", "<F>b__0#1_0#1");
CheckNames(new[] { reader0, reader1 }, reader1.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__0#1_0#1");
diff1.VerifySynthesizedMembers(
"C.<>c__0#1<T>: {<>9__0#1_0#1, <F>b__0#1_0#1}",
"C: {<>c__DisplayClass0#1_0#1, <>c__0#1}",
"C.<>c__DisplayClass0#1_0#1<T>: {<>4__this, a, <F>b__1#1, <F>b__2#1}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2)));
var reader2 = diff2.GetMetadata().Reader;
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>c__DisplayClass1#2_0#2`1", "<>c__1#2`1");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetMethodDefNames(), "F", ".ctor", "<F>b__1#2", "<F>b__2#2", ".cctor", ".ctor", "<F>b__1#2_0#2");
CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetFieldDefNames(), "<>4__this", "a", "<>9", "<>9__1#2_0#2");
}
[Fact]
public void UniqueSynthesizedNames2()
{
var source0 = @"
using System;
public class C
{
public static void Main()
{
}
}";
var source1 = @"
using System;
public class C
{
public static void Main()
{
new C().F();
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source2 = @"
using System;
public class C
{
public static void Main()
{
new C().F(1);
new C().F();
}
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var source3 = @"
using System;
public class C
{
public static void Main()
{
}
public int F(int x)
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
public int F()
{
var a = 1;
var f1 = new Func<int>(() => 1);
var f2 = new Func<int>(() => F());
var f3 = new Func<int>(() => a);
return 2;
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A");
var compilation1 = compilation0.WithSource(source1);
var compilation2 = compilation1.WithSource(source2);
var compilation3 = compilation2.WithSource(source3);
var main0 = compilation0.GetMember<MethodSymbol>("C.Main");
var main1 = compilation1.GetMember<MethodSymbol>("C.Main");
var main2 = compilation2.GetMember<MethodSymbol>("C.Main");
var main3 = compilation3.GetMember<MethodSymbol>("C.Main");
var f1 = compilation1.GetMember<MethodSymbol>("C.F");
var f_int2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(int)");
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.Insert, null, f1),
SemanticEdit.Create(SemanticEditKind.Update, main0, main1, preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C.<>c: {<>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C: {<>c__DisplayClass1#1_0#1, <>c}");
var diff2 = compilation2.EmitDifference(
diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, f_int2),
SemanticEdit.Create(SemanticEditKind.Update, main1, main2, preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C.<>c__DisplayClass1#2_0#2: {<>4__this, a, <F>b__1#2, <F>b__2#2}",
"C: {<>c__DisplayClass1#2_0#2, <>c, <>c__DisplayClass1#1_0#1}",
"C.<>c: {<>9__1#2_0#2, <F>b__1#2_0#2, <>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}");
var diff3 = compilation3.EmitDifference(
diff2.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, main2, main3, preserveLocalVariables: true)));
diff3.VerifySynthesizedMembers(
"C.<>c__DisplayClass1#1_0#1: {<>4__this, a, <F>b__1#1, <F>b__2#1}",
"C.<>c: {<>9__1#2_0#2, <F>b__1#2_0#2, <>9__1#1_0#1, <F>b__1#1_0#1}",
"C.<>c__DisplayClass1#2_0#2: {<>4__this, a, <F>b__1#2, <F>b__2#2}",
"C: {<>c__DisplayClass1#2_0#2, <>c, <>c__DisplayClass1#1_0#1}");
}
[Fact]
public void NestedLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + G(<N:1>b => 1</N:1>)</N:0>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
static object F()
{
return G(<N:0>a => a + G(<N:1>b => 2</N:1>)</N:0>);
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// 3 method updates:
// Note that even if the change is in the inner lambda such a change will usually impact sequence point
// spans in outer lambda and the method body. So although the IL doesn't change we usually need to update the outer methods.
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(2, TableIndex.Param, EditAndContinueOperation.Default),
Row(3, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void LambdasInInitializers1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => a + 1</N:0>);
public C() : this(G(<N:1>a => a + 2</N:1>))
{
G(<N:2>a => a + 3</N:2>);
}
public C(int x)
{
G(<N:3>a => a + 4</N:3>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => a - 1</N:0>);
public C() : this(G(<N:1>a => a - 2</N:1>))
{
G(<N:2>a => a - 3</N:2>);
}
public C(int x)
{
G(<N:3>a => a - 4</N:3>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor00 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor10 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var ctor01 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor11 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor00, ctor01, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, ctor10, ctor11, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <>9__3_0, <>9__3_1, <.ctor>b__2_0, <.ctor>b__2_1, <.ctor>b__3_0, <.ctor>b__3_1}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.2
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.3
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_0", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.4
IL_0002: sub
IL_0003: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: sub
IL_0003: ret
}");
}
[Fact]
public void LambdasInInitializers2()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => { int <N:4>v1 = 1</N:4>; return 1; }</N:0>);
public C() : this(G(<N:1>a => { int <N:5>v2 = 1</N:5>; return 2; }</N:1>))
{
G(<N:2>a => { int <N:6>v3 = 1</N:6>; return 3; }</N:2>);
}
public C(int x)
{
G(<N:3>a => { int <N:7>v4 = 1</N:7>; return 4; }</N:3>);
}
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int G(Func<int, int> f) => 1;
public int A = G(<N:0>a => { int <N:4>v1 = 10</N:4>; return 1; }</N:0>);
public C() : this(G(<N:1>a => { int <N:5>v2 = 10</N:5>; return 2; }</N:1>))
{
G(<N:2>a => { int <N:6>v3 = 10</N:6>; return 3; }</N:2>);
}
public C(int x)
{
G(<N:3>a => { int <N:7>v4 = 10</N:7>; return 4; }</N:3>);
}
}");
var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var ctor00 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor10 = compilation0.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var ctor01 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor()");
var ctor11 = compilation1.GetMembers("C..ctor").Single(m => m.ToTestDisplayString() == "C..ctor(System.Int32 x)");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, ctor00, ctor01, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true),
SemanticEdit.Create(SemanticEditKind.Update, ctor10, ctor11, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0, <>9__2_1, <>9__3_0, <>9__3_1, <.ctor>b__2_0, <.ctor>b__2_1, <.ctor>b__3_0, <.ctor>b__3_1}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_0", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v2
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.2
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__2_1", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v3
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_0", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v4
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.4
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
diff1.VerifyIL("C.<>c.<.ctor>b__3_1", @"
{
// Code size 10 (0xa)
.maxstack 1
.locals init (int V_0, //v1
[int] V_1,
int V_2)
IL_0000: nop
IL_0001: ldc.i4.s 10
IL_0003: stloc.0
IL_0004: ldc.i4.1
IL_0005: stloc.2
IL_0006: br.s IL_0008
IL_0008: ldloc.2
IL_0009: ret
}");
}
[Fact]
public void UpdateParameterlessConstructorInPresenceOfFieldInitializersWithLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
int B = F(b => b + 1); // new field
public C() // new ctor
{
F(c => c + 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 b1 = compilation1.GetMember<FieldSymbol>("C.B");
var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, b1),
SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <>9__2_2#1, <.ctor>b__2_0#1, <.ctor>b__2_0, <.ctor>b__2_2#1}");
diff1.VerifyIL("C..ctor", @"
{
// Code size 130 (0x82)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldsfld ""System.Func<int, int> C.<>c.<>9__2_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.<.ctor>b__2_0(int)""
IL_0015: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_001a: dup
IL_001b: stsfld ""System.Func<int, int> C.<>c.<>9__2_0""
IL_0020: call ""int C.F(System.Func<int, int>)""
IL_0025: stfld ""int C.A""
IL_002a: ldarg.0
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__2_2#1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<.ctor>b__2_2#1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__2_2#1""
IL_004a: call ""int C.F(System.Func<int, int>)""
IL_004f: stfld ""int C.B""
IL_0054: ldarg.0
IL_0055: call ""object..ctor()""
IL_005a: nop
IL_005b: nop
IL_005c: ldsfld ""System.Func<int, int> C.<>c.<>9__2_0#1""
IL_0061: dup
IL_0062: brtrue.s IL_007b
IL_0064: pop
IL_0065: ldsfld ""C.<>c C.<>c.<>9""
IL_006a: ldftn ""int C.<>c.<.ctor>b__2_0#1(int)""
IL_0070: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0075: dup
IL_0076: stsfld ""System.Func<int, int> C.<>c.<>9__2_0#1""
IL_007b: call ""int C.F(System.Func<int, int>)""
IL_0080: pop
IL_0081: ret
}
");
}
[Fact(Skip = "2504"), WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")]
public void InsertConstructorInPresenceOfFieldInitializersWithLambdas()
{
var source0 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
}");
var source1 = MarkedSource(@"
using System;
class C
{
static int F(Func<int, int> x) => 1;
int A = F(<N:0>a => a + 1</N:0>);
int B = F(b => b + 1); // new field
public C(int x) // new ctor
{
F(c => c + 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 b1 = compilation1.GetMember<FieldSymbol>("C.B");
var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor");
var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo);
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Insert, null, b1),
SemanticEdit.Create(SemanticEditKind.Insert, null, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<> c}",
"C.<>c: {<>9__2_0#1, <>9__2_0, <>9__2_2#1, <.ctor>b__2_0#1, <.ctor>b__2_0, <.ctor>b__2_2#1}");
}
[Fact]
public void Queries_Select_Reduced1()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a</N:2></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a + 1</N:2></N:0>;
}
int[] array = null;
}
");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda for Select(a => a + 1)
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <F>b__0_0, <F>b__0_1#1}");
diff1.VerifyIL("C.<>c.<F>b__0_1#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: stloc.0
IL_002c: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<F>b__0_1#1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_004a: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_004f: stloc.0
IL_0050: ret
}
");
}
[Fact]
public void Queries_Select_Reduced2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a + 1</N:2></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>where a > 0</N:1>
<N:2>select a</N:2></N:0>;
}
int[] array = null;
}
");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// lambda for Select(a => a + 1) is gone
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 81 (0x51)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_0030: dup
IL_0031: brtrue.s IL_004a
IL_0033: pop
IL_0034: ldsfld ""C.<>c C.<>c.<>9""
IL_0039: ldftn ""int C.<>c.<F>b__0_1(int)""
IL_003f: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0044: dup
IL_0045: stsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_004a: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_004f: stloc.0
IL_0050: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<int> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""bool C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, bool> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Where<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)""
IL_002b: stloc.0
IL_002c: ret
}
");
}
[Fact]
public void Queries_GroupBy_Reduced1()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a by a</N:1></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a + 1 by a</N:1></N:0>;
}
int[] array = null;
}
");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// new lambda for GroupBy(..., a => a + 1)
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <>9__0_1#1, <F>b__0_0, <F>b__0_1#1}");
diff1.VerifyIL("C.<>c.<F>b__0_1#1", @"
{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
}
");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_002b: stloc.0
IL_002c: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: ldsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_002b: dup
IL_002c: brtrue.s IL_0045
IL_002e: pop
IL_002f: ldsfld ""C.<>c C.<>c.<>9""
IL_0034: ldftn ""int C.<>c.<F>b__0_1#1(int)""
IL_003a: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<int, int> C.<>c.<>9__0_1#1""
IL_0045: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>, System.Func<int, int>)""
IL_004a: stloc.0
IL_004b: ret
}
");
}
[Fact]
public void Queries_GroupBy_Reduced2()
{
var source0 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a + 1 by a</N:1></N:0>;
}
int[] array = null;
}
");
var source1 = MarkedSource(@"
using System;
using System.Linq;
using System.Collections.Generic;
class C
{
void F()
{
var <N:0>result = from a in array
<N:1>group a by a</N:1></N:0>;
}
int[] array = null;
}
");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// lambda for GroupBy(..., a => a + 1) is gone
diff1.VerifySynthesizedMembers(
"C: {<>c}",
"C.<>c: {<>9__0_0, <F>b__0_0}");
// old query:
v0.VerifyIL("C.F", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: ldsfld ""System.Func<int, int> 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 ""int C.<>c.<F>b__0_1(int)""
IL_003a: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_003f: dup
IL_0040: stsfld ""System.Func<int, int> C.<>c.<>9__0_1""
IL_0045: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>, System.Func<int, int>)""
IL_004a: stloc.0
IL_004b: ret
}
");
// new query:
diff1.VerifyIL("C.F", @"
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> V_0) //result
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldfld ""int[] C.array""
IL_0007: ldsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_000c: dup
IL_000d: brtrue.s IL_0026
IL_000f: pop
IL_0010: ldsfld ""C.<>c C.<>c.<>9""
IL_0015: ldftn ""int C.<>c.<F>b__0_0(int)""
IL_001b: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)""
IL_0020: dup
IL_0021: stsfld ""System.Func<int, int> C.<>c.<>9__0_0""
IL_0026: call ""System.Collections.Generic.IEnumerable<System.Linq.IGrouping<int, int>> System.Linq.Enumerable.GroupBy<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)""
IL_002b: stloc.0
IL_002c: ret
}
");
}
[Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")]
public void CapturedAnonymousTypes1()
{
var source0 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(1);
}</N:0>
}
");
var source1 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(2);
}</N:0>
}
");
var source2 = MarkedSource(@"
using System;
class C
{
static void F()
<N:0>{
var <N:1>x = new { A = 1 }</N:1>;
var <N:2>y = new Func<int>(<N:3>() => x.A</N:3>)</N:2>;
Console.WriteLine(3);
}</N:0>
}
");
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 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 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.1
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
var diff1 = compilation1.EmitDifference(generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff1.VerifyIL("C.F", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.2
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
var diff2 = compilation2.EmitDifference(diff1.NextGeneration,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true)));
diff2.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", @"
{
// Code size 40 (0x28)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int A> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldc.i4.3
IL_0021: call ""void System.Console.WriteLine(int)""
IL_0026: nop
IL_0027: ret
}");
}
[Fact, WorkItem(1170899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1170899")]
public void CapturedAnonymousTypes2()
{
var template = @"
using System;
class C
{
static void F()
<N:0>{
var x = new { X = <<VALUE>> };
Func<int> <N:2>y = <N:1>() => x.X</N:1></N:2>;
Console.WriteLine(y());
}</N:0>
}
";
var source0 = MarkedSource(template.Replace("<<VALUE>>", "0"));
var source1 = MarkedSource(template.Replace("<<VALUE>>", "1"));
var source2 = MarkedSource(template.Replace("<<VALUE>>", "2"));
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 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);
string expectedIL = @"
{
// Code size 45 (0x2d)
.maxstack 2
.locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
System.Func<int> V_1) //y
IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
IL_0006: nop
IL_0007: ldloc.0
IL_0008: ldc.i4.<<VALUE>>
IL_0009: newobj ""<>f__AnonymousType0<int>..ctor(int)""
IL_000e: stfld ""<anonymous type: int X> C.<>c__DisplayClass0_0.x""
IL_0013: ldloc.0
IL_0014: ldftn ""int C.<>c__DisplayClass0_0.<F>b__0()""
IL_001a: newobj ""System.Func<int>..ctor(object, System.IntPtr)""
IL_001f: stloc.1
IL_0020: ldloc.1
IL_0021: callvirt ""int System.Func<int>.Invoke()""
IL_0026: call ""void System.Console.WriteLine(int)""
IL_002b: nop
IL_002c: 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__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<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__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"<>f__AnonymousType0<<X>j__TPar>: {Equals, GetHashCode, ToString}");
diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2"));
}
[WorkItem(179990, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/179990")]
[Fact]
public void SynthesizedDelegates()
{
var template =
@"class C
{
static void F(dynamic d, out object x, object y)
<N:0>{
<<CALL>>;
}</N:0>
}";
var source0 = MarkedSource(template.Replace("<<CALL>>", "d.F(out x, new { })"));
var source1 = MarkedSource(template.Replace("<<CALL>>", "d.F(out x, new { y })"));
var source2 = MarkedSource(template.Replace("<<CALL>>", "d.F(new { y }, out x)"));
var compilation0 = CreateCompilationWithMscorlib40(new[] { source0.Tree }, references: new[] { SystemCoreRef, CSharpRef }, 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 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 112 (0x70)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.s 17
IL_0033: ldnull
IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldc.i4.1
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0058: ldfld ""<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>> System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>> C.<>o__0.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.1
IL_0064: newobj ""<>f__AnonymousType0..ctor()""
IL_0069: callvirt ""void <>A{00000010}<System.Runtime.CompilerServices.CallSite, dynamic, object, <empty anonymous type>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref object, <empty anonymous type>)""
IL_006e: nop
IL_006f: ret
}");
var diff1 = compilation1.EmitDifference(
generation0,
ImmutableArray.Create(
SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)));
diff1.VerifyIL("C.F",
@"{
// Code size 113 (0x71)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.s 17
IL_0033: ldnull
IL_0034: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.2
IL_003c: ldc.i4.1
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0058: ldfld ""<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>> System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>> C.<>o__0#1.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.1
IL_0064: ldarg.2
IL_0065: newobj ""<>f__AnonymousType1<object>..ctor(object)""
IL_006a: callvirt ""void <>A{00000010}#1<System.Runtime.CompilerServices.CallSite, dynamic, object, <anonymous type: object y>>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, ref object, <anonymous type: object y>)""
IL_006f: nop
IL_0070: 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 113 (0x71)
.maxstack 9
IL_0000: nop
IL_0001: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0006: brfalse.s IL_000a
IL_0008: br.s IL_0053
IL_000a: ldc.i4 0x100
IL_000f: ldstr ""F""
IL_0014: ldnull
IL_0015: ldtoken ""C""
IL_001a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_001f: ldc.i4.3
IL_0020: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo""
IL_0025: dup
IL_0026: ldc.i4.0
IL_0027: ldc.i4.0
IL_0028: ldnull
IL_0029: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_002e: stelem.ref
IL_002f: dup
IL_0030: ldc.i4.1
IL_0031: ldc.i4.1
IL_0032: ldnull
IL_0033: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0038: stelem.ref
IL_0039: dup
IL_003a: ldc.i4.2
IL_003b: ldc.i4.s 17
IL_003d: ldnull
IL_003e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)""
IL_0043: stelem.ref
IL_0044: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)""
IL_0049: call ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>>.Create(System.Runtime.CompilerServices.CallSiteBinder)""
IL_004e: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0058: ldfld ""<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object> System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>>.Target""
IL_005d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>> C.<>o__0#2.<>p__0""
IL_0062: ldarg.0
IL_0063: ldarg.2
IL_0064: newobj ""<>f__AnonymousType1<object>..ctor(object)""
IL_0069: ldarg.1
IL_006a: callvirt ""void <>A{00000040}#2<System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, object>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic, <anonymous type: object y>, ref object)""
IL_006f: nop
IL_0070: ret
}");
}
[Fact]
public void TwoStructClosures()
{
var source0 = MarkedSource(@"
public class C
{
public void F()
<N:0>{</N:0>
int <N:1>x</N:1> = 0;
<N:2>{</N:2>
int <N:3>y</N:3> = 0;
// Captures two struct closures
<N:4>int L() => x + y;</N:4>
}
}
}");
var source1 = MarkedSource(@"
public class C
{
public void F()
<N:0>{</N:0>
int <N:1>x</N:1> = 0;
<N:2>{</N:2>
int <N:3>y</N:3> = 0;
// Captures two struct closures
<N:4>int L() => x + y + 1;</N:4>
}
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {x}",
"C.<>c__DisplayClass0_1: {y}",
"C: {<F>g__L|0_0, <>c__DisplayClass0_0, <>c__DisplayClass0_1}");
v0.VerifyIL("C.<F>g__L|0_0(ref C.<>c__DisplayClass0_0, ref C.<>c__DisplayClass0_1)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ret
}");
diff1.VerifyIL("C.<F>g__L|0_0(ref C.<>c__DisplayClass0_0, ref C.<>c__DisplayClass0_1)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ThisClosureAndStructClosure()
{
var source0 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
// This + struct closures
<N:3>int L() => x + y;</N:3>
L();
}
}");
var source1 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
// This + struct closures
<N:3>int L() => x + y + 1;</N:3>
L();
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass1_0: {<>4__this, y}",
"C: {<F>g__L|1_0, <>c__DisplayClass1_0}");
v0.VerifyIL("C.<F>g__L|1_0(ref C.<>c__DisplayClass1_0)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass1_0.y""
IL_000c: add
IL_000d: ret
}
");
diff1.VerifyIL("C.<F>g__L|1_0(ref C.<>c__DisplayClass1_0)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass1_0.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void ThisOnlyClosure()
{
var source0 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
// This-only closure
<N:2>int L() => x;</N:2>
L();
}
}");
var source1 = MarkedSource(@"
public class C
{
int <N:0>x</N:0> = 0;
public void F()
<N:1>{</N:1>
// This-only closure
<N:2>int L() => x + 1;</N:2>
L();
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<F>g__L|1_0}");
v0.VerifyIL("C.<F>g__L|1_0()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ret
}");
diff1.VerifyIL("C.<F>g__L|1_0()", @"
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.x""
IL_0006: ldc.i4.1
IL_0007: add
IL_0008: ret
}
");
CheckEncLogDefinitions(reader1,
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default));
}
[Fact]
public void LocatedInSameClosureEnvironment()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
Func<int> f = <N:1>() => x</N:1>;
// Located in same closure environment
<N:2>int L() => x;</N:2>
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
Func<int> f = <N:1>() => x</N:1>;
// Located in same closure environment
<N:2>int L() => x + 1;</N:2>
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_0: {x, <F>b__0, <F>g__L|1}",
"C: {<>c__DisplayClass0_0}");
v0.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1()", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1()", @"
{
// 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
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void SameClassEnvironmentWithStruct()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
// Same class environment, with struct env
<N:4>int L() => x + y;</N:4>
}
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
// Same class environment, with struct env
<N:4>int L() => x + y + 1;</N:4>
}
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1}",
"C.<>c__DisplayClass0_0: {x, <F>b__0, <F>g__L|1}",
"C.<>c__DisplayClass0_1: {y}");
v0.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1(ref C.<>c__DisplayClass0_1)", @"
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_0.<F>g__L|1(ref C.<>c__DisplayClass0_1)", @"
{
// Code size 16 (0x10)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_0006: ldarg.1
IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_000c: add
IL_000d: ldc.i4.1
IL_000e: add
IL_000f: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void CaptureStructAndThroughClassEnvChain()
{
var source0 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
<N:4>{</N:4>
Func<int> f2 = <N:5>() => x + y</N:5>;
int <N:6>z</N:6> = 0;
// Capture struct and through class env chain
<N:7>int L() => x + y + z;</N:7>
}
}
}
}");
var source1 = MarkedSource(@"
using System;
public class C
{
public void F(int x)
<N:0>{</N:0>
<N:1>{</N:1>
int <N:2>y</N:2> = 0;
Func<int> f = <N:3>() => x</N:3>;
<N:4>{</N:4>
Func<int> f2 = <N:5>() => x + y</N:5>;
int <N:6>z</N:6> = 0;
// Capture struct and through class env chain
<N:7>int L() => x + y + z + 1;</N:7>
}
}
}
}");
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)));
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
diff1.VerifySynthesizedMembers(
"C.<>c__DisplayClass0_2: {z}",
"C.<>c__DisplayClass0_0: {x, <F>b__0}",
"C: {<>c__DisplayClass0_0, <>c__DisplayClass0_1, <>c__DisplayClass0_2}",
"C.<>c__DisplayClass0_1: {y, CS$<>8__locals1, <F>b__1, <F>g__L|2}");
v0.VerifyIL("C.<>c__DisplayClass0_1.<F>g__L|2(ref C.<>c__DisplayClass0_2)", @"
{
// Code size 26 (0x1a)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_0006: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_000b: ldarg.0
IL_000c: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_0011: add
IL_0012: ldarg.1
IL_0013: ldfld ""int C.<>c__DisplayClass0_2.z""
IL_0018: add
IL_0019: ret
}");
diff1.VerifyIL("C.<>c__DisplayClass0_1.<F>g__L|2(ref C.<>c__DisplayClass0_2)", @"
{
// Code size 28 (0x1c)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldfld ""C.<>c__DisplayClass0_0 C.<>c__DisplayClass0_1.CS$<>8__locals1""
IL_0006: ldfld ""int C.<>c__DisplayClass0_0.x""
IL_000b: ldarg.0
IL_000c: ldfld ""int C.<>c__DisplayClass0_1.y""
IL_0011: add
IL_0012: ldarg.1
IL_0013: ldfld ""int C.<>c__DisplayClass0_2.z""
IL_0018: add
IL_0019: ldc.i4.1
IL_001a: add
IL_001b: ret
}
");
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
public void TopLevelStatement_Closure()
{
var source0 = MarkedSource(@"
<N:0>
using System;
Func<string> x = <N:1>() => args[0]</N:1>;
Console.WriteLine(x());
</N:0>
");
var source1 = MarkedSource(@"
<N:0>
using System;
Func<string> x = <N:1>() => args[1]</N:1>;
Console.WriteLine(x());
</N:0>
");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugExe);
var compilation1 = compilation0.WithSource(source1.Tree);
var v0 = CompileAndVerify(compilation0);
var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData);
var f0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$");
var f1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$");
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"Program.<>c__DisplayClass0_0: {args, <<Main>$>b__0}",
"Program: {<>c__DisplayClass0_0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
[Fact]
[WorkItem(55381, "https://github.com/dotnet/roslyn/issues/55381")]
public void HiddenMethodClosure()
{
var source0 = MarkedSource(@"
#line hidden
using System;
class C
{
public static void F(int arg)
<N:0>{</N:0>
Func<int> x = <N:1>() => arg</N:1>;
}
}
");
var source1 = MarkedSource(@"
#line hidden
using System;
class C
{
public static void F(int arg)
<N:0>{</N:0>
Func<int> x = <N:1>() => arg + 1</N:1>;
}
}
");
var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll);
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)));
// no new synthesized members generated (with #1 in names):
diff1.VerifySynthesizedMembers(
"C: {<>c__DisplayClass0_0}",
"C.<>c__DisplayClass0_0: {arg, <F>b__0}");
var md1 = diff1.GetMetadata();
var reader1 = md1.Reader;
// Method updates
CheckEncLogDefinitions(reader1,
Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default),
Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default),
Row(1, TableIndex.Param, EditAndContinueOperation.Default));
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.SymbolKeyWriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private enum SymbolKeyType
{
Alias = 'A',
BodyLevel = 'B',
ConstructedMethod = 'C',
NamedType = 'D',
ErrorType = 'E',
Field = 'F',
FunctionPointer = 'G',
DynamicType = 'I',
Method = 'M',
Namespace = 'N',
PointerType = 'O',
Parameter = 'P',
Property = 'Q',
ArrayType = 'R',
Assembly = 'S',
TupleType = 'T',
Module = 'U',
Event = 'V',
AnonymousType = 'W',
ReducedExtensionMethod = 'X',
TypeParameter = 'Y',
AnonymousFunctionOrDelegate = 'Z',
// Not to be confused with ArrayType. This indicates an array of elements in the stream.
Array = '%',
Reference = '#',
Null = '!',
TypeParameterOrdinal = '@',
}
private class SymbolKeyWriter : SymbolVisitor, IDisposable
{
private static readonly ObjectPool<SymbolKeyWriter> s_writerPool = SharedPools.Default<SymbolKeyWriter>();
private readonly Action<ISymbol> _writeSymbolKey;
private readonly Action<string?> _writeString;
private readonly Action<Location?> _writeLocation;
private readonly Action<bool> _writeBoolean;
private readonly Action<IParameterSymbol> _writeParameterType;
private readonly Action<IParameterSymbol> _writeRefKind;
private readonly Dictionary<ISymbol, int> _symbolToId = new();
private readonly StringBuilder _stringBuilder = new();
public CancellationToken CancellationToken { get; private set; }
private readonly List<IMethodSymbol> _methodSymbolStack = new();
internal int _nestingCount;
private int _nextId;
public SymbolKeyWriter()
{
_writeSymbolKey = WriteSymbolKey;
_writeString = WriteString;
_writeLocation = WriteLocation;
_writeBoolean = WriteBoolean;
_writeParameterType = p => WriteSymbolKey(p.Type);
_writeRefKind = p => WriteRefKind(p.RefKind);
}
public void Dispose()
{
_symbolToId.Clear();
_stringBuilder.Clear();
_methodSymbolStack.Clear();
CancellationToken = default;
_nestingCount = 0;
_nextId = 0;
// Place us back in the pool for future use.
s_writerPool.Free(this);
}
public static SymbolKeyWriter GetWriter(CancellationToken cancellationToken)
{
var visitor = s_writerPool.Allocate();
visitor.Initialize(cancellationToken);
return visitor;
}
private void Initialize(CancellationToken cancellationToken)
=> CancellationToken = cancellationToken;
public string CreateKey()
{
Debug.Assert(_nestingCount == 0);
return _stringBuilder.ToString();
}
private void StartKey()
{
_stringBuilder.Append('(');
_nestingCount++;
}
private void WriteType(SymbolKeyType type)
=> _stringBuilder.Append((char)type);
private void EndKey()
{
_nestingCount--;
_stringBuilder.Append(')');
}
internal void WriteSymbolKey(ISymbol? symbol)
{
WriteSpace();
if (symbol == null)
{
WriteType(SymbolKeyType.Null);
return;
}
int id;
var shouldWriteOrdinal = ShouldWriteTypeParameterOrdinal(symbol, out _);
if (!shouldWriteOrdinal)
{
if (_symbolToId.TryGetValue(symbol, out id))
{
StartKey();
WriteType(SymbolKeyType.Reference);
WriteInteger(id);
EndKey();
return;
}
}
id = _nextId;
_nextId++;
StartKey();
if (IsBodyLevelSymbol(symbol))
{
WriteType(SymbolKeyType.BodyLevel);
BodyLevelSymbolKey.Create(symbol, this);
}
else
{
symbol.Accept(this);
}
if (!shouldWriteOrdinal)
{
// Note: it is possible in some situations to hit the same symbol
// multiple times. For example, if you have:
//
// Goo<Z>(List<Z> list)
//
// If we start with the symbol for "list" then we'll see the following
// chain of symbols hit:
//
// List<Z>
// Z
// Goo<Z>(List<Z>)
// List<Z>
//
// The recursion is prevented because when we hit 'Goo' we mark that
// we're writing out a signature. And, in signature mode we only write
// out the ordinal for 'Z' without recursing. However, even though
// we prevent the recursion, we still hit List<Z> twice. After writing
// the innermost one out, we'll give it a reference ID. When we
// then hit the outermost one, we want to just reuse that one.
if (_symbolToId.TryGetValue(symbol, out var existingId))
{
// While we recursed, we already hit this symbol. Use its ID as our
// ID.
id = existingId;
}
else
{
// Haven't hit this symbol before, write out its fresh ID.
_symbolToId.Add(symbol, id);
}
}
// Now write out the ID for this symbol so that any future hits of it can
// write out a reference to it instead.
WriteInteger(id);
EndKey();
}
private void WriteSpace()
=> _stringBuilder.Append(' ');
internal void WriteFormatVersion(int version)
=> WriteIntegerRaw_DoNotCallDirectly(version);
internal void WriteInteger(int value)
{
WriteSpace();
WriteIntegerRaw_DoNotCallDirectly(value);
}
private void WriteIntegerRaw_DoNotCallDirectly(int value)
=> _stringBuilder.Append(value.ToString(CultureInfo.InvariantCulture));
internal void WriteBoolean(bool value)
=> WriteInteger(value ? 1 : 0);
internal void WriteString(string? value)
{
// Strings are quoted, with all embedded quotes being doubled to escape them.
WriteSpace();
if (value == null)
{
WriteType(SymbolKeyType.Null);
}
else
{
_stringBuilder.Append('"');
_stringBuilder.Append(value.Replace("\"", "\"\""));
_stringBuilder.Append('"');
}
}
internal void WriteLocation(Location? location)
{
WriteSpace();
if (location == null)
{
WriteType(SymbolKeyType.Null);
return;
}
Debug.Assert(location.Kind == LocationKind.None ||
location.Kind == LocationKind.SourceFile ||
location.Kind == LocationKind.MetadataFile);
WriteInteger((int)location.Kind);
if (location.IsInSource)
{
WriteString(location.SourceTree.FilePath);
WriteInteger(location.SourceSpan.Start);
WriteInteger(location.SourceSpan.Length);
}
else if (location.Kind == LocationKind.MetadataFile)
{
WriteSymbolKey(location.MetadataModule!.ContainingAssembly);
WriteString(location.MetadataModule.MetadataName);
}
}
/// <summary>
/// Writes out the provided symbols to the key. The array provided must not
/// be <c>default</c>.
/// </summary>
internal void WriteSymbolKeyArray<TSymbol>(ImmutableArray<TSymbol> symbols)
where TSymbol : ISymbol
{
WriteArray(symbols, _writeSymbolKey);
}
internal void WriteParameterTypesArray(ImmutableArray<IParameterSymbol> symbols)
=> WriteArray(symbols, _writeParameterType);
internal void WriteBooleanArray(ImmutableArray<bool> array)
=> WriteArray(array, _writeBoolean);
// annotating WriteStringArray and WriteLocationArray as allowing null elements
// then causes issues where we can't pass ImmutableArrays of non-null elements
#nullable disable
internal void WriteStringArray(ImmutableArray<string> strings)
=> WriteArray(strings, _writeString);
internal void WriteLocationArray(ImmutableArray<Location> array)
=> WriteArray(array, _writeLocation);
#nullable enable
internal void WriteRefKindArray(ImmutableArray<IParameterSymbol> values)
=> WriteArray(values, _writeRefKind);
private void WriteArray<T, U>(ImmutableArray<T> array, Action<U> writeValue)
where T : U
{
WriteSpace();
Debug.Assert(!array.IsDefault);
StartKey();
WriteType(SymbolKeyType.Array);
WriteInteger(array.Length);
foreach (var value in array)
{
writeValue(value);
}
EndKey();
}
internal void WriteRefKind(RefKind refKind) => WriteInteger((int)refKind);
public override void VisitAlias(IAliasSymbol aliasSymbol)
{
WriteType(SymbolKeyType.Alias);
AliasSymbolKey.Create(aliasSymbol, this);
}
public override void VisitArrayType(IArrayTypeSymbol arrayTypeSymbol)
{
WriteType(SymbolKeyType.ArrayType);
ArrayTypeSymbolKey.Create(arrayTypeSymbol, this);
}
public override void VisitAssembly(IAssemblySymbol assemblySymbol)
{
WriteType(SymbolKeyType.Assembly);
AssemblySymbolKey.Create(assemblySymbol, this);
}
public override void VisitDynamicType(IDynamicTypeSymbol dynamicTypeSymbol)
{
WriteType(SymbolKeyType.DynamicType);
DynamicTypeSymbolKey.Create(this);
}
public override void VisitField(IFieldSymbol fieldSymbol)
{
WriteType(SymbolKeyType.Field);
FieldSymbolKey.Create(fieldSymbol, this);
}
public override void VisitLabel(ILabelSymbol labelSymbol)
=> throw ExceptionUtilities.Unreachable;
public override void VisitLocal(ILocalSymbol localSymbol)
=> throw ExceptionUtilities.Unreachable;
public override void VisitRangeVariable(IRangeVariableSymbol rangeVariableSymbol)
=> throw ExceptionUtilities.Unreachable;
public override void VisitMethod(IMethodSymbol methodSymbol)
{
if (!methodSymbol.Equals(methodSymbol.ConstructedFrom))
{
WriteType(SymbolKeyType.ConstructedMethod);
ConstructedMethodSymbolKey.Create(methodSymbol, this);
}
else
{
switch (methodSymbol.MethodKind)
{
case MethodKind.ReducedExtension:
WriteType(SymbolKeyType.ReducedExtensionMethod);
ReducedExtensionMethodSymbolKey.Create(methodSymbol, this);
break;
case MethodKind.AnonymousFunction:
WriteType(SymbolKeyType.AnonymousFunctionOrDelegate);
AnonymousFunctionOrDelegateSymbolKey.Create(methodSymbol, this);
break;
case MethodKind.LocalFunction:
throw ExceptionUtilities.Unreachable;
default:
WriteType(SymbolKeyType.Method);
MethodSymbolKey.Create(methodSymbol, this);
break;
}
}
}
public override void VisitModule(IModuleSymbol moduleSymbol)
{
WriteType(SymbolKeyType.Module);
ModuleSymbolKey.Create(moduleSymbol, this);
}
public override void VisitNamedType(INamedTypeSymbol namedTypeSymbol)
{
if (namedTypeSymbol.TypeKind == TypeKind.Error)
{
WriteType(SymbolKeyType.ErrorType);
ErrorTypeSymbolKey.Create(namedTypeSymbol, this);
}
else if (namedTypeSymbol.IsTupleType && namedTypeSymbol.TupleUnderlyingType is INamedTypeSymbol underlyingType && underlyingType != namedTypeSymbol)
{
// A tuple is a named type with some added information
// We only need to store this extra information if there is some
// (ie. the current type differs from the underlying type, which has no element names)
WriteType(SymbolKeyType.TupleType);
TupleTypeSymbolKey.Create(namedTypeSymbol, this);
}
else if (namedTypeSymbol.IsAnonymousType)
{
if (namedTypeSymbol.IsAnonymousDelegateType())
{
WriteType(SymbolKeyType.AnonymousFunctionOrDelegate);
AnonymousFunctionOrDelegateSymbolKey.Create(namedTypeSymbol, this);
}
else
{
WriteType(SymbolKeyType.AnonymousType);
AnonymousTypeSymbolKey.Create(namedTypeSymbol, this);
}
}
else
{
WriteType(SymbolKeyType.NamedType);
NamedTypeSymbolKey.Create(namedTypeSymbol, this);
}
}
public override void VisitNamespace(INamespaceSymbol namespaceSymbol)
{
WriteType(SymbolKeyType.Namespace);
NamespaceSymbolKey.Create(namespaceSymbol, this);
}
public override void VisitParameter(IParameterSymbol parameterSymbol)
{
WriteType(SymbolKeyType.Parameter);
ParameterSymbolKey.Create(parameterSymbol, this);
}
public override void VisitPointerType(IPointerTypeSymbol pointerTypeSymbol)
{
WriteType(SymbolKeyType.PointerType);
PointerTypeSymbolKey.Create(pointerTypeSymbol, this);
}
public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol)
{
WriteType(SymbolKeyType.FunctionPointer);
FunctionPointerTypeSymbolKey.Create(symbol, this);
}
public override void VisitProperty(IPropertySymbol propertySymbol)
{
WriteType(SymbolKeyType.Property);
PropertySymbolKey.Create(propertySymbol, this);
}
public override void VisitEvent(IEventSymbol eventSymbol)
{
WriteType(SymbolKeyType.Event);
EventSymbolKey.Create(eventSymbol, this);
}
public override void VisitTypeParameter(ITypeParameterSymbol typeParameterSymbol)
{
// If it's a reference to a method type parameter, and we're currently writing
// out a signture, then only write out the ordinal of type parameter. This
// helps prevent recursion problems in cases like "Goo<T>(T t).
if (ShouldWriteTypeParameterOrdinal(typeParameterSymbol, out var methodIndex))
{
WriteType(SymbolKeyType.TypeParameterOrdinal);
TypeParameterOrdinalSymbolKey.Create(typeParameterSymbol, methodIndex, this);
}
else
{
WriteType(SymbolKeyType.TypeParameter);
TypeParameterSymbolKey.Create(typeParameterSymbol, this);
}
}
public bool ShouldWriteTypeParameterOrdinal(ISymbol symbol, out int methodIndex)
{
if (symbol.Kind == SymbolKind.TypeParameter)
{
var typeParameter = (ITypeParameterSymbol)symbol;
if (typeParameter.TypeParameterKind == TypeParameterKind.Method)
{
for (int i = 0, n = _methodSymbolStack.Count; i < n; i++)
{
var method = _methodSymbolStack[i];
if (typeParameter.DeclaringMethod!.Equals(method))
{
methodIndex = i;
return true;
}
}
}
}
methodIndex = -1;
return false;
}
public void PushMethod(IMethodSymbol method)
=> _methodSymbolStack.Add(method);
public void PopMethod(IMethodSymbol method)
{
Contract.ThrowIfTrue(_methodSymbolStack.Count == 0);
Contract.ThrowIfFalse(method.Equals(_methodSymbolStack[_methodSymbolStack.Count - 1]));
_methodSymbolStack.RemoveAt(_methodSymbolStack.Count - 1);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal partial struct SymbolKey
{
private enum SymbolKeyType
{
Alias = 'A',
BodyLevel = 'B',
ConstructedMethod = 'C',
NamedType = 'D',
ErrorType = 'E',
Field = 'F',
FunctionPointer = 'G',
DynamicType = 'I',
Method = 'M',
Namespace = 'N',
PointerType = 'O',
Parameter = 'P',
Property = 'Q',
ArrayType = 'R',
Assembly = 'S',
TupleType = 'T',
Module = 'U',
Event = 'V',
AnonymousType = 'W',
ReducedExtensionMethod = 'X',
TypeParameter = 'Y',
AnonymousFunctionOrDelegate = 'Z',
// Not to be confused with ArrayType. This indicates an array of elements in the stream.
Array = '%',
Reference = '#',
Null = '!',
TypeParameterOrdinal = '@',
}
private class SymbolKeyWriter : SymbolVisitor, IDisposable
{
private static readonly ObjectPool<SymbolKeyWriter> s_writerPool = SharedPools.Default<SymbolKeyWriter>();
private readonly Action<ISymbol> _writeSymbolKey;
private readonly Action<string?> _writeString;
private readonly Action<Location?> _writeLocation;
private readonly Action<bool> _writeBoolean;
private readonly Action<IParameterSymbol> _writeParameterType;
private readonly Action<IParameterSymbol> _writeRefKind;
private readonly Dictionary<ISymbol, int> _symbolToId = new();
private readonly StringBuilder _stringBuilder = new();
public CancellationToken CancellationToken { get; private set; }
private readonly List<IMethodSymbol> _methodSymbolStack = new();
internal int _nestingCount;
private int _nextId;
public SymbolKeyWriter()
{
_writeSymbolKey = WriteSymbolKey;
_writeString = WriteString;
_writeLocation = WriteLocation;
_writeBoolean = WriteBoolean;
_writeParameterType = p => WriteSymbolKey(p.Type);
_writeRefKind = p => WriteRefKind(p.RefKind);
}
public void Dispose()
{
_symbolToId.Clear();
_stringBuilder.Clear();
_methodSymbolStack.Clear();
CancellationToken = default;
_nestingCount = 0;
_nextId = 0;
// Place us back in the pool for future use.
s_writerPool.Free(this);
}
public static SymbolKeyWriter GetWriter(CancellationToken cancellationToken)
{
var visitor = s_writerPool.Allocate();
visitor.Initialize(cancellationToken);
return visitor;
}
private void Initialize(CancellationToken cancellationToken)
=> CancellationToken = cancellationToken;
public string CreateKey()
{
Debug.Assert(_nestingCount == 0);
return _stringBuilder.ToString();
}
private void StartKey()
{
_stringBuilder.Append('(');
_nestingCount++;
}
private void WriteType(SymbolKeyType type)
=> _stringBuilder.Append((char)type);
private void EndKey()
{
_nestingCount--;
_stringBuilder.Append(')');
}
internal void WriteSymbolKey(ISymbol? symbol)
{
WriteSpace();
if (symbol == null)
{
WriteType(SymbolKeyType.Null);
return;
}
int id;
var shouldWriteOrdinal = ShouldWriteTypeParameterOrdinal(symbol, out _);
if (!shouldWriteOrdinal)
{
if (_symbolToId.TryGetValue(symbol, out id))
{
StartKey();
WriteType(SymbolKeyType.Reference);
WriteInteger(id);
EndKey();
return;
}
}
id = _nextId;
_nextId++;
StartKey();
if (IsBodyLevelSymbol(symbol))
{
WriteType(SymbolKeyType.BodyLevel);
BodyLevelSymbolKey.Create(symbol, this);
}
else
{
symbol.Accept(this);
}
if (!shouldWriteOrdinal)
{
// Note: it is possible in some situations to hit the same symbol
// multiple times. For example, if you have:
//
// Goo<Z>(List<Z> list)
//
// If we start with the symbol for "list" then we'll see the following
// chain of symbols hit:
//
// List<Z>
// Z
// Goo<Z>(List<Z>)
// List<Z>
//
// The recursion is prevented because when we hit 'Goo' we mark that
// we're writing out a signature. And, in signature mode we only write
// out the ordinal for 'Z' without recursing. However, even though
// we prevent the recursion, we still hit List<Z> twice. After writing
// the innermost one out, we'll give it a reference ID. When we
// then hit the outermost one, we want to just reuse that one.
if (_symbolToId.TryGetValue(symbol, out var existingId))
{
// While we recursed, we already hit this symbol. Use its ID as our
// ID.
id = existingId;
}
else
{
// Haven't hit this symbol before, write out its fresh ID.
_symbolToId.Add(symbol, id);
}
}
// Now write out the ID for this symbol so that any future hits of it can
// write out a reference to it instead.
WriteInteger(id);
EndKey();
}
private void WriteSpace()
=> _stringBuilder.Append(' ');
internal void WriteFormatVersion(int version)
=> WriteIntegerRaw_DoNotCallDirectly(version);
internal void WriteInteger(int value)
{
WriteSpace();
WriteIntegerRaw_DoNotCallDirectly(value);
}
private void WriteIntegerRaw_DoNotCallDirectly(int value)
=> _stringBuilder.Append(value.ToString(CultureInfo.InvariantCulture));
internal void WriteBoolean(bool value)
=> WriteInteger(value ? 1 : 0);
internal void WriteString(string? value)
{
// Strings are quoted, with all embedded quotes being doubled to escape them.
WriteSpace();
if (value == null)
{
WriteType(SymbolKeyType.Null);
}
else
{
_stringBuilder.Append('"');
_stringBuilder.Append(value.Replace("\"", "\"\""));
_stringBuilder.Append('"');
}
}
internal void WriteLocation(Location? location)
{
WriteSpace();
if (location == null)
{
WriteType(SymbolKeyType.Null);
return;
}
Debug.Assert(location.Kind == LocationKind.None ||
location.Kind == LocationKind.SourceFile ||
location.Kind == LocationKind.MetadataFile);
WriteInteger((int)location.Kind);
if (location.IsInSource)
{
WriteString(location.SourceTree.FilePath);
WriteInteger(location.SourceSpan.Start);
WriteInteger(location.SourceSpan.Length);
}
else if (location.Kind == LocationKind.MetadataFile)
{
WriteSymbolKey(location.MetadataModule!.ContainingAssembly);
WriteString(location.MetadataModule.MetadataName);
}
}
/// <summary>
/// Writes out the provided symbols to the key. The array provided must not
/// be <c>default</c>.
/// </summary>
internal void WriteSymbolKeyArray<TSymbol>(ImmutableArray<TSymbol> symbols)
where TSymbol : ISymbol
{
WriteArray(symbols, _writeSymbolKey);
}
internal void WriteParameterTypesArray(ImmutableArray<IParameterSymbol> symbols)
=> WriteArray(symbols, _writeParameterType);
internal void WriteBooleanArray(ImmutableArray<bool> array)
=> WriteArray(array, _writeBoolean);
// annotating WriteStringArray and WriteLocationArray as allowing null elements
// then causes issues where we can't pass ImmutableArrays of non-null elements
#nullable disable
internal void WriteStringArray(ImmutableArray<string> strings)
=> WriteArray(strings, _writeString);
internal void WriteLocationArray(ImmutableArray<Location> array)
=> WriteArray(array, _writeLocation);
#nullable enable
internal void WriteRefKindArray(ImmutableArray<IParameterSymbol> values)
=> WriteArray(values, _writeRefKind);
private void WriteArray<T, U>(ImmutableArray<T> array, Action<U> writeValue)
where T : U
{
WriteSpace();
Debug.Assert(!array.IsDefault);
StartKey();
WriteType(SymbolKeyType.Array);
WriteInteger(array.Length);
foreach (var value in array)
{
writeValue(value);
}
EndKey();
}
internal void WriteRefKind(RefKind refKind) => WriteInteger((int)refKind);
public override void VisitAlias(IAliasSymbol aliasSymbol)
{
WriteType(SymbolKeyType.Alias);
AliasSymbolKey.Create(aliasSymbol, this);
}
public override void VisitArrayType(IArrayTypeSymbol arrayTypeSymbol)
{
WriteType(SymbolKeyType.ArrayType);
ArrayTypeSymbolKey.Create(arrayTypeSymbol, this);
}
public override void VisitAssembly(IAssemblySymbol assemblySymbol)
{
WriteType(SymbolKeyType.Assembly);
AssemblySymbolKey.Create(assemblySymbol, this);
}
public override void VisitDynamicType(IDynamicTypeSymbol dynamicTypeSymbol)
{
WriteType(SymbolKeyType.DynamicType);
DynamicTypeSymbolKey.Create(this);
}
public override void VisitField(IFieldSymbol fieldSymbol)
{
WriteType(SymbolKeyType.Field);
FieldSymbolKey.Create(fieldSymbol, this);
}
public override void VisitLabel(ILabelSymbol labelSymbol)
=> throw ExceptionUtilities.Unreachable;
public override void VisitLocal(ILocalSymbol localSymbol)
=> throw ExceptionUtilities.Unreachable;
public override void VisitRangeVariable(IRangeVariableSymbol rangeVariableSymbol)
=> throw ExceptionUtilities.Unreachable;
public override void VisitMethod(IMethodSymbol methodSymbol)
{
if (!methodSymbol.Equals(methodSymbol.ConstructedFrom))
{
WriteType(SymbolKeyType.ConstructedMethod);
ConstructedMethodSymbolKey.Create(methodSymbol, this);
}
else
{
switch (methodSymbol.MethodKind)
{
case MethodKind.ReducedExtension:
WriteType(SymbolKeyType.ReducedExtensionMethod);
ReducedExtensionMethodSymbolKey.Create(methodSymbol, this);
break;
case MethodKind.AnonymousFunction:
WriteType(SymbolKeyType.AnonymousFunctionOrDelegate);
AnonymousFunctionOrDelegateSymbolKey.Create(methodSymbol, this);
break;
case MethodKind.LocalFunction:
throw ExceptionUtilities.Unreachable;
default:
WriteType(SymbolKeyType.Method);
MethodSymbolKey.Create(methodSymbol, this);
break;
}
}
}
public override void VisitModule(IModuleSymbol moduleSymbol)
{
WriteType(SymbolKeyType.Module);
ModuleSymbolKey.Create(moduleSymbol, this);
}
public override void VisitNamedType(INamedTypeSymbol namedTypeSymbol)
{
if (namedTypeSymbol.TypeKind == TypeKind.Error)
{
WriteType(SymbolKeyType.ErrorType);
ErrorTypeSymbolKey.Create(namedTypeSymbol, this);
}
else if (namedTypeSymbol.IsTupleType && namedTypeSymbol.TupleUnderlyingType is INamedTypeSymbol underlyingType && underlyingType != namedTypeSymbol)
{
// A tuple is a named type with some added information
// We only need to store this extra information if there is some
// (ie. the current type differs from the underlying type, which has no element names)
WriteType(SymbolKeyType.TupleType);
TupleTypeSymbolKey.Create(namedTypeSymbol, this);
}
else if (namedTypeSymbol.IsAnonymousType)
{
if (namedTypeSymbol.IsAnonymousDelegateType())
{
WriteType(SymbolKeyType.AnonymousFunctionOrDelegate);
AnonymousFunctionOrDelegateSymbolKey.Create(namedTypeSymbol, this);
}
else
{
WriteType(SymbolKeyType.AnonymousType);
AnonymousTypeSymbolKey.Create(namedTypeSymbol, this);
}
}
else
{
WriteType(SymbolKeyType.NamedType);
NamedTypeSymbolKey.Create(namedTypeSymbol, this);
}
}
public override void VisitNamespace(INamespaceSymbol namespaceSymbol)
{
WriteType(SymbolKeyType.Namespace);
NamespaceSymbolKey.Create(namespaceSymbol, this);
}
public override void VisitParameter(IParameterSymbol parameterSymbol)
{
WriteType(SymbolKeyType.Parameter);
ParameterSymbolKey.Create(parameterSymbol, this);
}
public override void VisitPointerType(IPointerTypeSymbol pointerTypeSymbol)
{
WriteType(SymbolKeyType.PointerType);
PointerTypeSymbolKey.Create(pointerTypeSymbol, this);
}
public override void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol)
{
WriteType(SymbolKeyType.FunctionPointer);
FunctionPointerTypeSymbolKey.Create(symbol, this);
}
public override void VisitProperty(IPropertySymbol propertySymbol)
{
WriteType(SymbolKeyType.Property);
PropertySymbolKey.Create(propertySymbol, this);
}
public override void VisitEvent(IEventSymbol eventSymbol)
{
WriteType(SymbolKeyType.Event);
EventSymbolKey.Create(eventSymbol, this);
}
public override void VisitTypeParameter(ITypeParameterSymbol typeParameterSymbol)
{
// If it's a reference to a method type parameter, and we're currently writing
// out a signture, then only write out the ordinal of type parameter. This
// helps prevent recursion problems in cases like "Goo<T>(T t).
if (ShouldWriteTypeParameterOrdinal(typeParameterSymbol, out var methodIndex))
{
WriteType(SymbolKeyType.TypeParameterOrdinal);
TypeParameterOrdinalSymbolKey.Create(typeParameterSymbol, methodIndex, this);
}
else
{
WriteType(SymbolKeyType.TypeParameter);
TypeParameterSymbolKey.Create(typeParameterSymbol, this);
}
}
public bool ShouldWriteTypeParameterOrdinal(ISymbol symbol, out int methodIndex)
{
if (symbol.Kind == SymbolKind.TypeParameter)
{
var typeParameter = (ITypeParameterSymbol)symbol;
if (typeParameter.TypeParameterKind == TypeParameterKind.Method)
{
for (int i = 0, n = _methodSymbolStack.Count; i < n; i++)
{
var method = _methodSymbolStack[i];
if (typeParameter.DeclaringMethod!.Equals(method))
{
methodIndex = i;
return true;
}
}
}
}
methodIndex = -1;
return false;
}
public void PushMethod(IMethodSymbol method)
=> _methodSymbolStack.Add(method);
public void PopMethod(IMethodSymbol method)
{
Contract.ThrowIfTrue(_methodSymbolStack.Count == 0);
Contract.ThrowIfFalse(method.Equals(_methodSymbolStack[_methodSymbolStack.Count - 1]));
_methodSymbolStack.RemoveAt(_methodSymbolStack.Count - 1);
}
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/PersistentStorageOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Options;
namespace Microsoft.CodeAnalysis.Host
{
internal static class PersistentStorageOptions
{
public const string OptionName = "FeatureManager/Persistence";
public static readonly Option<bool> Enabled = new(OptionName, "Enabled", defaultValue: 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 Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Host
{
internal static class PersistentStorageOptions
{
public const string OptionName = "FeatureManager/Persistence";
public static readonly Option<bool> Enabled = new(OptionName, "Enabled", defaultValue: true);
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/CSharp/Portable/Symbols/Source/SourceMethodSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Base class to represent all source method-like symbols. This includes
/// things like ordinary methods and constructors, and functions
/// like lambdas and local functions.
/// </summary>
internal abstract class SourceMethodSymbol : MethodSymbol
{
/// <summary>
/// If there are no constraints, returns an empty immutable array. Otherwise, returns an immutable
/// array of types, indexed by the constrained type parameter in <see cref="MethodSymbol.TypeParameters"/>.
/// </summary>
public abstract ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes();
/// <summary>
/// If there are no constraints, returns an empty immutable array. Otherwise, returns an immutable
/// array of kinds, indexed by the constrained type parameter in <see cref="MethodSymbol.TypeParameters"/>.
/// </summary>
public abstract ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds();
protected static void ReportBadRefToken(TypeSyntax returnTypeSyntax, BindingDiagnosticBag diagnostics)
{
if (!returnTypeSyntax.HasErrors)
{
var refKeyword = returnTypeSyntax.GetFirstToken();
diagnostics.Add(ErrorCode.ERR_UnexpectedToken, refKeyword.GetLocation(), refKeyword.ToString());
}
}
protected bool AreContainingSymbolLocalsZeroed
{
get
{
if (ContainingSymbol is SourceMethodSymbol method)
{
return method.AreLocalsZeroed;
}
else if (ContainingType is SourceMemberContainerTypeSymbol type)
{
return type.AreLocalsZeroed;
}
else
{
// Sometimes a source method symbol can be contained in a non-source symbol.
// For example in EE. We aren't concerned with respecting SkipLocalsInit in such cases.
return true;
}
}
}
internal void ReportAsyncParameterErrors(BindingDiagnosticBag diagnostics, Location location)
{
foreach (var parameter in Parameters)
{
if (parameter.RefKind != RefKind.None)
{
diagnostics.Add(ErrorCode.ERR_BadAsyncArgType, getLocation(parameter, location));
}
else if (parameter.Type.IsUnsafe())
{
diagnostics.Add(ErrorCode.ERR_UnsafeAsyncArgType, getLocation(parameter, location));
}
else if (parameter.Type.IsRestrictedType())
{
diagnostics.Add(ErrorCode.ERR_BadSpecialByRefLocal, getLocation(parameter, location), parameter.Type);
}
}
static Location getLocation(ParameterSymbol parameter, Location location)
=> parameter.Locations.FirstOrDefault() ?? location;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// Base class to represent all source method-like symbols. This includes
/// things like ordinary methods and constructors, and functions
/// like lambdas and local functions.
/// </summary>
internal abstract class SourceMethodSymbol : MethodSymbol
{
/// <summary>
/// If there are no constraints, returns an empty immutable array. Otherwise, returns an immutable
/// array of types, indexed by the constrained type parameter in <see cref="MethodSymbol.TypeParameters"/>.
/// </summary>
public abstract ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes();
/// <summary>
/// If there are no constraints, returns an empty immutable array. Otherwise, returns an immutable
/// array of kinds, indexed by the constrained type parameter in <see cref="MethodSymbol.TypeParameters"/>.
/// </summary>
public abstract ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds();
protected static void ReportBadRefToken(TypeSyntax returnTypeSyntax, BindingDiagnosticBag diagnostics)
{
if (!returnTypeSyntax.HasErrors)
{
var refKeyword = returnTypeSyntax.GetFirstToken();
diagnostics.Add(ErrorCode.ERR_UnexpectedToken, refKeyword.GetLocation(), refKeyword.ToString());
}
}
protected bool AreContainingSymbolLocalsZeroed
{
get
{
if (ContainingSymbol is SourceMethodSymbol method)
{
return method.AreLocalsZeroed;
}
else if (ContainingType is SourceMemberContainerTypeSymbol type)
{
return type.AreLocalsZeroed;
}
else
{
// Sometimes a source method symbol can be contained in a non-source symbol.
// For example in EE. We aren't concerned with respecting SkipLocalsInit in such cases.
return true;
}
}
}
internal void ReportAsyncParameterErrors(BindingDiagnosticBag diagnostics, Location location)
{
foreach (var parameter in Parameters)
{
if (parameter.RefKind != RefKind.None)
{
diagnostics.Add(ErrorCode.ERR_BadAsyncArgType, getLocation(parameter, location));
}
else if (parameter.Type.IsUnsafe())
{
diagnostics.Add(ErrorCode.ERR_UnsafeAsyncArgType, getLocation(parameter, location));
}
else if (parameter.Type.IsRestrictedType())
{
diagnostics.Add(ErrorCode.ERR_BadSpecialByRefLocal, getLocation(parameter, location), parameter.Type);
}
}
static Location getLocation(ParameterSymbol parameter, Location location)
=> parameter.Locations.FirstOrDefault() ?? location;
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/CSharp/Test/Syntax/Parsing/DeclarationExpressionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing
{
[CompilerTrait(CompilerFeature.Tuples)]
public class DeclarationExpressionTests : ParsingTests
{
public DeclarationExpressionTests(ITestOutputHelper output) : base(output) { }
[Fact]
public void NullaboutOutDeclaration()
{
UsingStatement("M(out int? x);");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.NullableType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.QuestionToken);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void NullableTypeTest_01()
{
UsingStatement("if (e is int?) {}");
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.NullableType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.QuestionToken);
}
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NullableTypeTest_02()
{
UsingStatement("if (e is int ? true : false) {}");
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.ColonToken);
N(SyntaxKind.FalseLiteralExpression);
{
N(SyntaxKind.FalseKeyword);
}
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NullableTypeTest_03()
{
UsingStatement("if (e is int? x) {}",
// (1,16): error CS1003: Syntax error, ':' expected
// if (e is int? x) {}
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(1, 16),
// (1,16): error CS1525: Invalid expression term ')'
// if (e is int? x) {}
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(1, 16)
);
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "x");
}
M(SyntaxKind.ColonToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NullableTypeTest_04()
{
UsingStatement("if (e is int x ? true : false) {}");
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IsPatternExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.DeclarationPattern);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.ColonToken);
N(SyntaxKind.FalseLiteralExpression);
{
N(SyntaxKind.FalseKeyword);
}
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NullableTypeTest_05()
{
UsingStatement("ref object x = o1 is string ? ref o2 : ref o3;");
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.RefType);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.ObjectKeyword);
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "x");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o1");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o2");
}
}
N(SyntaxKind.ColonToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o3");
}
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void NullableTypeTest_06()
{
UsingStatement("ref object x = ref o1 is string ? ref o2 : ref o3;");
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.RefType);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.ObjectKeyword);
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "x");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o1");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o2");
}
}
N(SyntaxKind.ColonToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o3");
}
}
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void UnderscoreInOldForeach_01()
{
UsingStatement("foreach (int _ in e) {}");
N(SyntaxKind.ForEachStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "_");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void UnderscoreInOldForeach_02()
{
UsingStatement("foreach (var _ in e) {}");
N(SyntaxKind.ForEachStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.IdentifierToken, "_");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_01()
{
UsingStatement("foreach ((var x, var y) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_02()
{
UsingStatement("foreach ((int x, int y) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_03()
{
UsingStatement("foreach ((int x, int y) v in e) {}");
N(SyntaxKind.ForEachStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "y");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken, "v");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_04()
{
// there are semantic, not syntax errors
UsingStatement("foreach ((1, 2) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_05()
{
UsingStatement("foreach (var (x, y) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.ParenthesizedVariableDesignation);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_06()
{
UsingStatement("foreach ((int x, var (y, z)) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.ParenthesizedVariableDesignation);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "z");
}
N(SyntaxKind.CloseParenToken);
}
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_07()
{
// there are semantic but not syntax errors here.
UsingStatement("foreach ((var (x, y), z) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.ParenthesizedVariableDesignation);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
N(SyntaxKind.CloseParenToken);
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "z");
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_08()
{
UsingStatement("foreach (x in e) {}",
// (1,12): error CS0230: Type and identifier are both required in a foreach statement
// foreach (x in e) {}
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(1, 12)
);
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_09()
{
UsingStatement("foreach (_ in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "_");
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_10()
{
UsingStatement("foreach (a.b in e) {}",
// (1,14): error CS0230: Type and identifier are both required in a foreach statement
// foreach (a.b in e) {}
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(1, 14)
);
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void TupleOnTheLeft()
{
UsingStatement("(1, 2) = e;");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void OutTuple_01()
{
UsingStatement("M(out (1, 2));");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void OutTuple_02()
{
UsingStatement("M(out (x, y));");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void OutTuple_03()
{
UsingStatement("M(out (1, 2).Field);");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Field");
}
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void OutTuple_04()
{
// there are semantic but not syntax errors here.
UsingStatement("M(out (int x, int y));");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void OutTuple_05()
{
// there are semantic but not syntax errors here.
UsingStatement("M(out (var x, var y));");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void NamedTupleOnTheLeft()
{
UsingStatement("(x: 1, y: 2) = e;");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NameColon);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.ColonToken);
}
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NameColon);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "y");
}
N(SyntaxKind.ColonToken);
}
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void InvokeMethodNamedVar()
{
UsingStatement("var(1, 2) = e;");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing
{
[CompilerTrait(CompilerFeature.Tuples)]
public class DeclarationExpressionTests : ParsingTests
{
public DeclarationExpressionTests(ITestOutputHelper output) : base(output) { }
[Fact]
public void NullaboutOutDeclaration()
{
UsingStatement("M(out int? x);");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.NullableType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.QuestionToken);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void NullableTypeTest_01()
{
UsingStatement("if (e is int?) {}");
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.NullableType);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.QuestionToken);
}
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NullableTypeTest_02()
{
UsingStatement("if (e is int ? true : false) {}");
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.ColonToken);
N(SyntaxKind.FalseLiteralExpression);
{
N(SyntaxKind.FalseKeyword);
}
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NullableTypeTest_03()
{
UsingStatement("if (e is int? x) {}",
// (1,16): error CS1003: Syntax error, ':' expected
// if (e is int? x) {}
Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(":", ")").WithLocation(1, 16),
// (1,16): error CS1525: Invalid expression term ')'
// if (e is int? x) {}
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(1, 16)
);
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "x");
}
M(SyntaxKind.ColonToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NullableTypeTest_04()
{
UsingStatement("if (e is int x ? true : false) {}");
N(SyntaxKind.IfStatement);
{
N(SyntaxKind.IfKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IsPatternExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.DeclarationPattern);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
N(SyntaxKind.ColonToken);
N(SyntaxKind.FalseLiteralExpression);
{
N(SyntaxKind.FalseKeyword);
}
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NullableTypeTest_05()
{
UsingStatement("ref object x = o1 is string ? ref o2 : ref o3;");
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.RefType);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.ObjectKeyword);
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "x");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o1");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o2");
}
}
N(SyntaxKind.ColonToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o3");
}
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void NullableTypeTest_06()
{
UsingStatement("ref object x = ref o1 is string ? ref o2 : ref o3;");
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.RefType);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.ObjectKeyword);
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "x");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o1");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.StringKeyword);
}
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o2");
}
}
N(SyntaxKind.ColonToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "o3");
}
}
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void UnderscoreInOldForeach_01()
{
UsingStatement("foreach (int _ in e) {}");
N(SyntaxKind.ForEachStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "_");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void UnderscoreInOldForeach_02()
{
UsingStatement("foreach (var _ in e) {}");
N(SyntaxKind.ForEachStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.IdentifierToken, "_");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_01()
{
UsingStatement("foreach ((var x, var y) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_02()
{
UsingStatement("foreach ((int x, int y) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_03()
{
UsingStatement("foreach ((int x, int y) v in e) {}");
N(SyntaxKind.ForEachStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleType);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.TupleElement);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken, "y");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.IdentifierToken, "v");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_04()
{
// there are semantic, not syntax errors
UsingStatement("foreach ((1, 2) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_05()
{
UsingStatement("foreach (var (x, y) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.ParenthesizedVariableDesignation);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_06()
{
UsingStatement("foreach ((int x, var (y, z)) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.ParenthesizedVariableDesignation);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "z");
}
N(SyntaxKind.CloseParenToken);
}
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_07()
{
// there are semantic but not syntax errors here.
UsingStatement("foreach ((var (x, y), z) in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.ParenthesizedVariableDesignation);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
N(SyntaxKind.CloseParenToken);
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "z");
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_08()
{
UsingStatement("foreach (x in e) {}",
// (1,12): error CS0230: Type and identifier are both required in a foreach statement
// foreach (x in e) {}
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(1, 12)
);
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_09()
{
UsingStatement("foreach (_ in e) {}");
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "_");
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void NewForeach_10()
{
UsingStatement("foreach (a.b in e) {}",
// (1,14): error CS0230: Type and identifier are both required in a foreach statement
// foreach (a.b in e) {}
Diagnostic(ErrorCode.ERR_BadForeachDecl, "in").WithLocation(1, 14)
);
N(SyntaxKind.ForEachVariableStatement);
{
N(SyntaxKind.ForEachKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
public void TupleOnTheLeft()
{
UsingStatement("(1, 2) = e;");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void OutTuple_01()
{
UsingStatement("M(out (1, 2));");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void OutTuple_02()
{
UsingStatement("M(out (x, y));");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void OutTuple_03()
{
UsingStatement("M(out (1, 2).Field);");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Field");
}
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void OutTuple_04()
{
// there are semantic but not syntax errors here.
UsingStatement("M(out (int x, int y));");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void OutTuple_05()
{
// there are semantic but not syntax errors here.
UsingStatement("M(out (var x, var y));");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.OutKeyword);
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.DeclarationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.SingleVariableDesignation);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void NamedTupleOnTheLeft()
{
UsingStatement("(x: 1, y: 2) = e;");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.TupleExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NameColon);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.ColonToken);
}
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NameColon);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "y");
}
N(SyntaxKind.ColonToken);
}
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
[Fact]
public void InvokeMethodNamedVar()
{
UsingStatement("var(1, 2) = e;");
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken);
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
}
N(SyntaxKind.SemicolonToken);
}
EOF();
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Workspaces/Core/MSBuild/MSBuild/Constants/ItemNames.cs | // Licensed to the .NET Foundation under one or more 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.MSBuild
{
internal static class ItemNames
{
public const string AdditionalFiles = nameof(AdditionalFiles);
public const string Analyzer = nameof(Analyzer);
public const string Compile = nameof(Compile);
public const string CscCommandLineArgs = nameof(CscCommandLineArgs);
public const string DocFileItem = nameof(DocFileItem);
public const string EditorConfigFiles = nameof(EditorConfigFiles);
public const string Import = nameof(Import);
public const string ProjectReference = nameof(ProjectReference);
public const string Reference = nameof(Reference);
public const string ReferencePath = nameof(ReferencePath);
public const string VbcCommandLineArgs = nameof(VbcCommandLineArgs);
}
}
| // Licensed to the .NET Foundation under one or more 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.MSBuild
{
internal static class ItemNames
{
public const string AdditionalFiles = nameof(AdditionalFiles);
public const string Analyzer = nameof(Analyzer);
public const string Compile = nameof(Compile);
public const string CscCommandLineArgs = nameof(CscCommandLineArgs);
public const string DocFileItem = nameof(DocFileItem);
public const string EditorConfigFiles = nameof(EditorConfigFiles);
public const string Import = nameof(Import);
public const string ProjectReference = nameof(ProjectReference);
public const string Reference = nameof(Reference);
public const string ReferencePath = nameof(ReferencePath);
public const string VbcCommandLineArgs = nameof(VbcCommandLineArgs);
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/EditorFeatures/CSharpTest/EmbeddedLanguages/ValidateRegexStringTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EmbeddedLanguages
{
public class ValidateRegexStringTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public ValidateRegexStringTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpRegexDiagnosticAnalyzer(), null);
private static OptionsCollection OptionOn()
{
var optionsSet = new OptionsCollection(LanguageNames.CSharp);
optionsSet.Add(RegularExpressionsOptions.ReportInvalidRegexPatterns, true);
return optionsSet;
}
[Fact, Trait(Traits.Feature, Traits.Features.ValidateRegexString)]
public async Task TestWarning1()
{
await TestDiagnosticInfoAsync(@"
using System.Text.RegularExpressions;
class Program
{
void Main()
{
var r = new Regex(@""[|)|]"");
}
}",
options: OptionOn(),
diagnosticId: AbstractRegexDiagnosticAnalyzer.DiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning,
diagnosticMessage: string.Format(FeaturesResources.Regex_issue_0, FeaturesResources.Too_many_close_parens));
}
[Fact, Trait(Traits.Feature, Traits.Features.ValidateRegexString)]
public async Task TestWarning2()
{
await TestDiagnosticInfoAsync(@"
using System.Text.RegularExpressions;
class Program
{
void Main()
{
var r = new Regex(""[|\u0029|]"");
}
}",
options: OptionOn(),
diagnosticId: AbstractRegexDiagnosticAnalyzer.DiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning,
diagnosticMessage: string.Format(FeaturesResources.Regex_issue_0, FeaturesResources.Too_many_close_parens));
}
[Fact, Trait(Traits.Feature, Traits.Features.ValidateRegexString)]
public async Task TestWarningMissing1()
{
await TestDiagnosticMissingAsync(@"
using System.Text.RegularExpressions;
class Program
{
void Main()
{
var r = new Regex(@""[|\u0029|]"");
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.EmbeddedLanguages;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EmbeddedLanguages
{
public class ValidateRegexStringTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public ValidateRegexStringTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpRegexDiagnosticAnalyzer(), null);
private static OptionsCollection OptionOn()
{
var optionsSet = new OptionsCollection(LanguageNames.CSharp);
optionsSet.Add(RegularExpressionsOptions.ReportInvalidRegexPatterns, true);
return optionsSet;
}
[Fact, Trait(Traits.Feature, Traits.Features.ValidateRegexString)]
public async Task TestWarning1()
{
await TestDiagnosticInfoAsync(@"
using System.Text.RegularExpressions;
class Program
{
void Main()
{
var r = new Regex(@""[|)|]"");
}
}",
options: OptionOn(),
diagnosticId: AbstractRegexDiagnosticAnalyzer.DiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning,
diagnosticMessage: string.Format(FeaturesResources.Regex_issue_0, FeaturesResources.Too_many_close_parens));
}
[Fact, Trait(Traits.Feature, Traits.Features.ValidateRegexString)]
public async Task TestWarning2()
{
await TestDiagnosticInfoAsync(@"
using System.Text.RegularExpressions;
class Program
{
void Main()
{
var r = new Regex(""[|\u0029|]"");
}
}",
options: OptionOn(),
diagnosticId: AbstractRegexDiagnosticAnalyzer.DiagnosticId,
diagnosticSeverity: DiagnosticSeverity.Warning,
diagnosticMessage: string.Format(FeaturesResources.Regex_issue_0, FeaturesResources.Too_many_close_parens));
}
[Fact, Trait(Traits.Feature, Traits.Features.ValidateRegexString)]
public async Task TestWarningMissing1()
{
await TestDiagnosticMissingAsync(@"
using System.Text.RegularExpressions;
class Program
{
void Main()
{
var r = new Regex(@""[|\u0029|]"");
}
}");
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/StringKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Syntax;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class StringKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public StringKeywordRecommender()
: base(SyntaxKind.StringKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsTypeOfExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsDefaultExpressionContext(position, context.LeftToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_String;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Syntax;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class StringKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender
{
public StringKeywordRecommender()
: base(SyntaxKind.StringKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
var syntaxTree = context.SyntaxTree;
return
context.IsAnyExpressionContext ||
context.IsDefiniteCastTypeContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsObjectCreationTypeContext ||
(context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) ||
context.IsFunctionPointerTypeArgumentContext ||
context.IsIsOrAsTypeContext ||
context.IsLocalVariableDeclarationContext ||
context.IsParameterTypeContext ||
context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext ||
context.IsLocalFunctionDeclarationContext ||
context.IsImplicitOrExplicitOperatorTypeContext ||
context.IsTypeOfExpressionContext ||
context.IsCrefContext ||
syntaxTree.IsDefaultExpressionContext(position, context.LeftToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) ||
syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) ||
context.IsDelegateReturnTypeContext ||
syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) ||
context.IsPossibleTupleContext ||
context.IsMemberDeclarationContext(
validModifiers: SyntaxKindSet.AllMemberModifiers,
validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations,
canBePartial: false,
cancellationToken: cancellationToken);
}
protected override SpecialType SpecialType => SpecialType.System_String;
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/Core/Portable/InternalUtilities/BlobBuildingStream.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.IO;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
/// <summary>
/// A write-only memory stream backed by a <see cref="BlobBuilder"/>.
/// </summary>
internal sealed class BlobBuildingStream : Stream
{
private static readonly ObjectPool<BlobBuildingStream> s_pool = new ObjectPool<BlobBuildingStream>(() => new BlobBuildingStream());
private readonly BlobBuilder _builder;
/// <summary>
/// The chunk size to be used by the underlying BlobBuilder.
/// </summary>
/// <remarks>
/// The current single use case for this type is embedded sources in PDBs.
///
/// 32 KB is:
///
/// * Large enough to handle 99.6% all VB and C# files in Roslyn and CoreFX
/// without allocating additional chunks.
///
/// * Small enough to avoid the large object heap.
///
/// * Large enough to handle the files in the 0.4% case without allocating tons
/// of small chunks. Very large source files are often generated in build
/// (e.g. Syntax.xml.Generated.vb is 390KB compressed!) and those are actually
/// attractive candidates for embedding, so we don't want to discount the large
/// case too heavily.)
///
/// * We pool the outer BlobBuildingStream but only retain the first allocated chunk.
/// </remarks>
public const int ChunkSize = 32 * 1024;
public override bool CanWrite => true;
public override bool CanRead => false;
public override bool CanSeek => false;
public override long Length => _builder.Count;
public static BlobBuildingStream GetInstance()
{
return s_pool.Allocate();
}
private BlobBuildingStream()
{
// NOTE: We pool the wrapping BlobBuildingStream, but not individual chunks.
// The first chunk will be reused, but any further chunks will be freed when we're done building blob.
_builder = new BlobBuilder(ChunkSize);
}
public override void Write(byte[] buffer, int offset, int count)
{
_builder.WriteBytes(buffer, offset, count);
}
public override void WriteByte(byte value)
{
_builder.WriteByte(value);
}
public void WriteInt32(int value)
{
_builder.WriteInt32(value);
}
public Blob ReserveBytes(int byteCount)
{
return _builder.ReserveBytes(byteCount);
}
public ImmutableArray<byte> ToImmutableArray()
{
return _builder.ToImmutableArray();
}
public void Free()
{
_builder.Clear(); // frees all but first chunk
s_pool.Free(this); // return first chunk to pool
}
public override void Flush()
{
}
protected override void Dispose(bool disposing)
{
Debug.Assert(disposing);
Free();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
/// <summary>
/// A write-only memory stream backed by a <see cref="BlobBuilder"/>.
/// </summary>
internal sealed class BlobBuildingStream : Stream
{
private static readonly ObjectPool<BlobBuildingStream> s_pool = new ObjectPool<BlobBuildingStream>(() => new BlobBuildingStream());
private readonly BlobBuilder _builder;
/// <summary>
/// The chunk size to be used by the underlying BlobBuilder.
/// </summary>
/// <remarks>
/// The current single use case for this type is embedded sources in PDBs.
///
/// 32 KB is:
///
/// * Large enough to handle 99.6% all VB and C# files in Roslyn and CoreFX
/// without allocating additional chunks.
///
/// * Small enough to avoid the large object heap.
///
/// * Large enough to handle the files in the 0.4% case without allocating tons
/// of small chunks. Very large source files are often generated in build
/// (e.g. Syntax.xml.Generated.vb is 390KB compressed!) and those are actually
/// attractive candidates for embedding, so we don't want to discount the large
/// case too heavily.)
///
/// * We pool the outer BlobBuildingStream but only retain the first allocated chunk.
/// </remarks>
public const int ChunkSize = 32 * 1024;
public override bool CanWrite => true;
public override bool CanRead => false;
public override bool CanSeek => false;
public override long Length => _builder.Count;
public static BlobBuildingStream GetInstance()
{
return s_pool.Allocate();
}
private BlobBuildingStream()
{
// NOTE: We pool the wrapping BlobBuildingStream, but not individual chunks.
// The first chunk will be reused, but any further chunks will be freed when we're done building blob.
_builder = new BlobBuilder(ChunkSize);
}
public override void Write(byte[] buffer, int offset, int count)
{
_builder.WriteBytes(buffer, offset, count);
}
public override void WriteByte(byte value)
{
_builder.WriteByte(value);
}
public void WriteInt32(int value)
{
_builder.WriteInt32(value);
}
public Blob ReserveBytes(int byteCount)
{
return _builder.ReserveBytes(byteCount);
}
public ImmutableArray<byte> ToImmutableArray()
{
return _builder.ToImmutableArray();
}
public void Free()
{
_builder.Clear(); // frees all but first chunk
s_pool.Free(this); // return first chunk to pool
}
public override void Flush()
{
}
protected override void Dispose(bool disposing)
{
Debug.Assert(disposing);
Free();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Features/Core/Portable/PullMemberUp/Dialog/PullMemberUpWithDialogCodeAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog;
using Microsoft.CodeAnalysis.PullMemberUp;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp
{
internal abstract partial class AbstractPullMemberUpRefactoringProvider
{
private class PullMemberUpWithDialogCodeAction : CodeActionWithOptions
{
/// <summary>
/// Member which user initially selects. It will be selected initially when the dialog pops up.
/// </summary>
private readonly ISymbol _selectedMember;
private readonly Document _document;
private readonly IPullMemberUpOptionsService _service;
public override string Title => FeaturesResources.Pull_members_up_to_base_type;
public PullMemberUpWithDialogCodeAction(
Document document,
ISymbol selectedMember,
IPullMemberUpOptionsService service)
{
_document = document;
_selectedMember = selectedMember;
_service = service;
}
public override object GetOptions(CancellationToken cancellationToken)
{
var pullMemberUpOptionService = _service ?? _document.Project.Solution.Workspace.Services.GetRequiredService<IPullMemberUpOptionsService>();
return pullMemberUpOptionService.GetPullMemberUpOptions(_document, _selectedMember);
}
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken)
{
if (options is PullMembersUpOptions pullMemberUpOptions)
{
var changedSolution = await MembersPuller.PullMembersUpAsync(_document, pullMemberUpOptions, cancellationToken).ConfigureAwait(false);
return new[] { new ApplyChangesOperation(changedSolution) };
}
else
{
// If user click cancel button, options will be null and hit this branch
return SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog;
using Microsoft.CodeAnalysis.PullMemberUp;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp
{
internal abstract partial class AbstractPullMemberUpRefactoringProvider
{
private class PullMemberUpWithDialogCodeAction : CodeActionWithOptions
{
/// <summary>
/// Member which user initially selects. It will be selected initially when the dialog pops up.
/// </summary>
private readonly ISymbol _selectedMember;
private readonly Document _document;
private readonly IPullMemberUpOptionsService _service;
public override string Title => FeaturesResources.Pull_members_up_to_base_type;
public PullMemberUpWithDialogCodeAction(
Document document,
ISymbol selectedMember,
IPullMemberUpOptionsService service)
{
_document = document;
_selectedMember = selectedMember;
_service = service;
}
public override object GetOptions(CancellationToken cancellationToken)
{
var pullMemberUpOptionService = _service ?? _document.Project.Solution.Workspace.Services.GetRequiredService<IPullMemberUpOptionsService>();
return pullMemberUpOptionService.GetPullMemberUpOptions(_document, _selectedMember);
}
protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken)
{
if (options is PullMembersUpOptions pullMemberUpOptions)
{
var changedSolution = await MembersPuller.PullMembersUpAsync(_document, pullMemberUpOptions, cancellationToken).ConfigureAwait(false);
return new[] { new ApplyChangesOperation(changedSolution) };
}
else
{
// If user click cancel button, options will be null and hit this branch
return SpecializedCollections.EmptyEnumerable<CodeActionOperation>();
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Features/Core/Portable/ExtractClass/IExtractClassOptionsService.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Host;
namespace Microsoft.CodeAnalysis.ExtractClass
{
internal interface IExtractClassOptionsService : IWorkspaceService
{
Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalType, ISymbol? selectedMember);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Host;
namespace Microsoft.CodeAnalysis.ExtractClass
{
internal interface IExtractClassOptionsService : IWorkspaceService
{
Task<ExtractClassOptions?> GetExtractClassOptionsAsync(Document document, INamedTypeSymbol originalType, ISymbol? selectedMember);
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Workspaces/Core/Portable/CodeGeneration/SyntaxAnnotationExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal static class SyntaxAnnotationExtensions
{
public static TSymbol AddAnnotationToSymbol<TSymbol>(
this SyntaxAnnotation annotation,
TSymbol symbol)
where TSymbol : ISymbol
{
Contract.ThrowIfFalse(symbol is CodeGenerationSymbol);
var codeGenSymbol = (CodeGenerationSymbol)(object)symbol;
return (TSymbol)(object)codeGenSymbol.WithAdditionalAnnotations(annotation);
}
internal static SyntaxAnnotation[] CombineAnnotations(
SyntaxAnnotation[] originalAnnotations,
SyntaxAnnotation[] newAnnotations)
{
if (!originalAnnotations.IsNullOrEmpty())
{
// Make a new array (that includes the new annotations) and copy the original
// annotations into it.
var finalAnnotations = newAnnotations;
Array.Resize(ref finalAnnotations, originalAnnotations.Length + newAnnotations.Length);
Array.Copy(originalAnnotations, 0, finalAnnotations, newAnnotations.Length, originalAnnotations.Length);
return finalAnnotations;
}
return newAnnotations;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeGeneration
{
internal static class SyntaxAnnotationExtensions
{
public static TSymbol AddAnnotationToSymbol<TSymbol>(
this SyntaxAnnotation annotation,
TSymbol symbol)
where TSymbol : ISymbol
{
Contract.ThrowIfFalse(symbol is CodeGenerationSymbol);
var codeGenSymbol = (CodeGenerationSymbol)(object)symbol;
return (TSymbol)(object)codeGenSymbol.WithAdditionalAnnotations(annotation);
}
internal static SyntaxAnnotation[] CombineAnnotations(
SyntaxAnnotation[] originalAnnotations,
SyntaxAnnotation[] newAnnotations)
{
if (!originalAnnotations.IsNullOrEmpty())
{
// Make a new array (that includes the new annotations) and copy the original
// annotations into it.
var finalAnnotations = newAnnotations;
Array.Resize(ref finalAnnotations, originalAnnotations.Length + newAnnotations.Length);
Array.Copy(originalAnnotations, 0, finalAnnotations, newAnnotations.Length, originalAnnotations.Length);
return finalAnnotations;
}
return newAnnotations;
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpDeclarationComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal class CSharpDeclarationComparer : IComparer<SyntaxNode>
{
private static readonly Dictionary<SyntaxKind, int> s_kindPrecedenceMap = new(SyntaxFacts.EqualityComparer)
{
{ SyntaxKind.FieldDeclaration, 0 },
{ SyntaxKind.ConstructorDeclaration, 1 },
{ SyntaxKind.DestructorDeclaration, 2 },
{ SyntaxKind.IndexerDeclaration, 3 },
{ SyntaxKind.PropertyDeclaration, 4 },
{ SyntaxKind.EventFieldDeclaration, 5 },
{ SyntaxKind.EventDeclaration, 6 },
{ SyntaxKind.MethodDeclaration, 7 },
{ SyntaxKind.OperatorDeclaration, 8 },
{ SyntaxKind.ConversionOperatorDeclaration, 9 },
{ SyntaxKind.EnumDeclaration, 10 },
{ SyntaxKind.InterfaceDeclaration, 11 },
{ SyntaxKind.StructDeclaration, 12 },
{ SyntaxKind.ClassDeclaration, 13 },
{ SyntaxKind.RecordDeclaration, 14 },
{ SyntaxKind.RecordStructDeclaration, 15 },
{ SyntaxKind.DelegateDeclaration, 16 }
};
private static readonly Dictionary<SyntaxKind, int> s_operatorPrecedenceMap = new(SyntaxFacts.EqualityComparer)
{
{ SyntaxKind.PlusToken, 0 },
{ SyntaxKind.MinusToken, 1 },
{ SyntaxKind.ExclamationToken, 2 },
{ SyntaxKind.TildeToken, 3 },
{ SyntaxKind.PlusPlusToken, 4 },
{ SyntaxKind.MinusMinusToken, 5 },
{ SyntaxKind.AsteriskToken, 6 },
{ SyntaxKind.SlashToken, 7 },
{ SyntaxKind.PercentToken, 8 },
{ SyntaxKind.AmpersandToken, 9 },
{ SyntaxKind.BarToken, 10 },
{ SyntaxKind.CaretToken, 11 },
{ SyntaxKind.LessThanLessThanToken, 12 },
{ SyntaxKind.GreaterThanGreaterThanToken, 13 },
{ SyntaxKind.EqualsEqualsToken, 14 },
{ SyntaxKind.ExclamationEqualsToken, 15 },
{ SyntaxKind.LessThanToken, 16 },
{ SyntaxKind.GreaterThanToken, 17 },
{ SyntaxKind.LessThanEqualsToken, 18 },
{ SyntaxKind.GreaterThanEqualsToken, 19 },
{ SyntaxKind.TrueKeyword, 20 },
{ SyntaxKind.FalseKeyword, 21 },
};
public static readonly CSharpDeclarationComparer WithNamesInstance = new(includeName: true);
public static readonly CSharpDeclarationComparer WithoutNamesInstance = new(includeName: false);
private readonly bool _includeName;
private CSharpDeclarationComparer(bool includeName)
=> _includeName = includeName;
public int Compare(SyntaxNode x, SyntaxNode y)
{
if (x.Kind() != y.Kind())
{
if (!s_kindPrecedenceMap.TryGetValue(x.Kind(), out var xPrecedence) ||
!s_kindPrecedenceMap.TryGetValue(y.Kind(), out var yPrecedence))
{
// The containing declaration is malformed and contains a node kind we did not expect.
// Ignore comparisons with those unexpected nodes and sort them to the end of the declaration.
return 1;
}
return xPrecedence < yPrecedence ? -1 : 1;
}
switch (x.Kind())
{
case SyntaxKind.DelegateDeclaration:
return Compare((DelegateDeclarationSyntax)x, (DelegateDeclarationSyntax)y);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
return Compare((BaseFieldDeclarationSyntax)x, (BaseFieldDeclarationSyntax)y);
case SyntaxKind.ConstructorDeclaration:
return Compare((ConstructorDeclarationSyntax)x, (ConstructorDeclarationSyntax)y);
case SyntaxKind.DestructorDeclaration:
// All destructors are equal since there can only be one per named type
return 0;
case SyntaxKind.MethodDeclaration:
return Compare((MethodDeclarationSyntax)x, (MethodDeclarationSyntax)y);
case SyntaxKind.OperatorDeclaration:
return Compare((OperatorDeclarationSyntax)x, (OperatorDeclarationSyntax)y);
case SyntaxKind.EventDeclaration:
return Compare((EventDeclarationSyntax)x, (EventDeclarationSyntax)y);
case SyntaxKind.IndexerDeclaration:
return Compare((IndexerDeclarationSyntax)x, (IndexerDeclarationSyntax)y);
case SyntaxKind.PropertyDeclaration:
return Compare((PropertyDeclarationSyntax)x, (PropertyDeclarationSyntax)y);
case SyntaxKind.EnumDeclaration:
return Compare((EnumDeclarationSyntax)x, (EnumDeclarationSyntax)y);
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordStructDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
return Compare((BaseTypeDeclarationSyntax)x, (BaseTypeDeclarationSyntax)y);
case SyntaxKind.ConversionOperatorDeclaration:
return Compare((ConversionOperatorDeclarationSyntax)x, (ConversionOperatorDeclarationSyntax)y);
case SyntaxKind.IncompleteMember:
// Since these are incomplete members they are considered to be equal
return 0;
case SyntaxKind.GlobalStatement:
// for REPL, don't mess with order, just put new one at the end.
return 1;
default:
throw ExceptionUtilities.UnexpectedValue(x.Kind());
}
}
private int Compare(DelegateDeclarationSyntax x, DelegateDeclarationSyntax y)
{
if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out var result))
{
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private int Compare(BaseFieldDeclarationSyntax x, BaseFieldDeclarationSyntax y)
{
if (EqualConstness(x.Modifiers, y.Modifiers, out var result) &&
EqualStaticness(x.Modifiers, y.Modifiers, out result) &&
EqualReadOnlyness(x.Modifiers, y.Modifiers, out result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (_includeName)
{
EqualIdentifierName(
x.Declaration.Variables.FirstOrDefault().Identifier,
y.Declaration.Variables.FirstOrDefault().Identifier,
out result);
}
}
return result;
}
private static int Compare(ConstructorDeclarationSyntax x, ConstructorDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
EqualParameterCount(x.ParameterList, y.ParameterList, out result);
}
return result;
}
private int Compare(MethodDeclarationSyntax x, MethodDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (!_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private static int Compare(ConversionOperatorDeclarationSyntax x, ConversionOperatorDeclarationSyntax y)
{
if (x.ImplicitOrExplicitKeyword.Kind() != y.ImplicitOrExplicitKeyword.Kind())
{
return x.ImplicitOrExplicitKeyword.Kind() == SyntaxKind.ImplicitKeyword ? -1 : 1;
}
EqualParameterCount(x.ParameterList, y.ParameterList, out var result);
return result;
}
private static int Compare(OperatorDeclarationSyntax x, OperatorDeclarationSyntax y)
{
if (EqualOperatorPrecedence(x.OperatorToken, y.OperatorToken, out var result))
{
EqualParameterCount(x.ParameterList, y.ParameterList, out result);
}
return result;
}
private int Compare(EventDeclarationSyntax x, EventDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private static int Compare(IndexerDeclarationSyntax x, IndexerDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
EqualParameterCount(x.ParameterList, y.ParameterList, out result);
}
return result;
}
private int Compare(PropertyDeclarationSyntax x, PropertyDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private int Compare(EnumDeclarationSyntax x, EnumDeclarationSyntax y)
{
if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out var result))
{
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private int Compare(BaseTypeDeclarationSyntax x, BaseTypeDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private static bool NeitherNull(object x, object y, out int comparisonResult)
{
if (x == null && y == null)
{
comparisonResult = 0;
return false;
}
else if (x == null)
{
// x == null && y != null
comparisonResult = -1;
return false;
}
else if (y == null)
{
// x != null && y == null
comparisonResult = 1;
return false;
}
else
{
// x != null && y != null
comparisonResult = 0;
return true;
}
}
private static bool ContainsToken(SyntaxTokenList list, SyntaxKind kind)
=> list.Contains(token => token.Kind() == kind);
private enum Accessibility
{
Public,
Protected,
ProtectedInternal,
Internal,
PrivateProtected,
Private
}
private static int GetAccessibilityPrecedence(SyntaxTokenList modifiers, SyntaxNode parent)
{
if (ContainsToken(modifiers, SyntaxKind.PublicKeyword))
{
return (int)Accessibility.Public;
}
else if (ContainsToken(modifiers, SyntaxKind.ProtectedKeyword))
{
if (ContainsToken(modifiers, SyntaxKind.InternalKeyword))
{
return (int)Accessibility.ProtectedInternal;
}
if (ContainsToken(modifiers, SyntaxKind.PrivateKeyword))
{
return (int)Accessibility.PrivateProtected;
}
return (int)Accessibility.Protected;
}
else if (ContainsToken(modifiers, SyntaxKind.InternalKeyword))
{
return (int)Accessibility.Internal;
}
else if (ContainsToken(modifiers, SyntaxKind.PrivateKeyword))
{
return (int)Accessibility.Private;
}
// Determine default accessibility: This declaration is internal if we traverse up
// the syntax tree and don't find a containing named type.
for (var node = parent; node != null; node = node.Parent)
{
if (node.Kind() == SyntaxKind.InterfaceDeclaration)
{
// All interface members are public
return (int)Accessibility.Public;
}
else if (node.Kind() is SyntaxKind.StructDeclaration or SyntaxKind.ClassDeclaration or SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration)
{
// Members and nested types default to private
return (int)Accessibility.Private;
}
}
return (int)Accessibility.Internal;
}
private static bool BothHaveModifier(SyntaxTokenList x, SyntaxTokenList y, SyntaxKind modifierKind, out int comparisonResult)
{
var xHasModifier = ContainsToken(x, modifierKind);
var yHasModifier = ContainsToken(y, modifierKind);
if (xHasModifier == yHasModifier)
{
comparisonResult = 0;
return true;
}
comparisonResult = xHasModifier ? -1 : 1;
return false;
}
private static bool EqualStaticness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult)
=> BothHaveModifier(x, y, SyntaxKind.StaticKeyword, out comparisonResult);
private static bool EqualConstness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult)
=> BothHaveModifier(x, y, SyntaxKind.ConstKeyword, out comparisonResult);
private static bool EqualReadOnlyness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult)
=> BothHaveModifier(x, y, SyntaxKind.ReadOnlyKeyword, out comparisonResult);
private static bool EqualAccessibility(SyntaxNode x, SyntaxTokenList xModifiers, SyntaxNode y, SyntaxTokenList yModifiers, out int comparisonResult)
{
var xAccessibility = GetAccessibilityPrecedence(xModifiers, x.Parent ?? y.Parent);
var yAccessibility = GetAccessibilityPrecedence(yModifiers, y.Parent ?? x.Parent);
comparisonResult = xAccessibility - yAccessibility;
return comparisonResult == 0;
}
private static bool EqualIdentifierName(SyntaxToken x, SyntaxToken y, out int comparisonResult)
{
if (NeitherNull(x, y, out comparisonResult))
{
comparisonResult = string.Compare(x.ValueText, y.ValueText, StringComparison.OrdinalIgnoreCase);
}
return comparisonResult == 0;
}
private static bool EqualOperatorPrecedence(SyntaxToken x, SyntaxToken y, out int comparisonResult)
{
if (NeitherNull(x, y, out comparisonResult))
{
s_operatorPrecedenceMap.TryGetValue(x.Kind(), out var xPrecedence);
s_operatorPrecedenceMap.TryGetValue(y.Kind(), out var yPrecedence);
comparisonResult = xPrecedence - yPrecedence;
}
return comparisonResult == 0;
}
private static bool EqualParameterCount(BaseParameterListSyntax x, BaseParameterListSyntax y, out int comparisonResult)
{
var xParameterCount = x.Parameters.Count;
var yParameterCount = y.Parameters.Count;
comparisonResult = xParameterCount - yParameterCount;
return comparisonResult == 0;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal class CSharpDeclarationComparer : IComparer<SyntaxNode>
{
private static readonly Dictionary<SyntaxKind, int> s_kindPrecedenceMap = new(SyntaxFacts.EqualityComparer)
{
{ SyntaxKind.FieldDeclaration, 0 },
{ SyntaxKind.ConstructorDeclaration, 1 },
{ SyntaxKind.DestructorDeclaration, 2 },
{ SyntaxKind.IndexerDeclaration, 3 },
{ SyntaxKind.PropertyDeclaration, 4 },
{ SyntaxKind.EventFieldDeclaration, 5 },
{ SyntaxKind.EventDeclaration, 6 },
{ SyntaxKind.MethodDeclaration, 7 },
{ SyntaxKind.OperatorDeclaration, 8 },
{ SyntaxKind.ConversionOperatorDeclaration, 9 },
{ SyntaxKind.EnumDeclaration, 10 },
{ SyntaxKind.InterfaceDeclaration, 11 },
{ SyntaxKind.StructDeclaration, 12 },
{ SyntaxKind.ClassDeclaration, 13 },
{ SyntaxKind.RecordDeclaration, 14 },
{ SyntaxKind.RecordStructDeclaration, 15 },
{ SyntaxKind.DelegateDeclaration, 16 }
};
private static readonly Dictionary<SyntaxKind, int> s_operatorPrecedenceMap = new(SyntaxFacts.EqualityComparer)
{
{ SyntaxKind.PlusToken, 0 },
{ SyntaxKind.MinusToken, 1 },
{ SyntaxKind.ExclamationToken, 2 },
{ SyntaxKind.TildeToken, 3 },
{ SyntaxKind.PlusPlusToken, 4 },
{ SyntaxKind.MinusMinusToken, 5 },
{ SyntaxKind.AsteriskToken, 6 },
{ SyntaxKind.SlashToken, 7 },
{ SyntaxKind.PercentToken, 8 },
{ SyntaxKind.AmpersandToken, 9 },
{ SyntaxKind.BarToken, 10 },
{ SyntaxKind.CaretToken, 11 },
{ SyntaxKind.LessThanLessThanToken, 12 },
{ SyntaxKind.GreaterThanGreaterThanToken, 13 },
{ SyntaxKind.EqualsEqualsToken, 14 },
{ SyntaxKind.ExclamationEqualsToken, 15 },
{ SyntaxKind.LessThanToken, 16 },
{ SyntaxKind.GreaterThanToken, 17 },
{ SyntaxKind.LessThanEqualsToken, 18 },
{ SyntaxKind.GreaterThanEqualsToken, 19 },
{ SyntaxKind.TrueKeyword, 20 },
{ SyntaxKind.FalseKeyword, 21 },
};
public static readonly CSharpDeclarationComparer WithNamesInstance = new(includeName: true);
public static readonly CSharpDeclarationComparer WithoutNamesInstance = new(includeName: false);
private readonly bool _includeName;
private CSharpDeclarationComparer(bool includeName)
=> _includeName = includeName;
public int Compare(SyntaxNode x, SyntaxNode y)
{
if (x.Kind() != y.Kind())
{
if (!s_kindPrecedenceMap.TryGetValue(x.Kind(), out var xPrecedence) ||
!s_kindPrecedenceMap.TryGetValue(y.Kind(), out var yPrecedence))
{
// The containing declaration is malformed and contains a node kind we did not expect.
// Ignore comparisons with those unexpected nodes and sort them to the end of the declaration.
return 1;
}
return xPrecedence < yPrecedence ? -1 : 1;
}
switch (x.Kind())
{
case SyntaxKind.DelegateDeclaration:
return Compare((DelegateDeclarationSyntax)x, (DelegateDeclarationSyntax)y);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
return Compare((BaseFieldDeclarationSyntax)x, (BaseFieldDeclarationSyntax)y);
case SyntaxKind.ConstructorDeclaration:
return Compare((ConstructorDeclarationSyntax)x, (ConstructorDeclarationSyntax)y);
case SyntaxKind.DestructorDeclaration:
// All destructors are equal since there can only be one per named type
return 0;
case SyntaxKind.MethodDeclaration:
return Compare((MethodDeclarationSyntax)x, (MethodDeclarationSyntax)y);
case SyntaxKind.OperatorDeclaration:
return Compare((OperatorDeclarationSyntax)x, (OperatorDeclarationSyntax)y);
case SyntaxKind.EventDeclaration:
return Compare((EventDeclarationSyntax)x, (EventDeclarationSyntax)y);
case SyntaxKind.IndexerDeclaration:
return Compare((IndexerDeclarationSyntax)x, (IndexerDeclarationSyntax)y);
case SyntaxKind.PropertyDeclaration:
return Compare((PropertyDeclarationSyntax)x, (PropertyDeclarationSyntax)y);
case SyntaxKind.EnumDeclaration:
return Compare((EnumDeclarationSyntax)x, (EnumDeclarationSyntax)y);
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
case SyntaxKind.RecordStructDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.RecordDeclaration:
return Compare((BaseTypeDeclarationSyntax)x, (BaseTypeDeclarationSyntax)y);
case SyntaxKind.ConversionOperatorDeclaration:
return Compare((ConversionOperatorDeclarationSyntax)x, (ConversionOperatorDeclarationSyntax)y);
case SyntaxKind.IncompleteMember:
// Since these are incomplete members they are considered to be equal
return 0;
case SyntaxKind.GlobalStatement:
// for REPL, don't mess with order, just put new one at the end.
return 1;
default:
throw ExceptionUtilities.UnexpectedValue(x.Kind());
}
}
private int Compare(DelegateDeclarationSyntax x, DelegateDeclarationSyntax y)
{
if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out var result))
{
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private int Compare(BaseFieldDeclarationSyntax x, BaseFieldDeclarationSyntax y)
{
if (EqualConstness(x.Modifiers, y.Modifiers, out var result) &&
EqualStaticness(x.Modifiers, y.Modifiers, out result) &&
EqualReadOnlyness(x.Modifiers, y.Modifiers, out result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (_includeName)
{
EqualIdentifierName(
x.Declaration.Variables.FirstOrDefault().Identifier,
y.Declaration.Variables.FirstOrDefault().Identifier,
out result);
}
}
return result;
}
private static int Compare(ConstructorDeclarationSyntax x, ConstructorDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
EqualParameterCount(x.ParameterList, y.ParameterList, out result);
}
return result;
}
private int Compare(MethodDeclarationSyntax x, MethodDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (!_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private static int Compare(ConversionOperatorDeclarationSyntax x, ConversionOperatorDeclarationSyntax y)
{
if (x.ImplicitOrExplicitKeyword.Kind() != y.ImplicitOrExplicitKeyword.Kind())
{
return x.ImplicitOrExplicitKeyword.Kind() == SyntaxKind.ImplicitKeyword ? -1 : 1;
}
EqualParameterCount(x.ParameterList, y.ParameterList, out var result);
return result;
}
private static int Compare(OperatorDeclarationSyntax x, OperatorDeclarationSyntax y)
{
if (EqualOperatorPrecedence(x.OperatorToken, y.OperatorToken, out var result))
{
EqualParameterCount(x.ParameterList, y.ParameterList, out result);
}
return result;
}
private int Compare(EventDeclarationSyntax x, EventDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private static int Compare(IndexerDeclarationSyntax x, IndexerDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
EqualParameterCount(x.ParameterList, y.ParameterList, out result);
}
return result;
}
private int Compare(PropertyDeclarationSyntax x, PropertyDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private int Compare(EnumDeclarationSyntax x, EnumDeclarationSyntax y)
{
if (EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out var result))
{
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private int Compare(BaseTypeDeclarationSyntax x, BaseTypeDeclarationSyntax y)
{
if (EqualStaticness(x.Modifiers, y.Modifiers, out var result) &&
EqualAccessibility(x, x.Modifiers, y, y.Modifiers, out result))
{
if (_includeName)
{
EqualIdentifierName(x.Identifier, y.Identifier, out result);
}
}
return result;
}
private static bool NeitherNull(object x, object y, out int comparisonResult)
{
if (x == null && y == null)
{
comparisonResult = 0;
return false;
}
else if (x == null)
{
// x == null && y != null
comparisonResult = -1;
return false;
}
else if (y == null)
{
// x != null && y == null
comparisonResult = 1;
return false;
}
else
{
// x != null && y != null
comparisonResult = 0;
return true;
}
}
private static bool ContainsToken(SyntaxTokenList list, SyntaxKind kind)
=> list.Contains(token => token.Kind() == kind);
private enum Accessibility
{
Public,
Protected,
ProtectedInternal,
Internal,
PrivateProtected,
Private
}
private static int GetAccessibilityPrecedence(SyntaxTokenList modifiers, SyntaxNode parent)
{
if (ContainsToken(modifiers, SyntaxKind.PublicKeyword))
{
return (int)Accessibility.Public;
}
else if (ContainsToken(modifiers, SyntaxKind.ProtectedKeyword))
{
if (ContainsToken(modifiers, SyntaxKind.InternalKeyword))
{
return (int)Accessibility.ProtectedInternal;
}
if (ContainsToken(modifiers, SyntaxKind.PrivateKeyword))
{
return (int)Accessibility.PrivateProtected;
}
return (int)Accessibility.Protected;
}
else if (ContainsToken(modifiers, SyntaxKind.InternalKeyword))
{
return (int)Accessibility.Internal;
}
else if (ContainsToken(modifiers, SyntaxKind.PrivateKeyword))
{
return (int)Accessibility.Private;
}
// Determine default accessibility: This declaration is internal if we traverse up
// the syntax tree and don't find a containing named type.
for (var node = parent; node != null; node = node.Parent)
{
if (node.Kind() == SyntaxKind.InterfaceDeclaration)
{
// All interface members are public
return (int)Accessibility.Public;
}
else if (node.Kind() is SyntaxKind.StructDeclaration or SyntaxKind.ClassDeclaration or SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration)
{
// Members and nested types default to private
return (int)Accessibility.Private;
}
}
return (int)Accessibility.Internal;
}
private static bool BothHaveModifier(SyntaxTokenList x, SyntaxTokenList y, SyntaxKind modifierKind, out int comparisonResult)
{
var xHasModifier = ContainsToken(x, modifierKind);
var yHasModifier = ContainsToken(y, modifierKind);
if (xHasModifier == yHasModifier)
{
comparisonResult = 0;
return true;
}
comparisonResult = xHasModifier ? -1 : 1;
return false;
}
private static bool EqualStaticness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult)
=> BothHaveModifier(x, y, SyntaxKind.StaticKeyword, out comparisonResult);
private static bool EqualConstness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult)
=> BothHaveModifier(x, y, SyntaxKind.ConstKeyword, out comparisonResult);
private static bool EqualReadOnlyness(SyntaxTokenList x, SyntaxTokenList y, out int comparisonResult)
=> BothHaveModifier(x, y, SyntaxKind.ReadOnlyKeyword, out comparisonResult);
private static bool EqualAccessibility(SyntaxNode x, SyntaxTokenList xModifiers, SyntaxNode y, SyntaxTokenList yModifiers, out int comparisonResult)
{
var xAccessibility = GetAccessibilityPrecedence(xModifiers, x.Parent ?? y.Parent);
var yAccessibility = GetAccessibilityPrecedence(yModifiers, y.Parent ?? x.Parent);
comparisonResult = xAccessibility - yAccessibility;
return comparisonResult == 0;
}
private static bool EqualIdentifierName(SyntaxToken x, SyntaxToken y, out int comparisonResult)
{
if (NeitherNull(x, y, out comparisonResult))
{
comparisonResult = string.Compare(x.ValueText, y.ValueText, StringComparison.OrdinalIgnoreCase);
}
return comparisonResult == 0;
}
private static bool EqualOperatorPrecedence(SyntaxToken x, SyntaxToken y, out int comparisonResult)
{
if (NeitherNull(x, y, out comparisonResult))
{
s_operatorPrecedenceMap.TryGetValue(x.Kind(), out var xPrecedence);
s_operatorPrecedenceMap.TryGetValue(y.Kind(), out var yPrecedence);
comparisonResult = xPrecedence - yPrecedence;
}
return comparisonResult == 0;
}
private static bool EqualParameterCount(BaseParameterListSyntax x, BaseParameterListSyntax y, out int comparisonResult)
{
var xParameterCount = x.Parameters.Count;
var yParameterCount = y.Parameters.Count;
comparisonResult = xParameterCount - yParameterCount;
return comparisonResult == 0;
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Workspaces/MSBuildTest/Resources/ProjectFiles/VisualBasic/VisualBasicProject_3_5.vbproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == ''">Debug</Configuration>
<Platform Condition="'$(Platform)' == ''">AnyCPU</Platform>
<PlatformTarget>AnyCPU</PlatformTarget>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AC25ECDA-DE94-4FCF-A688-EB3A2BE3670C}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>VisualBasicProject</RootNamespace>
<AssemblyName>VisualBasicProject</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
<RemoveIntegerChecks>true</RemoveIntegerChecks>
<AssemblyOriginatorKeyFile>snKey.snk</AssemblyOriginatorKeyFile>
<DefineConstants>FURBY</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<NoWarn>$(NoWarn);42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Import Include="Microsoft.VisualBasic" />
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="My Project\Application.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Application.myapp</DependentUpon>
</Compile>
<Compile Include="My Project\AssemblyInfo.vb" />
<Compile Include="My Project\Resources.Designer.vb">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="My Project\Settings.Designer.vb">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<Compile Include="VisualBasicClass.vb" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="My Project\Resources.resx">
<Generator>VbMyResourcesResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.vb</LastGenOutput>
<CustomToolNamespace>My.Resources</CustomToolNamespace>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="My Project\Application.myapp">
<Generator>MyApplicationCodeGenerator</Generator>
<LastGenOutput>Application.Designer.vb</LastGenOutput>
</None>
<None Include="My Project\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<CustomToolNamespace>My</CustomToolNamespace>
<LastGenOutput>Settings.Designer.vb</LastGenOutput>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project> | -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/TypeKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 TypeKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public TypeKeywordRecommender()
: base(SyntaxKind.TypeKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> context.IsTypeAttributeContext(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.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class TypeKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public TypeKeywordRecommender()
: base(SyntaxKind.TypeKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
=> context.IsTypeAttributeContext(cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/Core/Portable/Syntax/SyntaxList.WithTwoChildren.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Syntax
{
internal partial class SyntaxList
{
internal class WithTwoChildren : SyntaxList
{
private SyntaxNode? _child0;
private SyntaxNode? _child1;
internal WithTwoChildren(InternalSyntax.SyntaxList green, SyntaxNode? parent, int position)
: base(green, parent, position)
{
}
internal override SyntaxNode? GetNodeSlot(int index)
{
switch (index)
{
case 0:
return this.GetRedElement(ref _child0, 0);
case 1:
return this.GetRedElementIfNotToken(ref _child1);
default:
return null;
}
}
internal override SyntaxNode? GetCachedSlot(int index)
{
switch (index)
{
case 0:
return _child0;
case 1:
return _child1;
default:
return null;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Syntax
{
internal partial class SyntaxList
{
internal class WithTwoChildren : SyntaxList
{
private SyntaxNode? _child0;
private SyntaxNode? _child1;
internal WithTwoChildren(InternalSyntax.SyntaxList green, SyntaxNode? parent, int position)
: base(green, parent, position)
{
}
internal override SyntaxNode? GetNodeSlot(int index)
{
switch (index)
{
case 0:
return this.GetRedElement(ref _child0, 0);
case 1:
return this.GetRedElementIfNotToken(ref _child1);
default:
return null;
}
}
internal override SyntaxNode? GetCachedSlot(int index)
{
switch (index)
{
case 0:
return _child0;
case 1:
return _child1;
default:
return null;
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/Test/Core/SourceGeneration/LambdaComparer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Roslyn.Test.Utilities.TestGenerators
{
public sealed class LambdaComparer<T> : IEqualityComparer<T>
{
private readonly Func<T?, T?, bool> _equal;
private readonly int? _hashCode;
public LambdaComparer(Func<T?, T?, bool> equal, int? hashCode = null)
{
_equal = equal;
_hashCode = hashCode;
}
public bool Equals(T? x, T? y) => _equal(x, y);
public int GetHashCode([DisallowNull] T obj) => _hashCode.HasValue ? _hashCode.Value : EqualityComparer<T>.Default.GetHashCode(obj);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Roslyn.Test.Utilities.TestGenerators
{
public sealed class LambdaComparer<T> : IEqualityComparer<T>
{
private readonly Func<T?, T?, bool> _equal;
private readonly int? _hashCode;
public LambdaComparer(Func<T?, T?, bool> equal, int? hashCode = null)
{
_equal = equal;
_hashCode = hashCode;
}
public bool Equals(T? x, T? y) => _equal(x, y);
public int GetHashCode([DisallowNull] T obj) => _hashCode.HasValue ? _hashCode.Value : EqualityComparer<T>.Default.GetHashCode(obj);
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/GeneratedNames.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Globalization
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Helper class to generate synthesized names.
''' </summary>
Friend NotInheritable Class GeneratedNames
Private Const s_idSeparator As Char = "-"c
Private Const s_generationSeparator As Char = "#"c
''' <summary>
''' Generates the name of a state machine's type.
''' </summary>
Public Shared Function MakeStateMachineTypeName(methodName As String, methodOrdinal As Integer, generation As Integer) As String
Debug.Assert(methodOrdinal >= -1)
Return MakeMethodScopedSynthesizedName(GeneratedNameConstants.StateMachineTypeNamePrefix, methodOrdinal, generation, methodName, isTypeName:=True)
End Function
''' <summary>
''' Generates the name of a state machine 'state' field
''' </summary>
Public Shared Function MakeStateMachineStateFieldName() As String
Return GeneratedNameConstants.StateMachineStateFieldName
End Function
Public Shared Function MakeBaseMethodWrapperName(methodName As String, isMyBase As Boolean) As String
Return GeneratedNameConstants.BaseMethodWrapperNamePrefix & methodName & If(isMyBase, "_MyBase", "_MyClass")
End Function
Public Shared Function ReusableHoistedLocalFieldName(number As Integer) As String
Return GeneratedNameConstants.ReusableHoistedLocalFieldName & StringExtensions.GetNumeral(number)
End Function
Public Shared Function MakeStaticLambdaDisplayClassName(methodOrdinal As Integer, generation As Integer) As String
Debug.Assert(methodOrdinal >= -1)
Debug.Assert(generation >= 0)
Return MakeMethodScopedSynthesizedName(GeneratedNameConstants.DisplayClassPrefix, methodOrdinal, generation)
End Function
Friend Shared Function MakeLambdaDisplayClassName(methodOrdinal As Integer, generation As Integer, closureOrdinal As Integer, closureGeneration As Integer, isDelegateRelaxation As Boolean) As String
Debug.Assert(closureOrdinal >= 0)
Debug.Assert(methodOrdinal >= 0)
Debug.Assert(generation >= 0)
Dim prefix = If(isDelegateRelaxation, GeneratedNameConstants.DelegateRelaxationDisplayClassPrefix, GeneratedNameConstants.DisplayClassPrefix)
Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=closureOrdinal, entityGeneration:=closureGeneration, isTypeName:=True)
End Function
Friend Shared Function MakeDisplayClassGenericParameterName(parameterIndex As Integer) As String
Return GeneratedNameConstants.DisplayClassGenericParameterNamePrefix & StringExtensions.GetNumeral(parameterIndex)
End Function
Friend Shared Function MakeLambdaMethodName(methodOrdinal As Integer, generation As Integer, lambdaOrdinal As Integer, lambdaGeneration As Integer, lambdaKind As SynthesizedLambdaKind) As String
Debug.Assert(methodOrdinal >= -1)
Debug.Assert(lambdaOrdinal >= 0)
Dim prefix = If(lambdaKind = SynthesizedLambdaKind.DelegateRelaxationStub,
GeneratedNameConstants.DelegateRelaxationMethodNamePrefix,
GeneratedNameConstants.LambdaMethodNamePrefix)
Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=lambdaOrdinal, entityGeneration:=lambdaGeneration)
End Function
''' <summary>
''' Generates the name of a static lambda display class instance cache
''' </summary>
Public Shared Function MakeCachedFrameInstanceName() As String
Return GeneratedNameConstants.LambdaCacheFieldPrefix
End Function
Friend Shared Function MakeLambdaCacheFieldName(methodOrdinal As Integer, generation As Integer, lambdaOrdinal As Integer, lambdaGeneration As Integer, lambdaKind As SynthesizedLambdaKind) As String
Debug.Assert(methodOrdinal >= -1)
Debug.Assert(lambdaOrdinal >= 0)
Dim prefix = If(lambdaKind = SynthesizedLambdaKind.DelegateRelaxationStub,
GeneratedNameConstants.DelegateRelaxationCacheFieldPrefix,
GeneratedNameConstants.LambdaCacheFieldPrefix)
Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=lambdaOrdinal, entityGeneration:=lambdaGeneration)
End Function
Friend Shared Function MakeDelegateRelaxationParameterName(parameterIndex As Integer) As String
Return GeneratedNameConstants.DelegateStubParameterPrefix & StringExtensions.GetNumeral(parameterIndex)
End Function
Private Shared Function MakeMethodScopedSynthesizedName(prefix As String,
methodOrdinal As Integer,
methodGeneration As Integer,
Optional methodNameOpt As String = Nothing,
Optional entityOrdinal As Integer = -1,
Optional entityGeneration As Integer = -1,
Optional isTypeName As Boolean = False) As String
Debug.Assert(methodOrdinal >= -1)
Debug.Assert(methodGeneration >= 0 OrElse methodGeneration = -1 AndAlso methodOrdinal = -1)
Debug.Assert(entityOrdinal >= -1)
Debug.Assert(entityGeneration >= 0 OrElse entityGeneration = -1 AndAlso entityOrdinal = -1)
Debug.Assert(entityGeneration = -1 OrElse entityGeneration >= methodGeneration)
Dim result = PooledStringBuilder.GetInstance()
Dim builder = result.Builder
builder.Append(prefix)
If methodOrdinal >= 0 Then
builder.Append(methodOrdinal)
If methodGeneration > 0 Then
builder.Append(s_generationSeparator)
builder.Append(methodGeneration)
End If
End If
If entityOrdinal >= 0 Then
If methodOrdinal >= 0 Then
' Can't use underscore since name parser uses it to find the method name.
builder.Append(s_idSeparator)
End If
builder.Append(entityOrdinal)
If entityGeneration > 0 Then
builder.Append(s_generationSeparator)
builder.Append(entityGeneration)
End If
End If
If methodNameOpt IsNot Nothing Then
builder.Append(GeneratedNameConstants.MethodNameSeparator)
builder.Append(methodNameOpt)
' CLR generally allows names with dots, however some APIs like IMetaDataImport
' can only return full type names combined with namespaces.
' see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps)
' When working with such APIs, names with dots become ambiguous since metadata
' consumer cannot figure where namespace ends and actual type name starts.
' Therefore it is a good practice to avoid type names with dots.
If isTypeName Then
builder.Replace("."c, GeneratedNameConstants.DotReplacementInTypeNames)
End If
End If
Return result.ToStringAndFree()
End Function
''' <summary>
''' Generates the name of a state machine 'builder' field
''' </summary>
Public Shared Function MakeStateMachineBuilderFieldName() As String
Return GeneratedNameConstants.StateMachineBuilderFieldName
End Function
''' <summary>
''' Generates the name of a field that backs Current property
''' </summary>
Public Shared Function MakeIteratorCurrentFieldName() As String
Return GeneratedNameConstants.IteratorCurrentFieldName
End Function
''' <summary>
''' Generates the name of a state machine's awaiter field
''' </summary>
Public Shared Function MakeStateMachineAwaiterFieldName(index As Integer) As String
Return GeneratedNameConstants.StateMachineAwaiterFieldPrefix & StringExtensions.GetNumeral(index)
End Function
''' <summary>
''' Generates the name of a state machine's parameter name
''' </summary>
Public Shared Function MakeStateMachineParameterName(paramName As String) As String
Return GeneratedNameConstants.HoistedUserVariablePrefix & paramName
End Function
''' <summary>
''' Generates the name of a state machine's parameter name
''' </summary>
Public Shared Function MakeIteratorParameterProxyName(paramName As String) As String
Return GeneratedNameConstants.IteratorParameterProxyPrefix & paramName
End Function
''' <summary>
''' Generates the name of a field where initial thread ID is stored
''' </summary>
Public Shared Function MakeIteratorInitialThreadIdName() As String
Return GeneratedNameConstants.IteratorInitialThreadIdName
End Function
''' <summary>
''' Generates the name of a state machine field name for captured me reference
''' </summary>
Public Shared Function MakeStateMachineCapturedMeName() As String
Return GeneratedNameConstants.HoistedMeName
End Function
''' <summary>
''' Generates the name of a state machine field name for captured me reference of lambda closure
''' </summary>
Public Shared Function MakeStateMachineCapturedClosureMeName(closureName As String) As String
Return GeneratedNameConstants.HoistedSpecialVariablePrefix & closureName
End Function
Friend Shared Function MakeAnonymousTypeTemplateName(prefix As String, index As Integer, submissionSlotIndex As Integer, moduleId As String) As String
Return If(submissionSlotIndex >= 0,
String.Format("{0}{1}_{2}{3}", prefix, submissionSlotIndex, index, moduleId),
String.Format("{0}{1}{2}", prefix, index, moduleId))
End Function
Friend Shared Function MakeSynthesizedLocalName(kind As SynthesizedLocalKind, ByRef uniqueId As Integer) As String
Debug.Assert(kind.IsLongLived())
' The following variables have to be named, EE depends on the name format.
Dim name As String
Select Case kind
Case SynthesizedLocalKind.LambdaDisplayClass
name = MakeLambdaDisplayClassStorageName(uniqueId)
uniqueId += 1
Case SynthesizedLocalKind.With
' Dev12 didn't name the local. We do so that we can do better job in EE evaluating With statements.
name = GeneratedNameConstants.HoistedWithLocalPrefix & StringExtensions.GetNumeral(uniqueId)
uniqueId += 1
Case Else
name = Nothing
End Select
Return name
End Function
Friend Shared Function MakeLambdaDisplayClassStorageName(uniqueId As Integer) As String
Return GeneratedNameConstants.ClosureVariablePrefix & StringExtensions.GetNumeral(uniqueId)
End Function
Friend Shared Function MakeSignatureString(signature As Byte()) As String
Dim builder = PooledStringBuilder.GetInstance()
For Each b In signature
' Note the format of each byte is not fixed width, so the resulting string may be
' ambiguous. And since this method Is used to generate field names for static
' locals, the same field name may be generated for two locals with the same
' local name in overloaded methods. The native compiler has the same behavior.
' Using a fixed width format {0:X2} would solve this but since the EE relies on
' the format for recognizing static locals, that would be a breaking change.
builder.Builder.AppendFormat("{0:X}", b)
Next
Return builder.ToStringAndFree()
End Function
Friend Shared Function MakeStaticLocalFieldName(
methodName As String,
methodSignature As String,
localName As String) As String
Return String.Format(GeneratedNameConstants.StaticLocalFieldNamePrefix & "{0}${1}${2}", methodName, methodSignature, localName)
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.Globalization
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Helper class to generate synthesized names.
''' </summary>
Friend NotInheritable Class GeneratedNames
Private Const s_idSeparator As Char = "-"c
Private Const s_generationSeparator As Char = "#"c
''' <summary>
''' Generates the name of a state machine's type.
''' </summary>
Public Shared Function MakeStateMachineTypeName(methodName As String, methodOrdinal As Integer, generation As Integer) As String
Debug.Assert(methodOrdinal >= -1)
Return MakeMethodScopedSynthesizedName(GeneratedNameConstants.StateMachineTypeNamePrefix, methodOrdinal, generation, methodName, isTypeName:=True)
End Function
''' <summary>
''' Generates the name of a state machine 'state' field
''' </summary>
Public Shared Function MakeStateMachineStateFieldName() As String
Return GeneratedNameConstants.StateMachineStateFieldName
End Function
Public Shared Function MakeBaseMethodWrapperName(methodName As String, isMyBase As Boolean) As String
Return GeneratedNameConstants.BaseMethodWrapperNamePrefix & methodName & If(isMyBase, "_MyBase", "_MyClass")
End Function
Public Shared Function ReusableHoistedLocalFieldName(number As Integer) As String
Return GeneratedNameConstants.ReusableHoistedLocalFieldName & StringExtensions.GetNumeral(number)
End Function
Public Shared Function MakeStaticLambdaDisplayClassName(methodOrdinal As Integer, generation As Integer) As String
Debug.Assert(methodOrdinal >= -1)
Debug.Assert(generation >= 0)
Return MakeMethodScopedSynthesizedName(GeneratedNameConstants.DisplayClassPrefix, methodOrdinal, generation)
End Function
Friend Shared Function MakeLambdaDisplayClassName(methodOrdinal As Integer, generation As Integer, closureOrdinal As Integer, closureGeneration As Integer, isDelegateRelaxation As Boolean) As String
Debug.Assert(closureOrdinal >= 0)
Debug.Assert(methodOrdinal >= 0)
Debug.Assert(generation >= 0)
Dim prefix = If(isDelegateRelaxation, GeneratedNameConstants.DelegateRelaxationDisplayClassPrefix, GeneratedNameConstants.DisplayClassPrefix)
Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=closureOrdinal, entityGeneration:=closureGeneration, isTypeName:=True)
End Function
Friend Shared Function MakeDisplayClassGenericParameterName(parameterIndex As Integer) As String
Return GeneratedNameConstants.DisplayClassGenericParameterNamePrefix & StringExtensions.GetNumeral(parameterIndex)
End Function
Friend Shared Function MakeLambdaMethodName(methodOrdinal As Integer, generation As Integer, lambdaOrdinal As Integer, lambdaGeneration As Integer, lambdaKind As SynthesizedLambdaKind) As String
Debug.Assert(methodOrdinal >= -1)
Debug.Assert(lambdaOrdinal >= 0)
Dim prefix = If(lambdaKind = SynthesizedLambdaKind.DelegateRelaxationStub,
GeneratedNameConstants.DelegateRelaxationMethodNamePrefix,
GeneratedNameConstants.LambdaMethodNamePrefix)
Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=lambdaOrdinal, entityGeneration:=lambdaGeneration)
End Function
''' <summary>
''' Generates the name of a static lambda display class instance cache
''' </summary>
Public Shared Function MakeCachedFrameInstanceName() As String
Return GeneratedNameConstants.LambdaCacheFieldPrefix
End Function
Friend Shared Function MakeLambdaCacheFieldName(methodOrdinal As Integer, generation As Integer, lambdaOrdinal As Integer, lambdaGeneration As Integer, lambdaKind As SynthesizedLambdaKind) As String
Debug.Assert(methodOrdinal >= -1)
Debug.Assert(lambdaOrdinal >= 0)
Dim prefix = If(lambdaKind = SynthesizedLambdaKind.DelegateRelaxationStub,
GeneratedNameConstants.DelegateRelaxationCacheFieldPrefix,
GeneratedNameConstants.LambdaCacheFieldPrefix)
Return MakeMethodScopedSynthesizedName(prefix, methodOrdinal, generation, entityOrdinal:=lambdaOrdinal, entityGeneration:=lambdaGeneration)
End Function
Friend Shared Function MakeDelegateRelaxationParameterName(parameterIndex As Integer) As String
Return GeneratedNameConstants.DelegateStubParameterPrefix & StringExtensions.GetNumeral(parameterIndex)
End Function
Private Shared Function MakeMethodScopedSynthesizedName(prefix As String,
methodOrdinal As Integer,
methodGeneration As Integer,
Optional methodNameOpt As String = Nothing,
Optional entityOrdinal As Integer = -1,
Optional entityGeneration As Integer = -1,
Optional isTypeName As Boolean = False) As String
Debug.Assert(methodOrdinal >= -1)
Debug.Assert(methodGeneration >= 0 OrElse methodGeneration = -1 AndAlso methodOrdinal = -1)
Debug.Assert(entityOrdinal >= -1)
Debug.Assert(entityGeneration >= 0 OrElse entityGeneration = -1 AndAlso entityOrdinal = -1)
Debug.Assert(entityGeneration = -1 OrElse entityGeneration >= methodGeneration)
Dim result = PooledStringBuilder.GetInstance()
Dim builder = result.Builder
builder.Append(prefix)
If methodOrdinal >= 0 Then
builder.Append(methodOrdinal)
If methodGeneration > 0 Then
builder.Append(s_generationSeparator)
builder.Append(methodGeneration)
End If
End If
If entityOrdinal >= 0 Then
If methodOrdinal >= 0 Then
' Can't use underscore since name parser uses it to find the method name.
builder.Append(s_idSeparator)
End If
builder.Append(entityOrdinal)
If entityGeneration > 0 Then
builder.Append(s_generationSeparator)
builder.Append(entityGeneration)
End If
End If
If methodNameOpt IsNot Nothing Then
builder.Append(GeneratedNameConstants.MethodNameSeparator)
builder.Append(methodNameOpt)
' CLR generally allows names with dots, however some APIs like IMetaDataImport
' can only return full type names combined with namespaces.
' see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps)
' When working with such APIs, names with dots become ambiguous since metadata
' consumer cannot figure where namespace ends and actual type name starts.
' Therefore it is a good practice to avoid type names with dots.
If isTypeName Then
builder.Replace("."c, GeneratedNameConstants.DotReplacementInTypeNames)
End If
End If
Return result.ToStringAndFree()
End Function
''' <summary>
''' Generates the name of a state machine 'builder' field
''' </summary>
Public Shared Function MakeStateMachineBuilderFieldName() As String
Return GeneratedNameConstants.StateMachineBuilderFieldName
End Function
''' <summary>
''' Generates the name of a field that backs Current property
''' </summary>
Public Shared Function MakeIteratorCurrentFieldName() As String
Return GeneratedNameConstants.IteratorCurrentFieldName
End Function
''' <summary>
''' Generates the name of a state machine's awaiter field
''' </summary>
Public Shared Function MakeStateMachineAwaiterFieldName(index As Integer) As String
Return GeneratedNameConstants.StateMachineAwaiterFieldPrefix & StringExtensions.GetNumeral(index)
End Function
''' <summary>
''' Generates the name of a state machine's parameter name
''' </summary>
Public Shared Function MakeStateMachineParameterName(paramName As String) As String
Return GeneratedNameConstants.HoistedUserVariablePrefix & paramName
End Function
''' <summary>
''' Generates the name of a state machine's parameter name
''' </summary>
Public Shared Function MakeIteratorParameterProxyName(paramName As String) As String
Return GeneratedNameConstants.IteratorParameterProxyPrefix & paramName
End Function
''' <summary>
''' Generates the name of a field where initial thread ID is stored
''' </summary>
Public Shared Function MakeIteratorInitialThreadIdName() As String
Return GeneratedNameConstants.IteratorInitialThreadIdName
End Function
''' <summary>
''' Generates the name of a state machine field name for captured me reference
''' </summary>
Public Shared Function MakeStateMachineCapturedMeName() As String
Return GeneratedNameConstants.HoistedMeName
End Function
''' <summary>
''' Generates the name of a state machine field name for captured me reference of lambda closure
''' </summary>
Public Shared Function MakeStateMachineCapturedClosureMeName(closureName As String) As String
Return GeneratedNameConstants.HoistedSpecialVariablePrefix & closureName
End Function
Friend Shared Function MakeAnonymousTypeTemplateName(prefix As String, index As Integer, submissionSlotIndex As Integer, moduleId As String) As String
Return If(submissionSlotIndex >= 0,
String.Format("{0}{1}_{2}{3}", prefix, submissionSlotIndex, index, moduleId),
String.Format("{0}{1}{2}", prefix, index, moduleId))
End Function
Friend Shared Function MakeSynthesizedLocalName(kind As SynthesizedLocalKind, ByRef uniqueId As Integer) As String
Debug.Assert(kind.IsLongLived())
' The following variables have to be named, EE depends on the name format.
Dim name As String
Select Case kind
Case SynthesizedLocalKind.LambdaDisplayClass
name = MakeLambdaDisplayClassStorageName(uniqueId)
uniqueId += 1
Case SynthesizedLocalKind.With
' Dev12 didn't name the local. We do so that we can do better job in EE evaluating With statements.
name = GeneratedNameConstants.HoistedWithLocalPrefix & StringExtensions.GetNumeral(uniqueId)
uniqueId += 1
Case Else
name = Nothing
End Select
Return name
End Function
Friend Shared Function MakeLambdaDisplayClassStorageName(uniqueId As Integer) As String
Return GeneratedNameConstants.ClosureVariablePrefix & StringExtensions.GetNumeral(uniqueId)
End Function
Friend Shared Function MakeSignatureString(signature As Byte()) As String
Dim builder = PooledStringBuilder.GetInstance()
For Each b In signature
' Note the format of each byte is not fixed width, so the resulting string may be
' ambiguous. And since this method Is used to generate field names for static
' locals, the same field name may be generated for two locals with the same
' local name in overloaded methods. The native compiler has the same behavior.
' Using a fixed width format {0:X2} would solve this but since the EE relies on
' the format for recognizing static locals, that would be a breaking change.
builder.Builder.AppendFormat("{0:X}", b)
Next
Return builder.ToStringAndFree()
End Function
Friend Shared Function MakeStaticLocalFieldName(
methodName As String,
methodSignature As String,
localName As String) As String
Return String.Format(GeneratedNameConstants.StaticLocalFieldNamePrefix & "{0}${1}${2}", methodName, methodSignature, localName)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/CompletionListTagCompletionProviderTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
Public Class CompletionListTagCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_EnumTypeDotMemberAlways() As Task
Dim markup = <Text><![CDATA[
Class P
Sub S()
Dim d As Color = $$
End Sub
End Class</a>
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
''' <completionlist cref="Color"/>
Public Class Color
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)>
Public Shared X as Integer = 3
Public Shared Y as Integer = 4
End Class
]]></Text>.Value
Await VerifyItemInEditorBrowsableContextsAsync(
markup:=markup,
referencedCode:=referencedCode,
item:="Color.X",
expectedSymbolsSameSolution:=1,
expectedSymbolsMetadataReference:=1,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_EnumTypeDotMemberNever() As Task
Dim markup = <Text><![CDATA[
Class P
Sub S()
Dim d As Color = $$
End Sub
End Class</a>
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
''' <completionlist cref="Color"/>
Public Class Color
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Public Shared X as Integer = 3
Public Shared Y as Integer = 4
End Class
]]></Text>.Value
Await VerifyItemInEditorBrowsableContextsAsync(
markup:=markup,
referencedCode:=referencedCode,
item:="Color.X",
expectedSymbolsSameSolution:=1,
expectedSymbolsMetadataReference:=0,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_EnumTypeDotMemberAdvanced() As Task
Dim markup = <Text><![CDATA[
Class P
Sub S()
Dim d As Color = $$
End Sub
End Class</a>
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
''' <completionlist cref="Color"/>
Public Class Color
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)>
Public Shared X as Integer = 3
Public Shared Y as Integer = 4
End Class
]]></Text>.Value
Await VerifyItemInEditorBrowsableContextsAsync(
markup:=markup,
referencedCode:=referencedCode,
item:="Color.X",
expectedSymbolsSameSolution:=1,
expectedSymbolsMetadataReference:=0,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic,
hideAdvancedMembers:=True)
Await VerifyItemInEditorBrowsableContextsAsync(
markup:=markup,
referencedCode:=referencedCode,
item:="Color.X",
expectedSymbolsSameSolution:=1,
expectedSymbolsMetadataReference:=1,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic,
hideAdvancedMembers:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTriggeredOnOpenParen() As Task
Dim markup = <Text><![CDATA[
Module Program
Sub Main(args As String())
' type after this line
Bar($$
End Sub
Sub Bar(f As Color)
End Sub
End Module
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True)
Await VerifyItemExistsAsync(markup, "Color.Y", usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestRightSideOfAssignment() As Task
Dim markup = <Text><![CDATA[
Module Program
Sub Main(args As String())
Dim x as Color
x = $$
End Sub
End Module
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True)
Await VerifyItemExistsAsync(markup, "Color.Y", usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDoNotCrashInObjectInitializer() As Task
Dim markup = <Text><![CDATA[
Module Program
Sub Main(args As String())
Dim z = New Goo() With {.z$$ }
End Sub
Class Goo
Property A As Integer
Get
End Get
Set(value As Integer)
End Set
End Property
End Class
End Module
]]></Text>.Value
Await VerifyNoItemsExistAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInYieldReturn() As Task
Dim markup = <Text><![CDATA[
Imports System
Imports System.Collections.Generic
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
Class C
Iterator Function M() As IEnumerable(Of Color)
Yield $$
End Function
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.X")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInAsyncMethodReturnStatement() As Task
Dim markup = <Text><![CDATA[
Imports System.Threading.Tasks
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
Class C
Async Function M() As Task(Of Color)
Await Task.Delay(1)
Return $$
End Function
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.X")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInIndexedProperty() As Task
Dim markup = <Text><![CDATA[
Module Module1
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
Public Class MyClass1
Public WriteOnly Property MyProperty(ByVal val1 As Color) As Boolean
Set(ByVal value As Boolean)
End Set
End Property
Public Sub MyMethod(ByVal val1 As Color)
End Sub
End Class
Sub Main()
Dim var As MyClass1 = New MyClass1
' MARKER
var.MyMethod(Color.X)
var.MyProperty($$Color.Y) = True
End Sub
End Module
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.Y")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFullyQualified() As Task
Dim markup = <Text><![CDATA[
Namespace ColorNamespace
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
End Namespace
Class C
Public Sub M(day As ColorNamespace.Color)
M($$)
End Sub
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "ColorNamespace.Color.X", glyph:=CType(Glyph.FieldPublic, Integer))
Await VerifyItemExistsAsync(markup, "ColorNamespace.Color.Y", glyph:=CType(Glyph.PropertyPublic, Integer))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTriggeredForNamedArgument() As Task
Dim markup = <Text><![CDATA[
Class C
Public Sub M(day As Color)
M(day:=$$)
End Sub
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInObjectCreation() As Task
Dim markup = <Text><![CDATA[
''' <completionlist cref="Program"/>
Class Program
Public Shared Goo As Integer
Sub Main(args As String())
Dim p As Program = New $$
End Sub
End Class
]]></Text>.Value
Await VerifyItemIsAbsentAsync(markup, "Program.Goo")
End Function
<WorkItem(954694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954694")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAnyAccessibleMember() As Task
Dim markup = <Text><![CDATA[
Public Class Program
Private Shared field1 As Integer
''' <summary>
''' </summary>
''' <completionList cref="Program"></completionList>
Public Class Program2
Public Async Function TestM() As Task
Dim obj As Program2 =$$
End Sub
End Class
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Program.field1")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(815963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/815963")>
Public Async Function TestLocalNoAs() As Task
Dim markup = <Text><![CDATA[
Enum E
A
End Enum
Class C
Sub M()
Const e As E = e$$
End Sub
End Class
]]></Text>.Value
Await VerifyItemIsAbsentAsync(markup, "e As E")
End Function
<WorkItem(3518, "https://github.com/dotnet/roslyn/issues/3518")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInTrivia() As Task
Dim markup = <Text><![CDATA[
Class C
Sub Test()
M(Type2.A)
' $$
End Sub
Private Sub M(a As Type1)
Throw New NotImplementedException()
End Sub
End Class
''' <completionlist cref="Type2"/>
Public Class Type1
End Class
Public Class Type2
Public Shared A As Type1
Public Shared B As Type1
End Class
]]></Text>.Value
Await VerifyNoItemsExistAsync(markup)
End Function
<WorkItem(3518, "https://github.com/dotnet/roslyn/issues/3518")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotAfterInvocationWithCompletionListTagTypeAsFirstParameter() As Task
Dim markup = <Text><![CDATA[
Class C
Sub Test()
M(Type2.A)
$$
End Sub
Private Sub M(a As Type1)
Throw New NotImplementedException()
End Sub
End Class
''' <completionlist cref="Type2"/>
Public Class Type1
End Class
Public Class Type2
Public Shared A As Type1
Public Shared B As Type1
End Class
]]></Text>.Value
Await VerifyNoItemsExistAsync(markup)
End Function
<WorkItem(18787, "https://github.com/dotnet/roslyn/issues/18787")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NotAfterDot() As Task
Dim markup = <Text><![CDATA[
Public Class Program
Private Shared field1 As Integer
''' <summary>
''' </summary>
''' <completionList cref="Program"></completionList>
Public Class Program2
Public Async Function TestM() As Task
Dim obj As Program2 = Program.$$
End Sub
End Class
End Class
]]></Text>.Value
Await VerifyNoItemsExistAsync(markup)
End Function
Friend Overrides Function GetCompletionProviderType() As Type
Return GetType(CompletionListTagCompletionProvider)
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.VisualBasic.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
Public Class CompletionListTagCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_EnumTypeDotMemberAlways() As Task
Dim markup = <Text><![CDATA[
Class P
Sub S()
Dim d As Color = $$
End Sub
End Class</a>
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
''' <completionlist cref="Color"/>
Public Class Color
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)>
Public Shared X as Integer = 3
Public Shared Y as Integer = 4
End Class
]]></Text>.Value
Await VerifyItemInEditorBrowsableContextsAsync(
markup:=markup,
referencedCode:=referencedCode,
item:="Color.X",
expectedSymbolsSameSolution:=1,
expectedSymbolsMetadataReference:=1,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_EnumTypeDotMemberNever() As Task
Dim markup = <Text><![CDATA[
Class P
Sub S()
Dim d As Color = $$
End Sub
End Class</a>
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
''' <completionlist cref="Color"/>
Public Class Color
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Public Shared X as Integer = 3
Public Shared Y as Integer = 4
End Class
]]></Text>.Value
Await VerifyItemInEditorBrowsableContextsAsync(
markup:=markup,
referencedCode:=referencedCode,
item:="Color.X",
expectedSymbolsSameSolution:=1,
expectedSymbolsMetadataReference:=0,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestEditorBrowsable_EnumTypeDotMemberAdvanced() As Task
Dim markup = <Text><![CDATA[
Class P
Sub S()
Dim d As Color = $$
End Sub
End Class</a>
]]></Text>.Value
Dim referencedCode = <Text><![CDATA[
''' <completionlist cref="Color"/>
Public Class Color
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)>
Public Shared X as Integer = 3
Public Shared Y as Integer = 4
End Class
]]></Text>.Value
Await VerifyItemInEditorBrowsableContextsAsync(
markup:=markup,
referencedCode:=referencedCode,
item:="Color.X",
expectedSymbolsSameSolution:=1,
expectedSymbolsMetadataReference:=0,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic,
hideAdvancedMembers:=True)
Await VerifyItemInEditorBrowsableContextsAsync(
markup:=markup,
referencedCode:=referencedCode,
item:="Color.X",
expectedSymbolsSameSolution:=1,
expectedSymbolsMetadataReference:=1,
sourceLanguage:=LanguageNames.VisualBasic,
referencedLanguage:=LanguageNames.VisualBasic,
hideAdvancedMembers:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTriggeredOnOpenParen() As Task
Dim markup = <Text><![CDATA[
Module Program
Sub Main(args As String())
' type after this line
Bar($$
End Sub
Sub Bar(f As Color)
End Sub
End Module
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True)
Await VerifyItemExistsAsync(markup, "Color.Y", usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestRightSideOfAssignment() As Task
Dim markup = <Text><![CDATA[
Module Program
Sub Main(args As String())
Dim x as Color
x = $$
End Sub
End Module
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True)
Await VerifyItemExistsAsync(markup, "Color.Y", usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDoNotCrashInObjectInitializer() As Task
Dim markup = <Text><![CDATA[
Module Program
Sub Main(args As String())
Dim z = New Goo() With {.z$$ }
End Sub
Class Goo
Property A As Integer
Get
End Get
Set(value As Integer)
End Set
End Property
End Class
End Module
]]></Text>.Value
Await VerifyNoItemsExistAsync(markup)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInYieldReturn() As Task
Dim markup = <Text><![CDATA[
Imports System
Imports System.Collections.Generic
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
Class C
Iterator Function M() As IEnumerable(Of Color)
Yield $$
End Function
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.X")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInAsyncMethodReturnStatement() As Task
Dim markup = <Text><![CDATA[
Imports System.Threading.Tasks
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
Class C
Async Function M() As Task(Of Color)
Await Task.Delay(1)
Return $$
End Function
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.X")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInIndexedProperty() As Task
Dim markup = <Text><![CDATA[
Module Module1
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
Public Class MyClass1
Public WriteOnly Property MyProperty(ByVal val1 As Color) As Boolean
Set(ByVal value As Boolean)
End Set
End Property
Public Sub MyMethod(ByVal val1 As Color)
End Sub
End Class
Sub Main()
Dim var As MyClass1 = New MyClass1
' MARKER
var.MyMethod(Color.X)
var.MyProperty($$Color.Y) = True
End Sub
End Module
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.Y")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFullyQualified() As Task
Dim markup = <Text><![CDATA[
Namespace ColorNamespace
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
End Namespace
Class C
Public Sub M(day As ColorNamespace.Color)
M($$)
End Sub
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "ColorNamespace.Color.X", glyph:=CType(Glyph.FieldPublic, Integer))
Await VerifyItemExistsAsync(markup, "ColorNamespace.Color.Y", glyph:=CType(Glyph.PropertyPublic, Integer))
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestTriggeredForNamedArgument() As Task
Dim markup = <Text><![CDATA[
Class C
Public Sub M(day As Color)
M(day:=$$)
End Sub
''' <completionlist cref="Color"/>
Public Class Color
Public Shared X as Integer = 3
Public Shared Property Y as Integer = 4
End Class
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Color.X", usePreviousCharAsTrigger:=True)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInObjectCreation() As Task
Dim markup = <Text><![CDATA[
''' <completionlist cref="Program"/>
Class Program
Public Shared Goo As Integer
Sub Main(args As String())
Dim p As Program = New $$
End Sub
End Class
]]></Text>.Value
Await VerifyItemIsAbsentAsync(markup, "Program.Goo")
End Function
<WorkItem(954694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/954694")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAnyAccessibleMember() As Task
Dim markup = <Text><![CDATA[
Public Class Program
Private Shared field1 As Integer
''' <summary>
''' </summary>
''' <completionList cref="Program"></completionList>
Public Class Program2
Public Async Function TestM() As Task
Dim obj As Program2 =$$
End Sub
End Class
End Class
]]></Text>.Value
Await VerifyItemExistsAsync(markup, "Program.field1")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(815963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/815963")>
Public Async Function TestLocalNoAs() As Task
Dim markup = <Text><![CDATA[
Enum E
A
End Enum
Class C
Sub M()
Const e As E = e$$
End Sub
End Class
]]></Text>.Value
Await VerifyItemIsAbsentAsync(markup, "e As E")
End Function
<WorkItem(3518, "https://github.com/dotnet/roslyn/issues/3518")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInTrivia() As Task
Dim markup = <Text><![CDATA[
Class C
Sub Test()
M(Type2.A)
' $$
End Sub
Private Sub M(a As Type1)
Throw New NotImplementedException()
End Sub
End Class
''' <completionlist cref="Type2"/>
Public Class Type1
End Class
Public Class Type2
Public Shared A As Type1
Public Shared B As Type1
End Class
]]></Text>.Value
Await VerifyNoItemsExistAsync(markup)
End Function
<WorkItem(3518, "https://github.com/dotnet/roslyn/issues/3518")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotAfterInvocationWithCompletionListTagTypeAsFirstParameter() As Task
Dim markup = <Text><![CDATA[
Class C
Sub Test()
M(Type2.A)
$$
End Sub
Private Sub M(a As Type1)
Throw New NotImplementedException()
End Sub
End Class
''' <completionlist cref="Type2"/>
Public Class Type1
End Class
Public Class Type2
Public Shared A As Type1
Public Shared B As Type1
End Class
]]></Text>.Value
Await VerifyNoItemsExistAsync(markup)
End Function
<WorkItem(18787, "https://github.com/dotnet/roslyn/issues/18787")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function NotAfterDot() As Task
Dim markup = <Text><![CDATA[
Public Class Program
Private Shared field1 As Integer
''' <summary>
''' </summary>
''' <completionList cref="Program"></completionList>
Public Class Program2
Public Async Function TestM() As Task
Dim obj As Program2 = Program.$$
End Sub
End Class
End Class
]]></Text>.Value
Await VerifyNoItemsExistAsync(markup)
End Function
Friend Overrides Function GetCompletionProviderType() As Type
Return GetType(CompletionListTagCompletionProvider)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayLocalOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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
{
/// <summary>
/// Specifies the options for how locals are displayed in the description of a symbol.
/// </summary>
[Flags]
public enum SymbolDisplayLocalOptions
{
/// <summary>
/// Shows only the name of the local.
/// For example, "x".
/// </summary>
None = 0,
/// <summary>
/// Shows the type of the local in addition to its name.
/// For example, "int x" in C# or "x As Integer" in Visual Basic.
/// </summary>
IncludeType = 1 << 0,
/// <summary>
/// Shows the constant value of the local, if there is one, in addition to its name.
/// For example "x = 1".
/// </summary>
IncludeConstantValue = 1 << 1,
/// <summary>
/// Includes the <c>ref</c> keyword for ref-locals.
/// </summary>
IncludeRef = 1 << 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
{
/// <summary>
/// Specifies the options for how locals are displayed in the description of a symbol.
/// </summary>
[Flags]
public enum SymbolDisplayLocalOptions
{
/// <summary>
/// Shows only the name of the local.
/// For example, "x".
/// </summary>
None = 0,
/// <summary>
/// Shows the type of the local in addition to its name.
/// For example, "int x" in C# or "x As Integer" in Visual Basic.
/// </summary>
IncludeType = 1 << 0,
/// <summary>
/// Shows the constant value of the local, if there is one, in addition to its name.
/// For example "x = 1".
/// </summary>
IncludeConstantValue = 1 << 1,
/// <summary>
/// Includes the <c>ref</c> keyword for ref-locals.
/// </summary>
IncludeRef = 1 << 2,
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Features/VisualBasic/Portable/SimplifyThisOrMe/VisualBasicSimplifyThisOrMeDiagnosticAnalyzer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.SimplifyThisOrMe
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Simplification.Simplifiers
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyThisOrMe
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicSimplifyThisOrMeDiagnosticAnalyzer
Inherits AbstractSimplifyThisOrMeDiagnosticAnalyzer(Of
SyntaxKind,
ExpressionSyntax,
MeExpressionSyntax,
MemberAccessExpressionSyntax)
Protected Overrides Function GetLanguageName() As String
Return LanguageNames.VisualBasic
End Function
Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts
Return VisualBasicSyntaxFacts.Instance
End Function
Protected Overrides Function CanSimplifyTypeNameExpression(
model As SemanticModel, memberAccess As MemberAccessExpressionSyntax,
optionSet As OptionSet, ByRef issueSpan As TextSpan,
cancellationToken As CancellationToken) As Boolean
Dim replacementSyntax As ExpressionSyntax = Nothing
Return ExpressionSimplifier.Instance.TrySimplify(memberAccess, model, optionSet, replacementSyntax, issueSpan, cancellationToken)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.SimplifyThisOrMe
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Simplification.Simplifiers
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyThisOrMe
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicSimplifyThisOrMeDiagnosticAnalyzer
Inherits AbstractSimplifyThisOrMeDiagnosticAnalyzer(Of
SyntaxKind,
ExpressionSyntax,
MeExpressionSyntax,
MemberAccessExpressionSyntax)
Protected Overrides Function GetLanguageName() As String
Return LanguageNames.VisualBasic
End Function
Protected Overrides Function GetSyntaxFacts() As ISyntaxFacts
Return VisualBasicSyntaxFacts.Instance
End Function
Protected Overrides Function CanSimplifyTypeNameExpression(
model As SemanticModel, memberAccess As MemberAccessExpressionSyntax,
optionSet As OptionSet, ByRef issueSpan As TextSpan,
cancellationToken As CancellationToken) As Boolean
Dim replacementSyntax As ExpressionSyntax = Nothing
Return ExpressionSimplifier.Instance.TrySimplify(memberAccess, model, optionSet, replacementSyntax, issueSpan, cancellationToken)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Tools/ExternalAccess/FSharp/Shared/Options/FSharpServiceFeatureOnOffOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.SolutionCrawler;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Shared.Options
{
internal static class FSharpServiceFeatureOnOffOptions
{
/// <summary>
/// this option is solely for performance. don't confused by option name.
/// this option doesn't mean we will show all diagnostics that belong to opened files when turned off,
/// rather it means we will only show diagnostics that are cheap to calculate for small scope such as opened files.
/// </summary>
[Obsolete("Currently used by F# - should move to the new option SolutionCrawlerOptions.BackgroundAnalysisScopeOption")]
public static PerLanguageOption<bool?> ClosedFileDiagnostic => SolutionCrawlerOptions.ClosedFileDiagnostic;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.SolutionCrawler;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Shared.Options
{
internal static class FSharpServiceFeatureOnOffOptions
{
/// <summary>
/// this option is solely for performance. don't confused by option name.
/// this option doesn't mean we will show all diagnostics that belong to opened files when turned off,
/// rather it means we will only show diagnostics that are cheap to calculate for small scope such as opened files.
/// </summary>
[Obsolete("Currently used by F# - should move to the new option SolutionCrawlerOptions.BackgroundAnalysisScopeOption")]
public static PerLanguageOption<bool?> ClosedFileDiagnostic => SolutionCrawlerOptions.ClosedFileDiagnostic;
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Coordinates the exectution of LSP messages to ensure correct results are sent back.
/// </summary>
/// <remarks>
/// <para>
/// When a request comes in for some data the handler must be able to access a solution state that is correct
/// at the time of the request, that takes into account any text change requests that have come in previously
/// (via textDocument/didChange for example).
/// </para>
/// <para>
/// This class acheives this by distinguishing between mutating and non-mutating requests, and ensuring that
/// when a mutating request comes in, its processing blocks all subsequent requests. As each request comes in
/// it is added to a queue, and a queue item will not be retrieved while a mutating request is running. Before
/// any request is handled the solution state is created by merging workspace solution state, which could have
/// changes from non-LSP means (eg, adding a project reference), with the current "mutated" state.
/// When a non-mutating work item is retrieved from the queue, it is given the current solution state, but then
/// run in a fire-and-forget fashion.
/// </para>
/// <para>
/// Regardless of whether a request is mutating or not, or blocking or not, is an implementation detail of this class
/// and any consumers observing the results of the task returned from <see cref="ExecuteAsync{TRequestType, TResponseType}(bool, bool, IRequestHandler{TRequestType, TResponseType}, TRequestType, ClientCapabilities, string?, string, CancellationToken)"/>
/// will see the results of the handling of the request, whenever it occurred.
/// </para>
/// <para>
/// Exceptions in the handling of non-mutating requests are sent back to callers. Exceptions in the processing of
/// the queue will close the LSP connection so that the client can reconnect. Exceptions in the handling of mutating
/// requests will also close the LSP connection, as at that point the mutated solution is in an unknown state.
/// </para>
/// <para>
/// After shutdown is called, or an error causes the closing of the connection, the queue will not accept any
/// more messages, and a new queue will need to be created.
/// </para>
/// </remarks>
internal partial class RequestExecutionQueue
{
private readonly string _serverName;
private readonly ImmutableArray<string> _supportedLanguages;
private readonly AsyncQueue<QueueItem> _queue;
private readonly CancellationTokenSource _cancelSource;
private readonly DocumentChangeTracker _documentChangeTracker;
private readonly RequestTelemetryLogger _requestTelemetryLogger;
// This dictionary is used to cache our forked LSP solution so we don't have to
// recompute it for each request. We don't need to worry about threading because they are only
// used when preparing to handle a request, which happens in a single thread in the ProcessQueueAsync
// method.
private readonly Dictionary<Workspace, (Solution workspaceSolution, Solution lspSolution)> _lspSolutionCache = new();
private readonly ILspLogger _logger;
private readonly ILspWorkspaceRegistrationService _workspaceRegistrationService;
public CancellationToken CancellationToken => _cancelSource.Token;
/// <summary>
/// Raised when the execution queue has failed, or the solution state its tracking is in an unknown state
/// and so the only course of action is to shutdown the server so that the client re-connects and we can
/// start over again.
/// </summary>
/// <remarks>
/// Once this event has been fired all currently active and pending work items in the queue will be cancelled.
/// </remarks>
public event EventHandler<RequestShutdownEventArgs>? RequestServerShutdown;
public RequestExecutionQueue(
ILspLogger logger,
ILspWorkspaceRegistrationService workspaceRegistrationService,
ImmutableArray<string> supportedLanguages,
string serverName,
string serverTypeName)
{
_logger = logger;
_workspaceRegistrationService = workspaceRegistrationService;
_supportedLanguages = supportedLanguages;
_serverName = serverName;
_queue = new AsyncQueue<QueueItem>();
_cancelSource = new CancellationTokenSource();
_documentChangeTracker = new DocumentChangeTracker();
// Pass the language client instance type name to the telemetry logger to ensure we can
// differentiate between the different C# LSP servers that have the same client name.
// We also don't use the language client's name property as it is a localized user facing string
// which is difficult to write telemetry queries for.
_requestTelemetryLogger = new RequestTelemetryLogger(serverTypeName);
// Start the queue processing
_ = ProcessQueueAsync();
}
/// <summary>
/// Shuts down the queue, stops accepting new messages, and cancels any in-progress or queued tasks. Calling
/// this multiple times won't cause any issues.
/// </summary>
public void Shutdown()
{
_cancelSource.Cancel();
DrainQueue();
_requestTelemetryLogger.Dispose();
}
/// <summary>
/// Queues a request to be handled by the specified handler, with mutating requests blocking subsequent requests
/// from starting until the mutation is complete.
/// </summary>
/// <param name="mutatesSolutionState">Whether or not handling this method results in changes to the current solution state.
/// Mutating requests will block all subsequent requests from starting until after they have
/// completed and mutations have been applied.</param>
/// <param name="requiresLSPSolution">Whether or not to build a solution that represents the LSP view of the world. If this
/// is set to false, the default workspace's current solution will be used.</param>
/// <param name="handler">The handler that will handle the request.</param>
/// <param name="request">The request to handle.</param>
/// <param name="clientCapabilities">The client capabilities.</param>
/// <param name="clientName">The client name.</param>
/// <param name="methodName">The name of the LSP method.</param>
/// <param name="requestCancellationToken">A cancellation token that will cancel the handing of this request.
/// The request could also be cancelled by the queue shutting down.</param>
/// <returns>A task that can be awaited to observe the results of the handing of this request.</returns>
public Task<TResponseType> ExecuteAsync<TRequestType, TResponseType>(
bool mutatesSolutionState,
bool requiresLSPSolution,
IRequestHandler<TRequestType, TResponseType> handler,
TRequestType request,
ClientCapabilities clientCapabilities,
string? clientName,
string methodName,
CancellationToken requestCancellationToken) where TRequestType : class
{
// Create a task completion source that will represent the processing of this request to the caller
var completion = new TaskCompletionSource<TResponseType>();
// Note: If the queue is not accepting any more items then TryEnqueue below will fail.
var textDocument = handler.GetTextDocumentIdentifier(request);
var item = new QueueItem(
mutatesSolutionState,
requiresLSPSolution,
clientCapabilities,
clientName,
methodName,
textDocument,
Trace.CorrelationManager.ActivityId,
_logger,
_requestTelemetryLogger,
callbackAsync: async (context, cancellationToken) =>
{
// Check if cancellation was requested while this was waiting in the queue
if (cancellationToken.IsCancellationRequested)
{
completion.SetCanceled();
return;
}
try
{
var result = await handler.HandleRequestAsync(request, context, cancellationToken).ConfigureAwait(false);
completion.SetResult(result);
}
catch (OperationCanceledException ex)
{
completion.TrySetCanceled(ex.CancellationToken);
}
catch (Exception exception)
{
// Pass the exception to the task completion source, so the caller of the ExecuteAsync method can react
completion.SetException(exception);
// Also allow the exception to flow back to the request queue to handle as appropriate
throw new InvalidOperationException($"Error handling '{methodName}' request: {exception.Message}", exception);
}
}, requestCancellationToken);
var didEnqueue = _queue.TryEnqueue(item);
// If the queue has been shut down the enqueue will fail, so we just fault the task immediately.
// The queue itself is threadsafe (_queue.TryEnqueue and _queue.Complete use the same lock).
if (!didEnqueue)
{
completion.SetException(new InvalidOperationException($"{_serverName} was requested to shut down."));
}
return completion.Task;
}
private async Task ProcessQueueAsync()
{
try
{
while (!_cancelSource.IsCancellationRequested)
{
var work = await _queue.DequeueAsync(_cancelSource.Token).ConfigureAwait(false);
// Record when the work item was been de-queued and the request context preparation started.
work.Metrics.RecordExecutionStart();
// Restore our activity id so that logging/tracking works across asynchronous calls.
Trace.CorrelationManager.ActivityId = work.ActivityId;
var context = CreateRequestContext(work, out var workspace);
if (work.MutatesSolutionState)
{
// Mutating requests block other requests from starting to ensure an up to date snapshot is used.
await ExecuteCallbackAsync(work, context, _cancelSource.Token).ConfigureAwait(false);
// Now that we've mutated our solution, clear out our saved state to ensure it gets recalculated
_lspSolutionCache.Remove(workspace);
}
else
{
// Non mutating are fire-and-forget because they are by definition readonly. Any errors
// will be sent back to the client but we can still capture errors in queue processing
// via NFW, though these errors don't put us into a bad state as far as the rest of the queue goes.
// Furthermore we use Task.Run here to protect ourselves against synchronous execution of work
// blocking the request queue for longer periods of time (it enforces parallelizabilty).
_ = Task.Run(() => ExecuteCallbackAsync(work, context, _cancelSource.Token), _cancelSource.Token).ReportNonFatalErrorAsync();
}
}
}
catch (OperationCanceledException e) when (e.CancellationToken == _cancelSource.Token)
{
// If cancellation occurs as a result of our token, then it was either because we cancelled it in the Shutdown
// method, if it happened during a mutating request, or because the queue was completed in the Shutdown method
// if it happened while waiting to dequeue the next item. Either way, we're already shutting down so we don't
// want to log it.
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
_logger.TraceException(e);
OnRequestServerShutdown($"Error occurred processing queue in {_serverName}: {e.Message}.");
}
}
private static Task ExecuteCallbackAsync(QueueItem work, RequestContext context, CancellationToken queueCancellationToken)
{
// Create a combined cancellation token to cancel any requests in progress when this shuts down
using var combinedTokenSource = queueCancellationToken.CombineWith(work.CancellationToken);
return work.CallbackAsync(context, combinedTokenSource.Token);
}
private void OnRequestServerShutdown(string message)
{
RequestServerShutdown?.Invoke(this, new RequestShutdownEventArgs(message));
Shutdown();
}
/// <summary>
/// Cancels all requests in the queue and stops the queue from accepting any more requests. After this method
/// is called this queue is essentially useless.
/// </summary>
private void DrainQueue()
{
// Tell the queue not to accept any more items
_queue.Complete();
// Spin through the queue and pass in our cancelled token, so that the waiting tasks are cancelled.
// NOTE: This only really works because the first thing that CallbackAsync does is check for cancellation
// but generics make it annoying to store the TaskCompletionSource<TResult> on the QueueItem so this
// is the best we can do for now. Ideally we would manipulate the TaskCompletionSource directly here
// and just call SetCanceled
while (_queue.TryDequeue(out var item))
{
_ = item.CallbackAsync(default, new CancellationToken(true));
}
}
private RequestContext CreateRequestContext(QueueItem queueItem, out Workspace workspace)
{
var trackerToUse = queueItem.MutatesSolutionState
? (IDocumentChangeTracker)_documentChangeTracker
: new NonMutatingDocumentChangeTracker(_documentChangeTracker);
return RequestContext.Create(
queueItem.RequiresLSPSolution,
queueItem.TextDocument,
queueItem.ClientName,
_logger,
_requestTelemetryLogger,
queueItem.ClientCapabilities,
_workspaceRegistrationService,
_lspSolutionCache,
trackerToUse,
_supportedLanguages,
out 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Coordinates the exectution of LSP messages to ensure correct results are sent back.
/// </summary>
/// <remarks>
/// <para>
/// When a request comes in for some data the handler must be able to access a solution state that is correct
/// at the time of the request, that takes into account any text change requests that have come in previously
/// (via textDocument/didChange for example).
/// </para>
/// <para>
/// This class acheives this by distinguishing between mutating and non-mutating requests, and ensuring that
/// when a mutating request comes in, its processing blocks all subsequent requests. As each request comes in
/// it is added to a queue, and a queue item will not be retrieved while a mutating request is running. Before
/// any request is handled the solution state is created by merging workspace solution state, which could have
/// changes from non-LSP means (eg, adding a project reference), with the current "mutated" state.
/// When a non-mutating work item is retrieved from the queue, it is given the current solution state, but then
/// run in a fire-and-forget fashion.
/// </para>
/// <para>
/// Regardless of whether a request is mutating or not, or blocking or not, is an implementation detail of this class
/// and any consumers observing the results of the task returned from <see cref="ExecuteAsync{TRequestType, TResponseType}(bool, bool, IRequestHandler{TRequestType, TResponseType}, TRequestType, ClientCapabilities, string?, string, CancellationToken)"/>
/// will see the results of the handling of the request, whenever it occurred.
/// </para>
/// <para>
/// Exceptions in the handling of non-mutating requests are sent back to callers. Exceptions in the processing of
/// the queue will close the LSP connection so that the client can reconnect. Exceptions in the handling of mutating
/// requests will also close the LSP connection, as at that point the mutated solution is in an unknown state.
/// </para>
/// <para>
/// After shutdown is called, or an error causes the closing of the connection, the queue will not accept any
/// more messages, and a new queue will need to be created.
/// </para>
/// </remarks>
internal partial class RequestExecutionQueue
{
private readonly string _serverName;
private readonly ImmutableArray<string> _supportedLanguages;
private readonly AsyncQueue<QueueItem> _queue;
private readonly CancellationTokenSource _cancelSource;
private readonly DocumentChangeTracker _documentChangeTracker;
private readonly RequestTelemetryLogger _requestTelemetryLogger;
// This dictionary is used to cache our forked LSP solution so we don't have to
// recompute it for each request. We don't need to worry about threading because they are only
// used when preparing to handle a request, which happens in a single thread in the ProcessQueueAsync
// method.
private readonly Dictionary<Workspace, (Solution workspaceSolution, Solution lspSolution)> _lspSolutionCache = new();
private readonly ILspLogger _logger;
private readonly ILspWorkspaceRegistrationService _workspaceRegistrationService;
public CancellationToken CancellationToken => _cancelSource.Token;
/// <summary>
/// Raised when the execution queue has failed, or the solution state its tracking is in an unknown state
/// and so the only course of action is to shutdown the server so that the client re-connects and we can
/// start over again.
/// </summary>
/// <remarks>
/// Once this event has been fired all currently active and pending work items in the queue will be cancelled.
/// </remarks>
public event EventHandler<RequestShutdownEventArgs>? RequestServerShutdown;
public RequestExecutionQueue(
ILspLogger logger,
ILspWorkspaceRegistrationService workspaceRegistrationService,
ImmutableArray<string> supportedLanguages,
string serverName,
string serverTypeName)
{
_logger = logger;
_workspaceRegistrationService = workspaceRegistrationService;
_supportedLanguages = supportedLanguages;
_serverName = serverName;
_queue = new AsyncQueue<QueueItem>();
_cancelSource = new CancellationTokenSource();
_documentChangeTracker = new DocumentChangeTracker();
// Pass the language client instance type name to the telemetry logger to ensure we can
// differentiate between the different C# LSP servers that have the same client name.
// We also don't use the language client's name property as it is a localized user facing string
// which is difficult to write telemetry queries for.
_requestTelemetryLogger = new RequestTelemetryLogger(serverTypeName);
// Start the queue processing
_ = ProcessQueueAsync();
}
/// <summary>
/// Shuts down the queue, stops accepting new messages, and cancels any in-progress or queued tasks. Calling
/// this multiple times won't cause any issues.
/// </summary>
public void Shutdown()
{
_cancelSource.Cancel();
DrainQueue();
_requestTelemetryLogger.Dispose();
}
/// <summary>
/// Queues a request to be handled by the specified handler, with mutating requests blocking subsequent requests
/// from starting until the mutation is complete.
/// </summary>
/// <param name="mutatesSolutionState">Whether or not handling this method results in changes to the current solution state.
/// Mutating requests will block all subsequent requests from starting until after they have
/// completed and mutations have been applied.</param>
/// <param name="requiresLSPSolution">Whether or not to build a solution that represents the LSP view of the world. If this
/// is set to false, the default workspace's current solution will be used.</param>
/// <param name="handler">The handler that will handle the request.</param>
/// <param name="request">The request to handle.</param>
/// <param name="clientCapabilities">The client capabilities.</param>
/// <param name="clientName">The client name.</param>
/// <param name="methodName">The name of the LSP method.</param>
/// <param name="requestCancellationToken">A cancellation token that will cancel the handing of this request.
/// The request could also be cancelled by the queue shutting down.</param>
/// <returns>A task that can be awaited to observe the results of the handing of this request.</returns>
public Task<TResponseType> ExecuteAsync<TRequestType, TResponseType>(
bool mutatesSolutionState,
bool requiresLSPSolution,
IRequestHandler<TRequestType, TResponseType> handler,
TRequestType request,
ClientCapabilities clientCapabilities,
string? clientName,
string methodName,
CancellationToken requestCancellationToken) where TRequestType : class
{
// Create a task completion source that will represent the processing of this request to the caller
var completion = new TaskCompletionSource<TResponseType>();
// Note: If the queue is not accepting any more items then TryEnqueue below will fail.
var textDocument = handler.GetTextDocumentIdentifier(request);
var item = new QueueItem(
mutatesSolutionState,
requiresLSPSolution,
clientCapabilities,
clientName,
methodName,
textDocument,
Trace.CorrelationManager.ActivityId,
_logger,
_requestTelemetryLogger,
callbackAsync: async (context, cancellationToken) =>
{
// Check if cancellation was requested while this was waiting in the queue
if (cancellationToken.IsCancellationRequested)
{
completion.SetCanceled();
return;
}
try
{
var result = await handler.HandleRequestAsync(request, context, cancellationToken).ConfigureAwait(false);
completion.SetResult(result);
}
catch (OperationCanceledException ex)
{
completion.TrySetCanceled(ex.CancellationToken);
}
catch (Exception exception)
{
// Pass the exception to the task completion source, so the caller of the ExecuteAsync method can react
completion.SetException(exception);
// Also allow the exception to flow back to the request queue to handle as appropriate
throw new InvalidOperationException($"Error handling '{methodName}' request: {exception.Message}", exception);
}
}, requestCancellationToken);
var didEnqueue = _queue.TryEnqueue(item);
// If the queue has been shut down the enqueue will fail, so we just fault the task immediately.
// The queue itself is threadsafe (_queue.TryEnqueue and _queue.Complete use the same lock).
if (!didEnqueue)
{
completion.SetException(new InvalidOperationException($"{_serverName} was requested to shut down."));
}
return completion.Task;
}
private async Task ProcessQueueAsync()
{
try
{
while (!_cancelSource.IsCancellationRequested)
{
var work = await _queue.DequeueAsync(_cancelSource.Token).ConfigureAwait(false);
// Record when the work item was been de-queued and the request context preparation started.
work.Metrics.RecordExecutionStart();
// Restore our activity id so that logging/tracking works across asynchronous calls.
Trace.CorrelationManager.ActivityId = work.ActivityId;
var context = CreateRequestContext(work, out var workspace);
if (work.MutatesSolutionState)
{
// Mutating requests block other requests from starting to ensure an up to date snapshot is used.
await ExecuteCallbackAsync(work, context, _cancelSource.Token).ConfigureAwait(false);
// Now that we've mutated our solution, clear out our saved state to ensure it gets recalculated
_lspSolutionCache.Remove(workspace);
}
else
{
// Non mutating are fire-and-forget because they are by definition readonly. Any errors
// will be sent back to the client but we can still capture errors in queue processing
// via NFW, though these errors don't put us into a bad state as far as the rest of the queue goes.
// Furthermore we use Task.Run here to protect ourselves against synchronous execution of work
// blocking the request queue for longer periods of time (it enforces parallelizabilty).
_ = Task.Run(() => ExecuteCallbackAsync(work, context, _cancelSource.Token), _cancelSource.Token).ReportNonFatalErrorAsync();
}
}
}
catch (OperationCanceledException e) when (e.CancellationToken == _cancelSource.Token)
{
// If cancellation occurs as a result of our token, then it was either because we cancelled it in the Shutdown
// method, if it happened during a mutating request, or because the queue was completed in the Shutdown method
// if it happened while waiting to dequeue the next item. Either way, we're already shutting down so we don't
// want to log it.
}
catch (Exception e) when (FatalError.ReportAndCatch(e))
{
_logger.TraceException(e);
OnRequestServerShutdown($"Error occurred processing queue in {_serverName}: {e.Message}.");
}
}
private static Task ExecuteCallbackAsync(QueueItem work, RequestContext context, CancellationToken queueCancellationToken)
{
// Create a combined cancellation token to cancel any requests in progress when this shuts down
using var combinedTokenSource = queueCancellationToken.CombineWith(work.CancellationToken);
return work.CallbackAsync(context, combinedTokenSource.Token);
}
private void OnRequestServerShutdown(string message)
{
RequestServerShutdown?.Invoke(this, new RequestShutdownEventArgs(message));
Shutdown();
}
/// <summary>
/// Cancels all requests in the queue and stops the queue from accepting any more requests. After this method
/// is called this queue is essentially useless.
/// </summary>
private void DrainQueue()
{
// Tell the queue not to accept any more items
_queue.Complete();
// Spin through the queue and pass in our cancelled token, so that the waiting tasks are cancelled.
// NOTE: This only really works because the first thing that CallbackAsync does is check for cancellation
// but generics make it annoying to store the TaskCompletionSource<TResult> on the QueueItem so this
// is the best we can do for now. Ideally we would manipulate the TaskCompletionSource directly here
// and just call SetCanceled
while (_queue.TryDequeue(out var item))
{
_ = item.CallbackAsync(default, new CancellationToken(true));
}
}
private RequestContext CreateRequestContext(QueueItem queueItem, out Workspace workspace)
{
var trackerToUse = queueItem.MutatesSolutionState
? (IDocumentChangeTracker)_documentChangeTracker
: new NonMutatingDocumentChangeTracker(_documentChangeTracker);
return RequestContext.Create(
queueItem.RequiresLSPSolution,
queueItem.TextDocument,
queueItem.ClientName,
_logger,
_requestTelemetryLogger,
queueItem.ClientCapabilities,
_workspaceRegistrationService,
_lspSolutionCache,
trackerToUse,
_supportedLanguages,
out workspace);
}
}
}
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Features/VisualBasic/Portable/Completion/CompletionProviders/XmlDocCommentCompletionProvider.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.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.ErrorReporting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities.DocumentationCommentXmlNames
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
<ExportCompletionProvider(NameOf(XmlDocCommentCompletionProvider), LanguageNames.VisualBasic)>
<ExtensionOrder(After:=NameOf(OverrideCompletionProvider))>
<[Shared]>
Friend Class XmlDocCommentCompletionProvider
Inherits AbstractDocCommentCompletionProvider(Of DocumentationCommentTriviaSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
MyBase.New(s_defaultRules)
End Sub
Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Dim isStartOfTag = text(characterPosition) = "<"c
Dim isClosingTag = (text(characterPosition) = "/"c AndAlso characterPosition > 0 AndAlso text(characterPosition - 1) = "<"c)
Dim isDoubleQuote = text(characterPosition) = """"c
Return isStartOfTag OrElse isClosingTag OrElse isDoubleQuote OrElse
IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options)
End Function
Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = ImmutableHashSet.Create("<"c, "/"c, """"c, " "c)
Public Shared Function GetPreviousTokenIfTouchingText(token As SyntaxToken, position As Integer) As SyntaxToken
Return If(token.IntersectsWith(position) AndAlso IsText(token),
token.GetPreviousToken(includeSkipped:=True),
token)
End Function
Private Shared Function IsText(token As SyntaxToken) As Boolean
Return token.IsKind(SyntaxKind.XmlNameToken, SyntaxKind.XmlTextLiteralToken, SyntaxKind.IdentifierToken)
End Function
Protected Overrides Async Function GetItemsWorkerAsync(document As Document, position As Integer, trigger As CompletionTrigger, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of CompletionItem))
Try
Dim tree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False)
Dim token = tree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments:=True)
Dim parent = token.GetAncestor(Of DocumentationCommentTriviaSyntax)()
If parent Is Nothing Then
Return Nothing
End If
' If the user is typing in xml text, don't trigger on backspace.
If token.IsKind(SyntaxKind.XmlTextLiteralToken) AndAlso
trigger.Kind = CompletionTriggerKind.Deletion Then
Return Nothing
End If
' Never provide any items inside a cref
If token.Parent.IsKind(SyntaxKind.XmlString) AndAlso token.Parent.Parent.IsKind(SyntaxKind.XmlAttribute) Then
Dim attribute = DirectCast(token.Parent.Parent, XmlAttributeSyntax)
Dim name = TryCast(attribute.Name, XmlNameSyntax)
Dim value = TryCast(attribute.Value, XmlStringSyntax)
If name?.LocalName.ValueText = CrefAttributeName AndAlso Not token = value?.EndQuoteToken Then
Return Nothing
End If
End If
If token.Parent.GetAncestor(Of XmlCrefAttributeSyntax)() IsNot Nothing Then
Return Nothing
End If
Dim items = New List(Of CompletionItem)()
Dim attachedToken = parent.ParentTrivia.Token
If attachedToken.Kind = SyntaxKind.None Then
Return items
End If
Dim declaration = attachedToken.GetAncestor(Of DeclarationStatementSyntax)()
' Maybe we're going to suggest the close tag
If token.Kind = SyntaxKind.LessThanSlashToken Then
Return GetCloseTagItem(token)
ElseIf token.IsKind(SyntaxKind.XmlNameToken) AndAlso token.GetPreviousToken().IsKind(SyntaxKind.LessThanSlashToken) Then
Return GetCloseTagItem(token.GetPreviousToken())
End If
Dim semanticModel = Await document.ReuseExistingSpeculativeModelAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(False)
Dim symbol As ISymbol = Nothing
If declaration IsNot Nothing Then
symbol = semanticModel.GetDeclaredSymbol(declaration, cancellationToken)
End If
If symbol IsNot Nothing Then
' Maybe we're going to do attribute completion
TryGetAttributes(token, position, items, symbol)
If items.Any() Then
Return items
End If
End If
If trigger.Kind = CompletionTriggerKind.Insertion AndAlso
Not trigger.Character = """"c AndAlso
Not trigger.Character = "<"c Then
' With the use of IsTriggerAfterSpaceOrStartOfWordCharacter, the code below is much
' too aggressive at suggesting tags, so exit early before degrading the experience
Return items
End If
items.AddRange(GetAlwaysVisibleItems())
Dim parentElement = token.GetAncestor(Of XmlElementSyntax)()
Dim grandParent = parentElement?.Parent
If grandParent.IsKind(SyntaxKind.XmlElement) Then
' Avoid including language keywords when following < Or <text, since these cases should only be
' attempting to complete the XML name (which for language keywords Is 'see'). The VB parser treats
' spaces after a < character as trailing whitespace, even if an identifier follows it on the same line.
' Therefore, the consistent VB experience says we never show keywords for < followed by spaces.
Dim xmlNameOnly = token.IsKind(SyntaxKind.LessThanToken) OrElse token.Parent.IsKind(SyntaxKind.XmlName)
Dim includeKeywords = Not xmlNameOnly
items.AddRange(GetNestedItems(symbol, includeKeywords))
AddXmlElementItems(items, grandParent)
ElseIf token.Parent.IsKind(SyntaxKind.XmlText) AndAlso
token.Parent.IsParentKind(SyntaxKind.DocumentationCommentTrivia) Then
' Top level, without tag:
' ''' $$
items.AddRange(GetTopLevelItems(symbol, parent))
ElseIf token.Parent.IsKind(SyntaxKind.XmlText) AndAlso
token.Parent.Parent.IsKind(SyntaxKind.XmlElement) Then
items.AddRange(GetNestedItems(symbol, includeKeywords:=True))
Dim xmlElement = token.Parent.Parent
AddXmlElementItems(items, xmlElement)
ElseIf grandParent.IsKind(SyntaxKind.DocumentationCommentTrivia) Then
' Top level, with tag:
' ''' <$$
' ''' <tag$$
items.AddRange(GetTopLevelItems(symbol, parent))
End If
If token.Parent.IsKind(SyntaxKind.XmlElementStartTag, SyntaxKind.XmlName) AndAlso
parentElement.IsParentKind(SyntaxKind.XmlElement) Then
AddXmlElementItems(items, parentElement.Parent)
End If
Return items
Catch e As Exception When FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)
Return SpecializedCollections.EmptyEnumerable(Of CompletionItem)
End Try
End Function
Private Sub AddXmlElementItems(items As List(Of CompletionItem), xmlElement As SyntaxNode)
Dim startTagName = GetStartTagName(xmlElement)
If startTagName = ListElementName Then
items.AddRange(GetListItems())
ElseIf startTagName = ListHeaderElementName Then
items.AddRange(GetListHeaderItems())
ElseIf startTagName = ItemElementName Then
items.AddRange(GetItemTagItems())
End If
End Sub
Private Function GetCloseTagItem(token As SyntaxToken) As IEnumerable(Of CompletionItem)
Dim endTag = TryCast(token.Parent, XmlElementEndTagSyntax)
If endTag Is Nothing Then
Return Nothing
End If
Dim element = TryCast(endTag.Parent, XmlElementSyntax)
If element Is Nothing Then
Return Nothing
End If
Dim startElement = element.StartTag
Dim name = TryCast(startElement.Name, XmlNameSyntax)
If name Is Nothing Then
Return Nothing
End If
Dim nameToken = name.LocalName
If Not nameToken.IsMissing AndAlso nameToken.ValueText.Length > 0 Then
Return SpecializedCollections.SingletonEnumerable(CreateCompletionItem(nameToken.ValueText, nameToken.ValueText & ">", String.Empty))
End If
Return Nothing
End Function
Private Shared Function GetStartTagName(element As SyntaxNode) As String
Return DirectCast(DirectCast(element, XmlElementSyntax).StartTag.Name, XmlNameSyntax).LocalName.ValueText
End Function
Private Sub TryGetAttributes(token As SyntaxToken,
position As Integer,
items As List(Of CompletionItem),
symbol As ISymbol)
Dim tagNameSyntax As XmlNameSyntax = Nothing
Dim tagAttributes As SyntaxList(Of XmlNodeSyntax) = Nothing
Dim startTagSyntax = token.GetAncestor(Of XmlElementStartTagSyntax)()
If startTagSyntax IsNot Nothing Then
tagNameSyntax = TryCast(startTagSyntax.Name, XmlNameSyntax)
tagAttributes = startTagSyntax.Attributes
Else
Dim emptyElementSyntax = token.GetAncestor(Of XmlEmptyElementSyntax)()
If emptyElementSyntax IsNot Nothing Then
tagNameSyntax = TryCast(emptyElementSyntax.Name, XmlNameSyntax)
tagAttributes = emptyElementSyntax.Attributes
End If
End If
If tagNameSyntax IsNot Nothing Then
Dim targetToken = GetPreviousTokenIfTouchingText(token, position)
Dim tagName = tagNameSyntax.LocalName.ValueText
If targetToken.IsChildToken(Function(n As XmlNameSyntax) n.LocalName) AndAlso targetToken.Parent Is tagNameSyntax Then
' <exception |
items.AddRange(GetAttributes(tagName, tagAttributes))
End If
'<exception a|
If targetToken.IsChildToken(Function(n As XmlNameSyntax) n.LocalName) AndAlso targetToken.Parent.IsParentKind(SyntaxKind.XmlAttribute) Then
' <exception |
items.AddRange(GetAttributes(tagName, tagAttributes))
End If
'<exception a=""|
If (targetToken.IsChildToken(Function(s As XmlStringSyntax) s.EndQuoteToken) AndAlso targetToken.Parent.IsParentKind(SyntaxKind.XmlAttribute)) OrElse
targetToken.IsChildToken(Function(a As XmlNameAttributeSyntax) a.EndQuoteToken) OrElse
targetToken.IsChildToken(Function(a As XmlCrefAttributeSyntax) a.EndQuoteToken) Then
items.AddRange(GetAttributes(tagName, tagAttributes))
End If
' <param name="|"
If (targetToken.IsChildToken(Function(s As XmlStringSyntax) s.StartQuoteToken) AndAlso targetToken.Parent.IsParentKind(SyntaxKind.XmlAttribute)) OrElse
targetToken.IsChildToken(Function(a As XmlNameAttributeSyntax) a.StartQuoteToken) Then
Dim attributeName As String
Dim xmlAttributeName = targetToken.GetAncestor(Of XmlNameAttributeSyntax)()
If xmlAttributeName IsNot Nothing Then
attributeName = xmlAttributeName.Name.LocalName.ValueText
Else
attributeName = DirectCast(targetToken.GetAncestor(Of XmlAttributeSyntax)().Name, XmlNameSyntax).LocalName.ValueText
End If
items.AddRange(GetAttributeValueItems(symbol, tagName, attributeName))
End If
End If
End Sub
Protected Overrides Iterator Function GetKeywordNames() As IEnumerable(Of String)
Yield SyntaxFacts.GetText(SyntaxKind.NothingKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.SharedKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.OverridableKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.TrueKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.FalseKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.MustInheritKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.NotOverridableKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.AsyncKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.AwaitKeyword)
End Function
Protected Overrides Function GetExistingTopLevelElementNames(parentTrivia As DocumentationCommentTriviaSyntax) As IEnumerable(Of String)
Return parentTrivia.Content _
.Select(Function(node) GetElementNameAndAttributes(node).Name) _
.WhereNotNull()
End Function
Protected Overrides Function GetExistingTopLevelAttributeValues(syntax As DocumentationCommentTriviaSyntax, elementName As String, attributeName As String) As IEnumerable(Of String)
Dim attributeValues = SpecializedCollections.EmptyEnumerable(Of String)()
For Each node In syntax.Content
Dim nameAndAttributes = GetElementNameAndAttributes(node)
If nameAndAttributes.Name = elementName Then
attributeValues = attributeValues.Concat(
nameAndAttributes.Attributes _
.Where(Function(attribute) GetAttributeName(attribute) = attributeName) _
.Select(AddressOf GetAttributeValue))
End If
Next
Return attributeValues
End Function
Private Shared Function GetElementNameAndAttributes(node As XmlNodeSyntax) As (Name As String, Attributes As SyntaxList(Of XmlNodeSyntax))
Dim nameSyntax As XmlNameSyntax = Nothing
Dim attributes As SyntaxList(Of XmlNodeSyntax) = Nothing
If node.IsKind(SyntaxKind.XmlEmptyElement) Then
Dim emptyElementSyntax = DirectCast(node, XmlEmptyElementSyntax)
nameSyntax = TryCast(emptyElementSyntax.Name, XmlNameSyntax)
attributes = emptyElementSyntax.Attributes
ElseIf node.IsKind(SyntaxKind.XmlElement) Then
Dim elementSyntax = DirectCast(node, XmlElementSyntax)
nameSyntax = TryCast(elementSyntax.StartTag.Name, XmlNameSyntax)
attributes = elementSyntax.StartTag.Attributes
End If
Return (nameSyntax?.LocalName.ValueText, attributes)
End Function
Private Function GetAttributeValue(attribute As XmlNodeSyntax) As String
If TypeOf attribute Is XmlAttributeSyntax Then
' Decode any XML enities and concatentate the results
Return DirectCast(DirectCast(attribute, XmlAttributeSyntax).Value, XmlStringSyntax).TextTokens.GetValueText()
End If
Return TryCast(attribute, XmlNameAttributeSyntax)?.Reference?.Identifier.ValueText
End Function
Private Function GetAttributes(tagName As String, attributes As SyntaxList(Of XmlNodeSyntax)) As IEnumerable(Of CompletionItem)
Dim existingAttributeNames = attributes.Select(AddressOf GetAttributeName).WhereNotNull().ToSet()
Return GetAttributeItems(tagName, existingAttributeNames)
End Function
Private Shared Function GetAttributeName(node As XmlNodeSyntax) As String
Dim nameSyntax As XmlNameSyntax = node.TypeSwitch(
Function(attribute As XmlAttributeSyntax) TryCast(attribute.Name, XmlNameSyntax),
Function(attribute As XmlNameAttributeSyntax) attribute.Name,
Function(attribute As XmlCrefAttributeSyntax) attribute.Name)
Return nameSyntax?.LocalName.ValueText
End Function
Protected Overrides Function GetParameters(symbol As ISymbol) As ImmutableArray(Of IParameterSymbol)
Return symbol.GetParameters()
End Function
Private Shared ReadOnly s_defaultRules As CompletionItemRules =
CompletionItemRules.Create(
filterCharacterRules:=FilterRules,
enterKeyRule:=EnterKeyRule.Never)
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.Threading
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.ErrorReporting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities.DocumentationCommentXmlNames
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
<ExportCompletionProvider(NameOf(XmlDocCommentCompletionProvider), LanguageNames.VisualBasic)>
<ExtensionOrder(After:=NameOf(OverrideCompletionProvider))>
<[Shared]>
Friend Class XmlDocCommentCompletionProvider
Inherits AbstractDocCommentCompletionProvider(Of DocumentationCommentTriviaSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
MyBase.New(s_defaultRules)
End Sub
Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Dim isStartOfTag = text(characterPosition) = "<"c
Dim isClosingTag = (text(characterPosition) = "/"c AndAlso characterPosition > 0 AndAlso text(characterPosition - 1) = "<"c)
Dim isDoubleQuote = text(characterPosition) = """"c
Return isStartOfTag OrElse isClosingTag OrElse isDoubleQuote OrElse
IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options)
End Function
Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = ImmutableHashSet.Create("<"c, "/"c, """"c, " "c)
Public Shared Function GetPreviousTokenIfTouchingText(token As SyntaxToken, position As Integer) As SyntaxToken
Return If(token.IntersectsWith(position) AndAlso IsText(token),
token.GetPreviousToken(includeSkipped:=True),
token)
End Function
Private Shared Function IsText(token As SyntaxToken) As Boolean
Return token.IsKind(SyntaxKind.XmlNameToken, SyntaxKind.XmlTextLiteralToken, SyntaxKind.IdentifierToken)
End Function
Protected Overrides Async Function GetItemsWorkerAsync(document As Document, position As Integer, trigger As CompletionTrigger, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of CompletionItem))
Try
Dim tree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False)
Dim token = tree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments:=True)
Dim parent = token.GetAncestor(Of DocumentationCommentTriviaSyntax)()
If parent Is Nothing Then
Return Nothing
End If
' If the user is typing in xml text, don't trigger on backspace.
If token.IsKind(SyntaxKind.XmlTextLiteralToken) AndAlso
trigger.Kind = CompletionTriggerKind.Deletion Then
Return Nothing
End If
' Never provide any items inside a cref
If token.Parent.IsKind(SyntaxKind.XmlString) AndAlso token.Parent.Parent.IsKind(SyntaxKind.XmlAttribute) Then
Dim attribute = DirectCast(token.Parent.Parent, XmlAttributeSyntax)
Dim name = TryCast(attribute.Name, XmlNameSyntax)
Dim value = TryCast(attribute.Value, XmlStringSyntax)
If name?.LocalName.ValueText = CrefAttributeName AndAlso Not token = value?.EndQuoteToken Then
Return Nothing
End If
End If
If token.Parent.GetAncestor(Of XmlCrefAttributeSyntax)() IsNot Nothing Then
Return Nothing
End If
Dim items = New List(Of CompletionItem)()
Dim attachedToken = parent.ParentTrivia.Token
If attachedToken.Kind = SyntaxKind.None Then
Return items
End If
Dim declaration = attachedToken.GetAncestor(Of DeclarationStatementSyntax)()
' Maybe we're going to suggest the close tag
If token.Kind = SyntaxKind.LessThanSlashToken Then
Return GetCloseTagItem(token)
ElseIf token.IsKind(SyntaxKind.XmlNameToken) AndAlso token.GetPreviousToken().IsKind(SyntaxKind.LessThanSlashToken) Then
Return GetCloseTagItem(token.GetPreviousToken())
End If
Dim semanticModel = Await document.ReuseExistingSpeculativeModelAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(False)
Dim symbol As ISymbol = Nothing
If declaration IsNot Nothing Then
symbol = semanticModel.GetDeclaredSymbol(declaration, cancellationToken)
End If
If symbol IsNot Nothing Then
' Maybe we're going to do attribute completion
TryGetAttributes(token, position, items, symbol)
If items.Any() Then
Return items
End If
End If
If trigger.Kind = CompletionTriggerKind.Insertion AndAlso
Not trigger.Character = """"c AndAlso
Not trigger.Character = "<"c Then
' With the use of IsTriggerAfterSpaceOrStartOfWordCharacter, the code below is much
' too aggressive at suggesting tags, so exit early before degrading the experience
Return items
End If
items.AddRange(GetAlwaysVisibleItems())
Dim parentElement = token.GetAncestor(Of XmlElementSyntax)()
Dim grandParent = parentElement?.Parent
If grandParent.IsKind(SyntaxKind.XmlElement) Then
' Avoid including language keywords when following < Or <text, since these cases should only be
' attempting to complete the XML name (which for language keywords Is 'see'). The VB parser treats
' spaces after a < character as trailing whitespace, even if an identifier follows it on the same line.
' Therefore, the consistent VB experience says we never show keywords for < followed by spaces.
Dim xmlNameOnly = token.IsKind(SyntaxKind.LessThanToken) OrElse token.Parent.IsKind(SyntaxKind.XmlName)
Dim includeKeywords = Not xmlNameOnly
items.AddRange(GetNestedItems(symbol, includeKeywords))
AddXmlElementItems(items, grandParent)
ElseIf token.Parent.IsKind(SyntaxKind.XmlText) AndAlso
token.Parent.IsParentKind(SyntaxKind.DocumentationCommentTrivia) Then
' Top level, without tag:
' ''' $$
items.AddRange(GetTopLevelItems(symbol, parent))
ElseIf token.Parent.IsKind(SyntaxKind.XmlText) AndAlso
token.Parent.Parent.IsKind(SyntaxKind.XmlElement) Then
items.AddRange(GetNestedItems(symbol, includeKeywords:=True))
Dim xmlElement = token.Parent.Parent
AddXmlElementItems(items, xmlElement)
ElseIf grandParent.IsKind(SyntaxKind.DocumentationCommentTrivia) Then
' Top level, with tag:
' ''' <$$
' ''' <tag$$
items.AddRange(GetTopLevelItems(symbol, parent))
End If
If token.Parent.IsKind(SyntaxKind.XmlElementStartTag, SyntaxKind.XmlName) AndAlso
parentElement.IsParentKind(SyntaxKind.XmlElement) Then
AddXmlElementItems(items, parentElement.Parent)
End If
Return items
Catch e As Exception When FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)
Return SpecializedCollections.EmptyEnumerable(Of CompletionItem)
End Try
End Function
Private Sub AddXmlElementItems(items As List(Of CompletionItem), xmlElement As SyntaxNode)
Dim startTagName = GetStartTagName(xmlElement)
If startTagName = ListElementName Then
items.AddRange(GetListItems())
ElseIf startTagName = ListHeaderElementName Then
items.AddRange(GetListHeaderItems())
ElseIf startTagName = ItemElementName Then
items.AddRange(GetItemTagItems())
End If
End Sub
Private Function GetCloseTagItem(token As SyntaxToken) As IEnumerable(Of CompletionItem)
Dim endTag = TryCast(token.Parent, XmlElementEndTagSyntax)
If endTag Is Nothing Then
Return Nothing
End If
Dim element = TryCast(endTag.Parent, XmlElementSyntax)
If element Is Nothing Then
Return Nothing
End If
Dim startElement = element.StartTag
Dim name = TryCast(startElement.Name, XmlNameSyntax)
If name Is Nothing Then
Return Nothing
End If
Dim nameToken = name.LocalName
If Not nameToken.IsMissing AndAlso nameToken.ValueText.Length > 0 Then
Return SpecializedCollections.SingletonEnumerable(CreateCompletionItem(nameToken.ValueText, nameToken.ValueText & ">", String.Empty))
End If
Return Nothing
End Function
Private Shared Function GetStartTagName(element As SyntaxNode) As String
Return DirectCast(DirectCast(element, XmlElementSyntax).StartTag.Name, XmlNameSyntax).LocalName.ValueText
End Function
Private Sub TryGetAttributes(token As SyntaxToken,
position As Integer,
items As List(Of CompletionItem),
symbol As ISymbol)
Dim tagNameSyntax As XmlNameSyntax = Nothing
Dim tagAttributes As SyntaxList(Of XmlNodeSyntax) = Nothing
Dim startTagSyntax = token.GetAncestor(Of XmlElementStartTagSyntax)()
If startTagSyntax IsNot Nothing Then
tagNameSyntax = TryCast(startTagSyntax.Name, XmlNameSyntax)
tagAttributes = startTagSyntax.Attributes
Else
Dim emptyElementSyntax = token.GetAncestor(Of XmlEmptyElementSyntax)()
If emptyElementSyntax IsNot Nothing Then
tagNameSyntax = TryCast(emptyElementSyntax.Name, XmlNameSyntax)
tagAttributes = emptyElementSyntax.Attributes
End If
End If
If tagNameSyntax IsNot Nothing Then
Dim targetToken = GetPreviousTokenIfTouchingText(token, position)
Dim tagName = tagNameSyntax.LocalName.ValueText
If targetToken.IsChildToken(Function(n As XmlNameSyntax) n.LocalName) AndAlso targetToken.Parent Is tagNameSyntax Then
' <exception |
items.AddRange(GetAttributes(tagName, tagAttributes))
End If
'<exception a|
If targetToken.IsChildToken(Function(n As XmlNameSyntax) n.LocalName) AndAlso targetToken.Parent.IsParentKind(SyntaxKind.XmlAttribute) Then
' <exception |
items.AddRange(GetAttributes(tagName, tagAttributes))
End If
'<exception a=""|
If (targetToken.IsChildToken(Function(s As XmlStringSyntax) s.EndQuoteToken) AndAlso targetToken.Parent.IsParentKind(SyntaxKind.XmlAttribute)) OrElse
targetToken.IsChildToken(Function(a As XmlNameAttributeSyntax) a.EndQuoteToken) OrElse
targetToken.IsChildToken(Function(a As XmlCrefAttributeSyntax) a.EndQuoteToken) Then
items.AddRange(GetAttributes(tagName, tagAttributes))
End If
' <param name="|"
If (targetToken.IsChildToken(Function(s As XmlStringSyntax) s.StartQuoteToken) AndAlso targetToken.Parent.IsParentKind(SyntaxKind.XmlAttribute)) OrElse
targetToken.IsChildToken(Function(a As XmlNameAttributeSyntax) a.StartQuoteToken) Then
Dim attributeName As String
Dim xmlAttributeName = targetToken.GetAncestor(Of XmlNameAttributeSyntax)()
If xmlAttributeName IsNot Nothing Then
attributeName = xmlAttributeName.Name.LocalName.ValueText
Else
attributeName = DirectCast(targetToken.GetAncestor(Of XmlAttributeSyntax)().Name, XmlNameSyntax).LocalName.ValueText
End If
items.AddRange(GetAttributeValueItems(symbol, tagName, attributeName))
End If
End If
End Sub
Protected Overrides Iterator Function GetKeywordNames() As IEnumerable(Of String)
Yield SyntaxFacts.GetText(SyntaxKind.NothingKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.SharedKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.OverridableKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.TrueKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.FalseKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.MustInheritKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.NotOverridableKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.AsyncKeyword)
Yield SyntaxFacts.GetText(SyntaxKind.AwaitKeyword)
End Function
Protected Overrides Function GetExistingTopLevelElementNames(parentTrivia As DocumentationCommentTriviaSyntax) As IEnumerable(Of String)
Return parentTrivia.Content _
.Select(Function(node) GetElementNameAndAttributes(node).Name) _
.WhereNotNull()
End Function
Protected Overrides Function GetExistingTopLevelAttributeValues(syntax As DocumentationCommentTriviaSyntax, elementName As String, attributeName As String) As IEnumerable(Of String)
Dim attributeValues = SpecializedCollections.EmptyEnumerable(Of String)()
For Each node In syntax.Content
Dim nameAndAttributes = GetElementNameAndAttributes(node)
If nameAndAttributes.Name = elementName Then
attributeValues = attributeValues.Concat(
nameAndAttributes.Attributes _
.Where(Function(attribute) GetAttributeName(attribute) = attributeName) _
.Select(AddressOf GetAttributeValue))
End If
Next
Return attributeValues
End Function
Private Shared Function GetElementNameAndAttributes(node As XmlNodeSyntax) As (Name As String, Attributes As SyntaxList(Of XmlNodeSyntax))
Dim nameSyntax As XmlNameSyntax = Nothing
Dim attributes As SyntaxList(Of XmlNodeSyntax) = Nothing
If node.IsKind(SyntaxKind.XmlEmptyElement) Then
Dim emptyElementSyntax = DirectCast(node, XmlEmptyElementSyntax)
nameSyntax = TryCast(emptyElementSyntax.Name, XmlNameSyntax)
attributes = emptyElementSyntax.Attributes
ElseIf node.IsKind(SyntaxKind.XmlElement) Then
Dim elementSyntax = DirectCast(node, XmlElementSyntax)
nameSyntax = TryCast(elementSyntax.StartTag.Name, XmlNameSyntax)
attributes = elementSyntax.StartTag.Attributes
End If
Return (nameSyntax?.LocalName.ValueText, attributes)
End Function
Private Function GetAttributeValue(attribute As XmlNodeSyntax) As String
If TypeOf attribute Is XmlAttributeSyntax Then
' Decode any XML enities and concatentate the results
Return DirectCast(DirectCast(attribute, XmlAttributeSyntax).Value, XmlStringSyntax).TextTokens.GetValueText()
End If
Return TryCast(attribute, XmlNameAttributeSyntax)?.Reference?.Identifier.ValueText
End Function
Private Function GetAttributes(tagName As String, attributes As SyntaxList(Of XmlNodeSyntax)) As IEnumerable(Of CompletionItem)
Dim existingAttributeNames = attributes.Select(AddressOf GetAttributeName).WhereNotNull().ToSet()
Return GetAttributeItems(tagName, existingAttributeNames)
End Function
Private Shared Function GetAttributeName(node As XmlNodeSyntax) As String
Dim nameSyntax As XmlNameSyntax = node.TypeSwitch(
Function(attribute As XmlAttributeSyntax) TryCast(attribute.Name, XmlNameSyntax),
Function(attribute As XmlNameAttributeSyntax) attribute.Name,
Function(attribute As XmlCrefAttributeSyntax) attribute.Name)
Return nameSyntax?.LocalName.ValueText
End Function
Protected Overrides Function GetParameters(symbol As ISymbol) As ImmutableArray(Of IParameterSymbol)
Return symbol.GetParameters()
End Function
Private Shared ReadOnly s_defaultRules As CompletionItemRules =
CompletionItemRules.Create(
filterCharacterRules:=FilterRules,
enterKeyRule:=EnterKeyRule.Never)
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,875 | Clear dependency information from unused references after analysis | Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | JoeRobich | 2021-08-25T00:30:36Z | 2021-08-25T21:20:39Z | f6a6e02e66884d465b8a0ca2e827bede0d66e634 | e9ed046c159bfc5caf33b875ab6928a73c5601f3 | Clear dependency information from unused references after analysis. Resolves #55869
We will no longer be serializing the reference dependencies when returning results from OOP. | ./src/Compilers/VisualBasic/Portable/Symbols/Retargeting/RetargetingPropertySymbol.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.Globalization
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting
Friend NotInheritable Class RetargetingPropertySymbol
Inherits PropertySymbol
''' <summary>
''' Owning RetargetingModuleSymbol.
''' </summary>
Private ReadOnly _retargetingModule As RetargetingModuleSymbol
''' <summary>
''' The underlying PropertySymbol, cannot be another RetargetingPropertySymbol.
''' </summary>
Private ReadOnly _underlyingProperty As PropertySymbol
Private _lazyParameters As ImmutableArray(Of ParameterSymbol)
Private _lazyCustomModifiers As CustomModifiersTuple
''' <summary>
''' Retargeted custom attributes
''' </summary>
''' <remarks></remarks>
Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData)
Private _lazyExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol)
Private _lazyCachedUseSiteInfo As CachedUseSiteInfo(Of AssemblySymbol) = CachedUseSiteInfo(Of AssemblySymbol).Uninitialized ' Indicates unknown state.
Public Sub New(retargetingModule As RetargetingModuleSymbol, underlyingProperty As PropertySymbol)
Debug.Assert(retargetingModule IsNot Nothing)
Debug.Assert(underlyingProperty IsNot Nothing)
If TypeOf underlyingProperty Is RetargetingPropertySymbol Then
Throw New ArgumentException()
End If
_retargetingModule = retargetingModule
_underlyingProperty = underlyingProperty
End Sub
Private ReadOnly Property RetargetingTranslator As RetargetingModuleSymbol.RetargetingSymbolTranslator
Get
Return _retargetingModule.RetargetingTranslator
End Get
End Property
Public ReadOnly Property UnderlyingProperty As PropertySymbol
Get
Return _underlyingProperty
End Get
End Property
Public ReadOnly Property RetargetingModule As RetargetingModuleSymbol
Get
Return _retargetingModule
End Get
End Property
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return _underlyingProperty.IsImplicitlyDeclared
End Get
End Property
Public Overrides ReadOnly Property IsWithEvents As Boolean
Get
Return _underlyingProperty.IsWithEvents
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return RetargetingTranslator.Retarget(_underlyingProperty.ContainingSymbol)
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return _underlyingProperty.DeclaredAccessibility
End Get
End Property
Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
Return RetargetingTranslator.GetRetargetedAttributes(_underlyingProperty, _lazyCustomAttributes)
End Function
Friend Overrides Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData)
Return RetargetingTranslator.RetargetAttributes(_underlyingProperty.GetCustomAttributesToEmit(compilationState))
End Function
Public Overrides ReadOnly Property GetMethod As MethodSymbol
Get
Return If(_underlyingProperty.GetMethod Is Nothing, Nothing, RetargetingTranslator.Retarget(_underlyingProperty.GetMethod))
End Get
End Property
Public Overrides ReadOnly Property SetMethod As MethodSymbol
Get
Return If(_underlyingProperty.SetMethod Is Nothing, Nothing, RetargetingTranslator.Retarget(_underlyingProperty.SetMethod))
End Get
End Property
Friend Overrides ReadOnly Property AssociatedField As FieldSymbol
Get
Return If(_underlyingProperty.AssociatedField Is Nothing, Nothing, RetargetingTranslator.Retarget(_underlyingProperty.AssociatedField))
End Get
End Property
Public Overrides ReadOnly Property IsDefault As Boolean
Get
Return _underlyingProperty.IsDefault
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return _underlyingProperty.IsMustOverride
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return _underlyingProperty.IsNotOverridable
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return _underlyingProperty.IsOverridable
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return _underlyingProperty.IsOverrides
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return _underlyingProperty.IsOverloads
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return _underlyingProperty.IsShared
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _underlyingProperty.Name
End Get
End Property
Public Overrides ReadOnly Property MetadataName As String
Get
Return _underlyingProperty.MetadataName
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return _underlyingProperty.HasSpecialName
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return _underlyingProperty.ObsoleteAttributeData
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _underlyingProperty.Locations
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return _underlyingProperty.DeclaringSyntaxReferences
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
If _lazyParameters.IsDefault Then
ImmutableInterlocked.InterlockedCompareExchange(_lazyParameters, RetargetParameters(), Nothing)
End If
Return _lazyParameters
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return _underlyingProperty.ParameterCount
End Get
End Property
Private Function RetargetParameters() As ImmutableArray(Of ParameterSymbol)
Dim list = _underlyingProperty.Parameters
Dim count = list.Length
If count = 0 Then
Return ImmutableArray(Of ParameterSymbol).Empty
Else
Dim parameters = New ParameterSymbol(count - 1) {}
For i As Integer = 0 To count - 1
parameters(i) = RetargetingParameterSymbol.CreatePropertyParameter(Me, list(i))
Next
Return parameters.AsImmutableOrNull()
End If
End Function
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return _underlyingProperty.ReturnsByRef
End Get
End Property
Public Overrides ReadOnly Property Type As TypeSymbol
Get
Return RetargetingTranslator.Retarget(_underlyingProperty.Type, RetargetOptions.RetargetPrimitiveTypesByTypeCode)
End Get
End Property
Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return CustomModifiersTuple.TypeCustomModifiers
End Get
End Property
Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return CustomModifiersTuple.RefCustomModifiers
End Get
End Property
Private ReadOnly Property CustomModifiersTuple As CustomModifiersTuple
Get
Return RetargetingTranslator.RetargetModifiers(_underlyingProperty.TypeCustomModifiers, _underlyingProperty.RefCustomModifiers, _lazyCustomModifiers)
End Get
End Property
Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention
Get
Return _underlyingProperty.CallingConvention
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol)
Get
If _lazyExplicitInterfaceImplementations.IsDefault Then
ImmutableInterlocked.InterlockedCompareExchange(
_lazyExplicitInterfaceImplementations,
Me.RetargetExplicitInterfaceImplementations(),
Nothing)
End If
Return _lazyExplicitInterfaceImplementations
End Get
End Property
Private Function RetargetExplicitInterfaceImplementations() As ImmutableArray(Of PropertySymbol)
Dim impls = Me.UnderlyingProperty.ExplicitInterfaceImplementations
If impls.IsEmpty Then
Return impls
End If
Dim builder = ArrayBuilder(Of PropertySymbol).GetInstance()
For i = 0 To impls.Length - 1
Dim retargeted = Me.RetargetingModule.RetargetingTranslator.Retarget(impls(i), PropertySignatureComparer.RetargetedExplicitPropertyImplementationComparer)
If retargeted IsNot Nothing Then
builder.Add(retargeted)
End If
Next
Return builder.ToImmutableAndFree()
End Function
Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol)
Dim primaryDependency As AssemblySymbol = Me.PrimaryDependency
If Not _lazyCachedUseSiteInfo.IsInitialized Then
_lazyCachedUseSiteInfo.Initialize(primaryDependency, CalculateUseSiteInfo())
End If
Return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency)
End Function
Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean
Get
Return _underlyingProperty.IsMyGroupCollectionProperty
End Get
End Property
Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean
Get
Return _underlyingProperty.HasRuntimeSpecialName
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 GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String
Return _underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken)
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.Globalization
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting
Friend NotInheritable Class RetargetingPropertySymbol
Inherits PropertySymbol
''' <summary>
''' Owning RetargetingModuleSymbol.
''' </summary>
Private ReadOnly _retargetingModule As RetargetingModuleSymbol
''' <summary>
''' The underlying PropertySymbol, cannot be another RetargetingPropertySymbol.
''' </summary>
Private ReadOnly _underlyingProperty As PropertySymbol
Private _lazyParameters As ImmutableArray(Of ParameterSymbol)
Private _lazyCustomModifiers As CustomModifiersTuple
''' <summary>
''' Retargeted custom attributes
''' </summary>
''' <remarks></remarks>
Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData)
Private _lazyExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol)
Private _lazyCachedUseSiteInfo As CachedUseSiteInfo(Of AssemblySymbol) = CachedUseSiteInfo(Of AssemblySymbol).Uninitialized ' Indicates unknown state.
Public Sub New(retargetingModule As RetargetingModuleSymbol, underlyingProperty As PropertySymbol)
Debug.Assert(retargetingModule IsNot Nothing)
Debug.Assert(underlyingProperty IsNot Nothing)
If TypeOf underlyingProperty Is RetargetingPropertySymbol Then
Throw New ArgumentException()
End If
_retargetingModule = retargetingModule
_underlyingProperty = underlyingProperty
End Sub
Private ReadOnly Property RetargetingTranslator As RetargetingModuleSymbol.RetargetingSymbolTranslator
Get
Return _retargetingModule.RetargetingTranslator
End Get
End Property
Public ReadOnly Property UnderlyingProperty As PropertySymbol
Get
Return _underlyingProperty
End Get
End Property
Public ReadOnly Property RetargetingModule As RetargetingModuleSymbol
Get
Return _retargetingModule
End Get
End Property
Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean
Get
Return _underlyingProperty.IsImplicitlyDeclared
End Get
End Property
Public Overrides ReadOnly Property IsWithEvents As Boolean
Get
Return _underlyingProperty.IsWithEvents
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return RetargetingTranslator.Retarget(_underlyingProperty.ContainingSymbol)
End Get
End Property
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return _underlyingProperty.DeclaredAccessibility
End Get
End Property
Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
Return RetargetingTranslator.GetRetargetedAttributes(_underlyingProperty, _lazyCustomAttributes)
End Function
Friend Overrides Function GetCustomAttributesToEmit(compilationState As ModuleCompilationState) As IEnumerable(Of VisualBasicAttributeData)
Return RetargetingTranslator.RetargetAttributes(_underlyingProperty.GetCustomAttributesToEmit(compilationState))
End Function
Public Overrides ReadOnly Property GetMethod As MethodSymbol
Get
Return If(_underlyingProperty.GetMethod Is Nothing, Nothing, RetargetingTranslator.Retarget(_underlyingProperty.GetMethod))
End Get
End Property
Public Overrides ReadOnly Property SetMethod As MethodSymbol
Get
Return If(_underlyingProperty.SetMethod Is Nothing, Nothing, RetargetingTranslator.Retarget(_underlyingProperty.SetMethod))
End Get
End Property
Friend Overrides ReadOnly Property AssociatedField As FieldSymbol
Get
Return If(_underlyingProperty.AssociatedField Is Nothing, Nothing, RetargetingTranslator.Retarget(_underlyingProperty.AssociatedField))
End Get
End Property
Public Overrides ReadOnly Property IsDefault As Boolean
Get
Return _underlyingProperty.IsDefault
End Get
End Property
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return _underlyingProperty.IsMustOverride
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return _underlyingProperty.IsNotOverridable
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return _underlyingProperty.IsOverridable
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return _underlyingProperty.IsOverrides
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return _underlyingProperty.IsOverloads
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return _underlyingProperty.IsShared
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return _underlyingProperty.Name
End Get
End Property
Public Overrides ReadOnly Property MetadataName As String
Get
Return _underlyingProperty.MetadataName
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return _underlyingProperty.HasSpecialName
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return _underlyingProperty.ObsoleteAttributeData
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _underlyingProperty.Locations
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return _underlyingProperty.DeclaringSyntaxReferences
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
If _lazyParameters.IsDefault Then
ImmutableInterlocked.InterlockedCompareExchange(_lazyParameters, RetargetParameters(), Nothing)
End If
Return _lazyParameters
End Get
End Property
Public Overrides ReadOnly Property ParameterCount As Integer
Get
Return _underlyingProperty.ParameterCount
End Get
End Property
Private Function RetargetParameters() As ImmutableArray(Of ParameterSymbol)
Dim list = _underlyingProperty.Parameters
Dim count = list.Length
If count = 0 Then
Return ImmutableArray(Of ParameterSymbol).Empty
Else
Dim parameters = New ParameterSymbol(count - 1) {}
For i As Integer = 0 To count - 1
parameters(i) = RetargetingParameterSymbol.CreatePropertyParameter(Me, list(i))
Next
Return parameters.AsImmutableOrNull()
End If
End Function
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return _underlyingProperty.ReturnsByRef
End Get
End Property
Public Overrides ReadOnly Property Type As TypeSymbol
Get
Return RetargetingTranslator.Retarget(_underlyingProperty.Type, RetargetOptions.RetargetPrimitiveTypesByTypeCode)
End Get
End Property
Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return CustomModifiersTuple.TypeCustomModifiers
End Get
End Property
Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return CustomModifiersTuple.RefCustomModifiers
End Get
End Property
Private ReadOnly Property CustomModifiersTuple As CustomModifiersTuple
Get
Return RetargetingTranslator.RetargetModifiers(_underlyingProperty.TypeCustomModifiers, _underlyingProperty.RefCustomModifiers, _lazyCustomModifiers)
End Get
End Property
Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention
Get
Return _underlyingProperty.CallingConvention
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol)
Get
If _lazyExplicitInterfaceImplementations.IsDefault Then
ImmutableInterlocked.InterlockedCompareExchange(
_lazyExplicitInterfaceImplementations,
Me.RetargetExplicitInterfaceImplementations(),
Nothing)
End If
Return _lazyExplicitInterfaceImplementations
End Get
End Property
Private Function RetargetExplicitInterfaceImplementations() As ImmutableArray(Of PropertySymbol)
Dim impls = Me.UnderlyingProperty.ExplicitInterfaceImplementations
If impls.IsEmpty Then
Return impls
End If
Dim builder = ArrayBuilder(Of PropertySymbol).GetInstance()
For i = 0 To impls.Length - 1
Dim retargeted = Me.RetargetingModule.RetargetingTranslator.Retarget(impls(i), PropertySignatureComparer.RetargetedExplicitPropertyImplementationComparer)
If retargeted IsNot Nothing Then
builder.Add(retargeted)
End If
Next
Return builder.ToImmutableAndFree()
End Function
Friend Overrides Function GetUseSiteInfo() As UseSiteInfo(Of AssemblySymbol)
Dim primaryDependency As AssemblySymbol = Me.PrimaryDependency
If Not _lazyCachedUseSiteInfo.IsInitialized Then
_lazyCachedUseSiteInfo.Initialize(primaryDependency, CalculateUseSiteInfo())
End If
Return _lazyCachedUseSiteInfo.ToUseSiteInfo(primaryDependency)
End Function
Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean
Get
Return _underlyingProperty.IsMyGroupCollectionProperty
End Get
End Property
Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean
Get
Return _underlyingProperty.HasRuntimeSpecialName
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 GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String
Return _underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken)
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/CSharp/Portable/Emitter/Model/PEModuleBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState>
{
// TODO: Need to estimate amount of elements for this map and pass that value to the constructor.
protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>();
private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>(Symbols.SymbolEqualityComparer.ConsiderEverything);
private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>();
private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt;
public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt
=> _embeddedTypesManagerOpt;
// Gives the name of this module (may not reflect the name of the underlying symbol).
// See Assembly.MetadataName.
private readonly string _metadataName;
private ImmutableArray<Cci.ExportedType> _lazyExportedTypes;
/// <summary>
/// The compiler-generated implementation type for each fixed-size buffer.
/// </summary>
private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes;
private int _needsGeneratedAttributes;
private bool _needsGeneratedAttributes_IsFrozen;
/// <summary>
/// Returns a value indicating which embedded attributes should be generated during emit phase.
/// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it.
/// Freezing is needed to make sure that nothing tries to modify the value after the value is read.
/// </summary>
internal EmbeddableAttributes GetNeedsGeneratedAttributes()
{
_needsGeneratedAttributes_IsFrozen = true;
return GetNeedsGeneratedAttributesInternal();
}
private EmbeddableAttributes GetNeedsGeneratedAttributesInternal()
{
return (EmbeddableAttributes)_needsGeneratedAttributes | Compilation.GetNeedsGeneratedAttributes();
}
private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes)
{
Debug.Assert(!_needsGeneratedAttributes_IsFrozen);
ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes);
}
internal PEModuleBuilder(
SourceModuleSymbol sourceModule,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources)
: base(sourceModule.ContainingSourceAssembly.DeclaringCompilation,
sourceModule,
serializationProperties,
manifestResources,
outputKind,
emitOptions,
new ModuleCompilationState())
{
var specifiedName = sourceModule.MetadataName;
_metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ?
specifiedName :
emitOptions.OutputNameOverride ?? specifiedName;
AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this);
if (sourceModule.AnyReferencedAssembliesAreLinked)
{
_embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this);
}
}
public override string Name
{
get { return _metadataName; }
}
internal sealed override string ModuleName
{
get { return _metadataName; }
}
internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor)
{
return Compilation.TrySynthesizeAttribute(attributeConstructor);
}
public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly)
{
return SourceModule.ContainingSourceAssembly
.GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule());
}
public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes()
{
return SourceModule.ContainingSourceAssembly.GetSecurityAttributes();
}
public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes()
{
return SourceModule.GetCustomAttributesToEmit(this);
}
internal sealed override AssemblySymbol CorLibrary
{
get { return SourceModule.ContainingSourceAssembly.CorLibrary; }
}
public sealed override bool GenerateVisualBasicStylePdb => false;
// C# doesn't emit linked assembly names into PDBs.
public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>();
// C# currently doesn't emit compilation level imports (TODO: scripting).
public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty;
// C# doesn't allow to define default namespace for compilation.
public sealed override string DefaultNamespace => null;
protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics)
{
ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules;
for (int i = 1; i < modules.Length; i++)
{
foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols())
{
yield return Translate(aRef, diagnostics);
}
}
}
private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics)
{
AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity;
AssemblyIdentity refIdentity = asmRef.Identity;
if (asmIdentity.IsStrongName && !refIdentity.IsStrongName &&
asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime)
{
// Dev12 reported error, we have changed it to a warning to allow referencing libraries
// built for platforms that don't support strong names.
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton);
}
if (OutputKind != OutputKind.NetModule &&
!string.IsNullOrEmpty(refIdentity.CultureName) &&
!string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase))
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton);
}
var refMachine = assembly.Machine;
// If other assembly is agnostic this is always safe
// Also, if no mscorlib was specified for back compat we add a reference to mscorlib
// that resolves to the current framework directory. If the compiler is 64-bit
// this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is
// specified. A reference to the default mscorlib should always succeed without
// warning so we ignore it here.
if ((object)assembly != (object)assembly.CorLibrary &&
!(refMachine == Machine.I386 && !assembly.Bit32Required))
{
var machine = SourceModule.Machine;
if (!(machine == Machine.I386 && !SourceModule.Bit32Required) &&
machine != refMachine)
{
// Different machine types, and neither is agnostic
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton);
}
}
if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen)
{
_embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics);
}
}
internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container)
{
return null;
}
public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap()
{
var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>();
var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>();
namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace);
Location location = null;
while (namespacesAndTypesToProcess.Count > 0)
{
NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop();
switch (symbol.Kind)
{
case SymbolKind.Namespace:
location = GetSmallestSourceLocationOrNull(symbol);
// filtering out synthesized symbols not having real source
// locations such as anonymous types, etc...
if (location != null)
{
foreach (var member in symbol.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.Namespace:
case SymbolKind.NamedType:
namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member);
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
}
break;
case SymbolKind.NamedType:
location = GetSmallestSourceLocationOrNull(symbol);
if (location != null)
{
// add this named type location
AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter());
foreach (var member in symbol.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.NamedType:
namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member);
break;
case SymbolKind.Method:
// NOTE: Dev11 does not add synthesized static constructors to this map,
// but adds synthesized instance constructors, Roslyn adds both
var method = (MethodSymbol)member;
if (!method.ShouldEmit())
{
break;
}
AddSymbolLocation(result, member);
break;
case SymbolKind.Property:
AddSymbolLocation(result, member);
break;
case SymbolKind.Field:
if (member is TupleErrorFieldSymbol)
{
break;
}
// NOTE: Dev11 does not add synthesized backing fields for properties,
// but adds backing fields for events, Roslyn adds both
AddSymbolLocation(result, member);
break;
case SymbolKind.Event:
AddSymbolLocation(result, member);
// event backing fields do not show up in GetMembers
{
FieldSymbol field = ((EventSymbol)member).AssociatedField;
if ((object)field != null)
{
AddSymbolLocation(result, field);
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
return result;
}
private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol)
{
var location = GetSmallestSourceLocationOrNull(symbol);
if (location != null)
{
AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter());
}
}
private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition)
{
FileLinePositionSpan span = location.GetLineSpan();
Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath);
if (doc != null)
{
result.Add(doc,
new Cci.DefinitionWithLocation(
definition,
span.StartLinePosition.Line,
span.StartLinePosition.Character,
span.EndLinePosition.Line,
span.EndLinePosition.Character));
}
}
private Location GetSmallestSourceLocationOrNull(Symbol symbol)
{
CSharpCompilation compilation = symbol.DeclaringCompilation;
Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?");
Location result = null;
foreach (var loc in symbol.Locations)
{
if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0))
{
result = loc;
}
}
return result;
}
/// <summary>
/// Ignore accessibility when resolving well-known type
/// members, in particular for generic type arguments
/// (e.g.: binding to internal types in the EE).
/// </summary>
internal virtual bool IgnoreAccessibility => false;
/// <summary>
/// Override the dynamic operation context type for all dynamic calls in the module.
/// </summary>
internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType)
{
return contextType;
}
internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics)
{
return null;
}
internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes()
{
return ImmutableArray<AnonymousTypeKey>.Empty;
}
internal virtual int GetNextAnonymousTypeIndex()
{
return 0;
}
internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index)
{
Debug.Assert(Compilation == template.DeclaringCompilation);
name = null;
index = -1;
return false;
}
public sealed override IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context)
{
if (context.MetadataOnly)
{
return SpecializedCollections.EmptyEnumerable<Cci.INamespaceTypeDefinition>();
}
return Compilation.AnonymousTypeManager.GetAllCreatedTemplates()
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context)
{
var namespacesToProcess = new Stack<NamespaceSymbol>();
namespacesToProcess.Push(SourceModule.GlobalNamespace);
while (namespacesToProcess.Count > 0)
{
var ns = namespacesToProcess.Pop();
foreach (var member in ns.GetMembers())
{
if (member.Kind == SymbolKind.Namespace)
{
namespacesToProcess.Push((NamespaceSymbol)member);
}
else
{
yield return ((NamedTypeSymbol)member).GetCciAdapter();
}
}
}
}
private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder)
{
int index;
if (symbol.Kind == SymbolKind.NamedType)
{
if (symbol.DeclaredAccessibility != Accessibility.Public)
{
return;
}
Debug.Assert(symbol.IsDefinition);
index = builder.Count;
builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol.GetCciAdapter(), parentIndex, isForwarder: false));
}
else
{
index = -1;
}
foreach (var member in symbol.GetMembers())
{
var namespaceOrType = member as NamespaceOrTypeSymbol;
if ((object)namespaceOrType != null)
{
GetExportedTypes(namespaceOrType, index, builder);
}
}
}
public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics)
{
Debug.Assert(HaveDeterminedTopLevelTypes);
if (_lazyExportedTypes.IsDefault)
{
_lazyExportedTypes = CalculateExportedTypes();
if (_lazyExportedTypes.Length > 0)
{
ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics);
}
}
return _lazyExportedTypes;
}
/// <summary>
/// Builds an array of public type symbols defined in netmodules included in the compilation
/// and type forwarders defined in this compilation or any included netmodule (in this order).
/// </summary>
private ImmutableArray<Cci.ExportedType> CalculateExportedTypes()
{
SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly;
var builder = ArrayBuilder<Cci.ExportedType>.GetInstance();
if (!OutputKind.IsNetModule())
{
var modules = sourceAssembly.Modules;
for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0]
{
GetExportedTypes(modules[i].GlobalNamespace, -1, builder);
}
}
Debug.Assert(OutputKind.IsNetModule() == sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule());
GetForwardedTypes(sourceAssembly, builder);
return builder.ToImmutableAndFree();
}
#nullable enable
/// <summary>
/// Returns a set of top-level forwarded types
/// </summary>
internal static HashSet<NamedTypeSymbol> GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder<Cci.ExportedType>? builder)
{
var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>();
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder);
if (!sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule())
{
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder);
}
return seenTopLevelForwardedTypes;
}
#nullable disable
private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics)
{
var sourceAssembly = SourceModule.ContainingSourceAssembly;
var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance);
foreach (var exportedType in exportedTypes)
{
var type = (NamedTypeSymbol)exportedType.Type.GetInternalSymbol();
Debug.Assert(type.IsDefinition);
if (!type.IsTopLevelType())
{
continue;
}
// exported types are not emitted in EnC deltas (hence generation 0):
string fullEmittedName = MetadataHelpers.BuildQualifiedName(
((Cci.INamespaceTypeReference)type.GetCciAdapter()).NamespaceName,
Cci.MetadataWriter.GetMangledName(type.GetCciAdapter(), generation: 0));
// First check against types declared in the primary module
if (ContainsTopLevelType(fullEmittedName))
{
if ((object)type.ContainingAssembly == sourceAssembly)
{
diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule);
}
else
{
diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type);
}
continue;
}
NamedTypeSymbol contender;
// Now check against other exported types
if (exportedNamesMap.TryGetValue(fullEmittedName, out contender))
{
if ((object)type.ContainingAssembly == sourceAssembly)
{
// all exported types precede forwarded types, therefore contender cannot be a forwarded type.
Debug.Assert(contender.ContainingAssembly == sourceAssembly);
diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule);
}
else if ((object)contender.ContainingAssembly == sourceAssembly)
{
// Forwarded type conflicts with exported type
diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule);
}
else
{
// Forwarded type conflicts with another forwarded type
diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly);
}
continue;
}
exportedNamesMap.Add(fullEmittedName, type);
}
}
#nullable enable
private static void GetForwardedTypes(
HashSet<NamedTypeSymbol> seenTopLevelTypes,
CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData,
ArrayBuilder<Cci.ExportedType>? builder)
{
if (wellKnownAttributeData?.ForwardedTypes?.Count > 0)
{
// (type, index of the parent exported type in builder, or -1 if the type is a top-level type)
var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance();
// Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names.
IEnumerable<NamedTypeSymbol> orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes;
if (builder is object)
{
orderedForwardedTypes = orderedForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat));
}
foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes)
{
NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition;
Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?");
// Since we need to allow multiple constructions of the same generic type at the source
// level, we need to de-dup the original definitions before emitting.
if (!seenTopLevelTypes.Add(originalDefinition)) continue;
if (builder is object)
{
// Return all nested types.
// Note the order: depth first, children in reverse order (to match dev10, not a requirement).
Debug.Assert(stack.Count == 0);
stack.Push((originalDefinition, -1));
while (stack.Count > 0)
{
var (type, parentIndex) = stack.Pop();
// In general, we don't want private types to appear in the ExportedTypes table.
// BREAK: dev11 emits these types. The problem was discovered in dev10, but failed
// to meet the bar Bug: Dev10/258038 and was left as-is.
if (type.DeclaredAccessibility == Accessibility.Private)
{
// NOTE: this will also exclude nested types of type
continue;
}
// NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection.
int index = builder.Count;
builder.Add(new Cci.ExportedType(type.GetCciAdapter(), parentIndex, isForwarder: true));
// Iterate backwards so they get popped in forward order.
ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered.
for (int i = nested.Length - 1; i >= 0; i--)
{
stack.Push((nested[i], index));
}
}
}
}
stack.Free();
}
}
#nullable disable
internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar()
{
foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols())
{
if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a))
{
yield return a;
}
}
}
private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
Debug.Assert(diagnostics != null);
var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType);
DiagnosticInfo info = typeSymbol.GetUseSiteInfo().DiagnosticInfo;
if (info != null)
{
Symbol.ReportUseSiteDiagnostic(info,
diagnostics,
syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton);
}
return typeSymbol;
}
internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics),
diagnostics: diagnostics,
syntaxNodeOpt: syntaxNodeOpt,
needDeclaration: true);
}
public sealed override Cci.IMethodReference GetInitArrayHelper()
{
return ((MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle))?.GetCciAdapter();
}
public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType)
{
var namedType = typeRef.GetInternalSymbol() as NamedTypeSymbol;
if ((object)namedType != null)
{
if (platformType == Cci.PlatformType.SystemType)
{
return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type);
}
return namedType.SpecialType == (SpecialType)platformType;
}
return false;
}
protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context)
{
AssemblySymbol corLibrary = CorLibrary;
if (!corLibrary.IsMissing &&
!corLibrary.IsLinked &&
!ReferenceEquals(corLibrary, SourceModule.ContainingAssembly))
{
return Translate(corLibrary, context.Diagnostics);
}
return null;
}
internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics)
{
if (ReferenceEquals(SourceModule.ContainingAssembly, assembly))
{
return (Cci.IAssemblyReference)this;
}
Cci.IModuleReference reference;
if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference))
{
return (Cci.IAssemblyReference)reference;
}
AssemblyReference asmRef = new AssemblyReference(assembly);
AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef);
if (cachedAsmRef == asmRef)
{
ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics);
}
// TryAdd because whatever is associated with assembly should be associated with Modules[0]
AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef);
return cachedAsmRef;
}
internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics)
{
if (ReferenceEquals(SourceModule, module))
{
return this;
}
if ((object)module == null)
{
return null;
}
Cci.IModuleReference moduleRef;
if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef))
{
return moduleRef;
}
moduleRef = TranslateModule(module, diagnostics);
moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef);
return moduleRef;
}
protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics)
{
AssemblySymbol container = module.ContainingAssembly;
if ((object)container != null && ReferenceEquals(container.Modules[0], module))
{
Cci.IModuleReference moduleRef = new AssemblyReference(container);
Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef);
if (cachedModuleRef == moduleRef)
{
ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics);
}
else
{
moduleRef = cachedModuleRef;
}
return moduleRef;
}
else
{
return new ModuleReference(this, module);
}
}
internal Cci.INamedTypeReference Translate(
NamedTypeSymbol namedTypeSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool fromImplements = false,
bool needDeclaration = false)
{
Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct());
Debug.Assert(diagnostics != null);
// Anonymous type being translated
if (namedTypeSymbol.IsAnonymousType)
{
Debug.Assert(!needDeclaration);
namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol);
}
else if (namedTypeSymbol.IsTupleType)
{
CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics);
}
// Substitute error types with a special singleton object.
// Unreported bad types can come through NoPia embedding, for example.
if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType)
{
ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition;
DiagnosticInfo diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo;
if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType)
{
errorType = (ErrorTypeSymbol)namedTypeSymbol;
diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo;
}
// Try to decrease noise by not complaining about the same type over and over again.
if (_reportedErrorTypesMap.Add(errorType))
{
diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location));
}
return CodeAnalysis.Emit.ErrorType.Singleton;
}
if (!namedTypeSymbol.IsDefinition)
{
// generic instantiation for sure
Debug.Assert(!needDeclaration);
if (namedTypeSymbol.IsUnboundGenericType)
{
namedTypeSymbol = namedTypeSymbol.OriginalDefinition;
}
else
{
return (Cci.INamedTypeReference)GetCciAdapter(namedTypeSymbol);
}
}
else if (!needDeclaration)
{
object reference;
Cci.INamedTypeReference typeRef;
NamedTypeSymbol container = namedTypeSymbol.ContainingType;
if (namedTypeSymbol.Arity > 0)
{
if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference))
{
return (Cci.INamedTypeReference)reference;
}
if ((object)container != null)
{
if (IsGenericType(container))
{
// Container is a generic instance too.
typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol);
}
else
{
typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol);
}
}
else
{
typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol);
}
typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef);
return typeRef;
}
else if (IsGenericType(container))
{
Debug.Assert((object)container != null);
if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference))
{
return (Cci.INamedTypeReference)reference;
}
typeRef = new SpecializedNestedTypeReference(namedTypeSymbol);
typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef);
return typeRef;
}
else if (namedTypeSymbol.NativeIntegerUnderlyingType is NamedTypeSymbol underlyingType)
{
namedTypeSymbol = underlyingType;
}
}
// NoPia: See if this is a type, which definition we should copy into our assembly.
Debug.Assert(namedTypeSymbol.IsDefinition);
return _embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics) ?? namedTypeSymbol.GetCciAdapter();
}
private object GetCciAdapter(Symbol symbol)
{
return _genericInstanceMap.GetOrAdd(symbol, s => s.GetCciAdapter());
}
private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
// check that underlying type of a ValueTuple is indeed a value type (or error)
// this should never happen, in theory,
// but if it does happen we should make it a failure.
// NOTE: declaredBase could be null for interfaces
var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics;
if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType)
{
return;
}
// Try to decrease noise by not complaining about the same type over and over again.
if (!_reportedErrorTypesMap.Add(namedTypeSymbol))
{
return;
}
var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location;
if ((object)declaredBase != null)
{
var diagnosticInfo = declaredBase.GetUseSiteInfo().DiagnosticInfo;
if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error)
{
diagnostics.Add(diagnosticInfo, location);
return;
}
}
diagnostics.Add(
new CSDiagnostic(
new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName),
location));
}
public static bool IsGenericType(NamedTypeSymbol toCheck)
{
while ((object)toCheck != null)
{
if (toCheck.Arity > 0)
{
return true;
}
toCheck = toCheck.ContainingType;
}
return false;
}
internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param)
{
if (!param.IsDefinition)
throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name));
return param.GetCciAdapter();
}
internal sealed override Cci.ITypeReference Translate(
TypeSymbol typeSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
Debug.Assert(diagnostics != null);
switch (typeSymbol.Kind)
{
case SymbolKind.DynamicType:
return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics);
case SymbolKind.ArrayType:
return Translate((ArrayTypeSymbol)typeSymbol);
case SymbolKind.ErrorType:
case SymbolKind.NamedType:
return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics);
case SymbolKind.PointerType:
return Translate((PointerTypeSymbol)typeSymbol);
case SymbolKind.TypeParameter:
return Translate((TypeParameterSymbol)typeSymbol);
case SymbolKind.FunctionPointerType:
return Translate((FunctionPointerTypeSymbol)typeSymbol);
}
throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind);
}
internal Cci.IFieldReference Translate(
FieldSymbol fieldSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool needDeclaration = false)
{
Debug.Assert(fieldSymbol.IsDefinitionOrDistinct());
Debug.Assert(!fieldSymbol.IsVirtualTupleField &&
(object)(fieldSymbol.TupleUnderlyingField ?? fieldSymbol) == fieldSymbol &&
fieldSymbol is not TupleErrorFieldSymbol, "tuple fields should be rewritten to underlying by now");
if (!fieldSymbol.IsDefinition)
{
Debug.Assert(!needDeclaration);
return (Cci.IFieldReference)GetCciAdapter(fieldSymbol);
}
else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType))
{
object reference;
Cci.IFieldReference fieldRef;
if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference))
{
return (Cci.IFieldReference)reference;
}
fieldRef = new SpecializedFieldReference(fieldSymbol);
fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef);
return fieldRef;
}
return _embeddedTypesManagerOpt?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics) ?? fieldSymbol.GetCciAdapter();
}
public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol)
{
//
// We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies.
//
// Top-level:
// private -> public
// protected -> public (compiles with a warning)
// public
// internal -> public
//
// In a nested class:
//
// private
// protected
// public
// internal -> public
//
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Public:
return Cci.TypeMemberVisibility.Public;
case Accessibility.Private:
if (symbol.ContainingType?.TypeKind == TypeKind.Submission)
{
// top-level private member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Private;
}
case Accessibility.Internal:
if (symbol.ContainingAssembly.IsInteractive)
{
// top-level or nested internal member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Assembly;
}
case Accessibility.Protected:
if (symbol.ContainingType.TypeKind == TypeKind.Submission)
{
// top-level protected member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Family;
}
case Accessibility.ProtectedAndInternal:
Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission);
return Cci.TypeMemberVisibility.FamilyAndAssembly;
case Accessibility.ProtectedOrInternal:
if (symbol.ContainingAssembly.IsInteractive)
{
// top-level or nested protected internal member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.FamilyOrAssembly;
}
default:
throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility);
}
}
internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration)
{
return Translate(symbol, null, diagnostics, null, needDeclaration);
}
internal Cci.IMethodReference Translate(
MethodSymbol methodSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
BoundArgListOperator optArgList = null,
bool needDeclaration = false)
{
Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor(requireZeroInit: true));
Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration));
Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration);
if (optArgList != null && optArgList.Arguments.Length > 0)
{
Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length];
int ordinal = methodSymbol.ParameterCount;
for (int i = 0; i < @params.Length; i++)
{
@params[i] = new ArgListParameterTypeInformation(ordinal,
!optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None,
Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics));
ordinal++;
}
return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull());
}
else
{
return unexpandedMethodRef;
}
}
private Cci.IMethodReference Translate(
MethodSymbol methodSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool needDeclaration)
{
object reference;
Cci.IMethodReference methodRef;
NamedTypeSymbol container = methodSymbol.ContainingType;
// Method of anonymous type being translated
if (container.IsAnonymousType)
{
Debug.Assert(!needDeclaration);
methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol);
}
Debug.Assert(methodSymbol.IsDefinitionOrDistinct());
if (!methodSymbol.IsDefinition)
{
Debug.Assert(!needDeclaration);
Debug.Assert(!(methodSymbol.OriginalDefinition is NativeIntegerMethodSymbol));
Debug.Assert(!(methodSymbol.ConstructedFrom is NativeIntegerMethodSymbol));
return (Cci.IMethodReference)GetCciAdapter(methodSymbol);
}
else if (!needDeclaration)
{
bool methodIsGeneric = methodSymbol.IsGenericMethod;
bool typeIsGeneric = IsGenericType(container);
if (methodIsGeneric || typeIsGeneric)
{
if (_genericInstanceMap.TryGetValue(methodSymbol, out reference))
{
return (Cci.IMethodReference)reference;
}
if (methodIsGeneric)
{
if (typeIsGeneric)
{
// Specialized and generic instance at the same time.
methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol);
}
else
{
methodRef = new GenericMethodInstanceReference(methodSymbol);
}
}
else
{
Debug.Assert(typeIsGeneric);
methodRef = new SpecializedMethodReference(methodSymbol);
}
methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef);
return methodRef;
}
else if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: MethodSymbol underlyingMethod })
{
methodSymbol = underlyingMethod;
}
}
if (_embeddedTypesManagerOpt != null)
{
return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
return methodSymbol.GetCciAdapter();
}
internal Cci.IMethodReference TranslateOverriddenMethodReference(
MethodSymbol methodSymbol,
CSharpSyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
Cci.IMethodReference methodRef;
NamedTypeSymbol container = methodSymbol.ContainingType;
if (IsGenericType(container))
{
if (methodSymbol.IsDefinition)
{
object reference;
if (_genericInstanceMap.TryGetValue(methodSymbol, out reference))
{
methodRef = (Cci.IMethodReference)reference;
}
else
{
methodRef = new SpecializedMethodReference(methodSymbol);
methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef);
}
}
else
{
methodRef = new SpecializedMethodReference(methodSymbol);
}
}
else
{
Debug.Assert(methodSymbol.IsDefinition);
if (_embeddedTypesManagerOpt != null)
{
methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
else
{
methodRef = methodSymbol.GetCciAdapter();
}
}
return methodRef;
}
internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params)
{
Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct()));
bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First());
Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating");
if (!mustBeTranslated)
{
#if DEBUG
return @params.SelectAsArray<ParameterSymbol, Cci.IParameterTypeInformation>(p => p.GetCciAdapter());
#else
return StaticCast<Cci.IParameterTypeInformation>.From(@params);
#endif
}
return TranslateAll(@params);
}
private static bool MustBeWrapped(ParameterSymbol param)
{
// we represent parameters of generic methods as definitions
// CCI wants them represented as IParameterTypeInformation
// so we need to create a wrapper of parameters iff
// 1) parameters are definitions and
// 2) container is generic
// NOTE: all parameters must always agree on whether they need wrapping
if (param.IsDefinition)
{
var container = param.ContainingSymbol;
if (ContainerIsGeneric(container))
{
return true;
}
}
return false;
}
private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params)
{
var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance();
foreach (var param in @params)
{
builder.Add(CreateParameterTypeInformationWrapper(param));
}
return builder.ToImmutableAndFree();
}
private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param)
{
object reference;
Cci.IParameterTypeInformation paramRef;
if (_genericInstanceMap.TryGetValue(param, out reference))
{
return (Cci.IParameterTypeInformation)reference;
}
paramRef = new ParameterTypeInformation(param);
paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef);
return paramRef;
}
private static bool ContainerIsGeneric(Symbol container)
{
return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod ||
IsGenericType(container.ContainingType);
}
internal Cci.ITypeReference Translate(
DynamicTypeSymbol symbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
// Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table.
// We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter
// masquerades the TypeRef as System.Object when used to encode signatures.
return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics);
}
internal Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol)
{
return (Cci.IArrayTypeReference)GetCciAdapter(symbol);
}
internal Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol)
{
return (Cci.IPointerTypeReference)GetCciAdapter(symbol);
}
internal Cci.IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol)
{
return (Cci.IFunctionPointerTypeReference)GetCciAdapter(symbol);
}
/// <summary>
/// Set the underlying implementation type for a given fixed-size buffer field.
/// </summary>
public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field)
{
if (_fixedImplementationTypes == null)
{
Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null);
}
lock (_fixedImplementationTypes)
{
NamedTypeSymbol result;
if (_fixedImplementationTypes.TryGetValue(field, out result))
{
return result;
}
result = new FixedFieldImplementationType(field);
_fixedImplementationTypes.Add(field, result);
AddSynthesizedDefinition(result.ContainingType, result.GetCciAdapter());
return result;
}
}
internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field)
{
// Note that this method is called only after ALL fixed buffer types have been placed in the map.
// At that point the map is all filled in and will not change further. Therefore it is safe to
// pull values from the map without locking.
NamedTypeSymbol result;
var found = _fixedImplementationTypes.TryGetValue(field, out result);
Debug.Assert(found);
return result;
}
protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics)
{
return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter();
}
internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute();
internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsReadOnlyAttribute();
}
internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsUnmanagedAttribute();
}
internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsByRefLikeAttribute();
}
/// <summary>
/// Given a type <paramref name="type"/>, which is either a nullable reference type OR
/// is a constructed type with a nullable reference type present in its type argument tree,
/// returns a synthesized NullableAttribute with encoded nullable transforms array.
/// </summary>
internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
var flagsBuilder = ArrayBuilder<byte>.GetInstance();
type.AddNullableTransforms(flagsBuilder);
SynthesizedAttributeData attribute;
if (!flagsBuilder.Any())
{
attribute = null;
}
else
{
Debug.Assert(flagsBuilder.All(f => f <= 2));
byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(flagsBuilder);
if (commonValue != null)
{
attribute = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault());
}
else
{
NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte);
var byteArrayType = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType));
var value = flagsBuilder.SelectAsArray((flag, byteType) => new TypedConstant(byteType, TypedConstantKind.Primitive, flag), byteType);
attribute = SynthesizeNullableAttribute(
WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags,
ImmutableArray.Create(new TypedConstant(byteArrayType, value)));
}
}
flagsBuilder.Free();
return attribute;
}
internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue)
{
if (nullableValue == nullableContextValue ||
(nullableContextValue == null && nullableValue == 0))
{
return null;
}
NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte);
return SynthesizeNullableAttribute(
WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte,
ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, nullableValue)));
}
internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value)
{
var module = Compilation.SourceModule;
if ((object)module != symbol && (object)module != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return SynthesizeNullableContextAttribute(
ImmutableArray.Create(new TypedConstant(Compilation.GetSpecialType(SpecialType.System_Byte), TypedConstantKind.Primitive, value)));
}
internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, arguments, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute()
{
return Compilation.TrySynthesizeAttribute(SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type)
{
Debug.Assert((object)type != null);
Debug.Assert(type.ContainsNativeInteger());
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
var builder = ArrayBuilder<bool>.GetInstance();
CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, type);
Debug.Assert(builder.Any());
Debug.Assert(builder.Contains(true));
SynthesizedAttributeData attribute;
if (builder.Count == 1 && builder[0])
{
attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, ImmutableArray<TypedConstant>.Empty);
}
else
{
NamedTypeSymbol booleanType = Compilation.GetSpecialType(SpecialType.System_Boolean);
Debug.Assert((object)booleanType != null);
var transformFlags = builder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType);
var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType));
var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags));
attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, arguments);
}
builder.Free();
return attribute;
}
internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true);
}
internal bool ShouldEmitNullablePublicOnlyAttribute()
{
// No need to look at this.GetNeedsGeneratedAttributes() since those bits are
// only set for members generated by the rewriter which are not public.
return Compilation.GetUsesNullableAttributes() && Compilation.EmitNullablePublicOnly;
}
internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, arguments);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor);
}
private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute)
{
Debug.Assert(!_needsGeneratedAttributes_IsFrozen);
if ((GetNeedsGeneratedAttributesInternal() & attribute) != 0)
{
return;
}
// Don't report any errors. They should be reported during binding.
if (Compilation.CheckIfAttributeShouldBeEmbedded(attribute, diagnosticsOpt: null, locationOpt: null))
{
SetNeedsGeneratedAttributes(attribute);
}
}
internal void EnsureIsReadOnlyAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute);
}
internal void EnsureIsUnmanagedAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute);
}
internal void EnsureNullableAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute);
}
internal void EnsureNativeIntegerAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute);
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context)
{
return GetAdditionalTopLevelTypes()
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context)
{
return GetEmbeddedTypes(context.Diagnostics)
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics)
{
return GetEmbeddedTypes(new BindingDiagnosticBag(diagnostics));
}
internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics)
{
return base.GetEmbeddedTypes(diagnostics.DiagnosticBag);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState>
{
// TODO: Need to estimate amount of elements for this map and pass that value to the constructor.
protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>();
private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>(Symbols.SymbolEqualityComparer.ConsiderEverything);
private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>();
private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt;
public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt
=> _embeddedTypesManagerOpt;
// Gives the name of this module (may not reflect the name of the underlying symbol).
// See Assembly.MetadataName.
private readonly string _metadataName;
private ImmutableArray<Cci.ExportedType> _lazyExportedTypes;
/// <summary>
/// The compiler-generated implementation type for each fixed-size buffer.
/// </summary>
private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes;
private int _needsGeneratedAttributes;
private bool _needsGeneratedAttributes_IsFrozen;
/// <summary>
/// Returns a value indicating which embedded attributes should be generated during emit phase.
/// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it.
/// Freezing is needed to make sure that nothing tries to modify the value after the value is read.
/// </summary>
internal EmbeddableAttributes GetNeedsGeneratedAttributes()
{
_needsGeneratedAttributes_IsFrozen = true;
return GetNeedsGeneratedAttributesInternal();
}
private EmbeddableAttributes GetNeedsGeneratedAttributesInternal()
{
return (EmbeddableAttributes)_needsGeneratedAttributes | Compilation.GetNeedsGeneratedAttributes();
}
private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes)
{
Debug.Assert(!_needsGeneratedAttributes_IsFrozen);
ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes);
}
internal PEModuleBuilder(
SourceModuleSymbol sourceModule,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources)
: base(sourceModule.ContainingSourceAssembly.DeclaringCompilation,
sourceModule,
serializationProperties,
manifestResources,
outputKind,
emitOptions,
new ModuleCompilationState())
{
var specifiedName = sourceModule.MetadataName;
_metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ?
specifiedName :
emitOptions.OutputNameOverride ?? specifiedName;
AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this);
if (sourceModule.AnyReferencedAssembliesAreLinked)
{
_embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this);
}
}
public override string Name
{
get { return _metadataName; }
}
internal sealed override string ModuleName
{
get { return _metadataName; }
}
internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor)
{
return Compilation.TrySynthesizeAttribute(attributeConstructor);
}
public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly)
{
return SourceModule.ContainingSourceAssembly
.GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule());
}
public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes()
{
return SourceModule.ContainingSourceAssembly.GetSecurityAttributes();
}
public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes()
{
return SourceModule.GetCustomAttributesToEmit(this);
}
internal sealed override AssemblySymbol CorLibrary
{
get { return SourceModule.ContainingSourceAssembly.CorLibrary; }
}
public sealed override bool GenerateVisualBasicStylePdb => false;
// C# doesn't emit linked assembly names into PDBs.
public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>();
// C# currently doesn't emit compilation level imports (TODO: scripting).
public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty;
// C# doesn't allow to define default namespace for compilation.
public sealed override string DefaultNamespace => null;
protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics)
{
ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules;
for (int i = 1; i < modules.Length; i++)
{
foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols())
{
yield return Translate(aRef, diagnostics);
}
}
}
private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics)
{
AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity;
AssemblyIdentity refIdentity = asmRef.Identity;
if (asmIdentity.IsStrongName && !refIdentity.IsStrongName &&
asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime)
{
// Dev12 reported error, we have changed it to a warning to allow referencing libraries
// built for platforms that don't support strong names.
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton);
}
if (OutputKind != OutputKind.NetModule &&
!string.IsNullOrEmpty(refIdentity.CultureName) &&
!string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase))
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton);
}
var refMachine = assembly.Machine;
// If other assembly is agnostic this is always safe
// Also, if no mscorlib was specified for back compat we add a reference to mscorlib
// that resolves to the current framework directory. If the compiler is 64-bit
// this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is
// specified. A reference to the default mscorlib should always succeed without
// warning so we ignore it here.
if ((object)assembly != (object)assembly.CorLibrary &&
!(refMachine == Machine.I386 && !assembly.Bit32Required))
{
var machine = SourceModule.Machine;
if (!(machine == Machine.I386 && !SourceModule.Bit32Required) &&
machine != refMachine)
{
// Different machine types, and neither is agnostic
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton);
}
}
if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen)
{
_embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics);
}
}
internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container)
{
return null;
}
public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap()
{
var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>();
var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>();
namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace);
Location location = null;
while (namespacesAndTypesToProcess.Count > 0)
{
NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop();
switch (symbol.Kind)
{
case SymbolKind.Namespace:
location = GetSmallestSourceLocationOrNull(symbol);
// filtering out synthesized symbols not having real source
// locations such as anonymous types, etc...
if (location != null)
{
foreach (var member in symbol.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.Namespace:
case SymbolKind.NamedType:
namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member);
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
}
break;
case SymbolKind.NamedType:
location = GetSmallestSourceLocationOrNull(symbol);
if (location != null)
{
// add this named type location
AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter());
foreach (var member in symbol.GetMembers())
{
switch (member.Kind)
{
case SymbolKind.NamedType:
namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member);
break;
case SymbolKind.Method:
// NOTE: Dev11 does not add synthesized static constructors to this map,
// but adds synthesized instance constructors, Roslyn adds both
var method = (MethodSymbol)member;
if (!method.ShouldEmit())
{
break;
}
AddSymbolLocation(result, member);
break;
case SymbolKind.Property:
AddSymbolLocation(result, member);
break;
case SymbolKind.Field:
if (member is TupleErrorFieldSymbol)
{
break;
}
// NOTE: Dev11 does not add synthesized backing fields for properties,
// but adds backing fields for events, Roslyn adds both
AddSymbolLocation(result, member);
break;
case SymbolKind.Event:
AddSymbolLocation(result, member);
// event backing fields do not show up in GetMembers
{
FieldSymbol field = ((EventSymbol)member).AssociatedField;
if ((object)field != null)
{
AddSymbolLocation(result, field);
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
return result;
}
private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol)
{
var location = GetSmallestSourceLocationOrNull(symbol);
if (location != null)
{
AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter());
}
}
private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition)
{
FileLinePositionSpan span = location.GetLineSpan();
Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath);
if (doc != null)
{
result.Add(doc,
new Cci.DefinitionWithLocation(
definition,
span.StartLinePosition.Line,
span.StartLinePosition.Character,
span.EndLinePosition.Line,
span.EndLinePosition.Character));
}
}
private Location GetSmallestSourceLocationOrNull(Symbol symbol)
{
CSharpCompilation compilation = symbol.DeclaringCompilation;
Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?");
Location result = null;
foreach (var loc in symbol.Locations)
{
if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0))
{
result = loc;
}
}
return result;
}
/// <summary>
/// Ignore accessibility when resolving well-known type
/// members, in particular for generic type arguments
/// (e.g.: binding to internal types in the EE).
/// </summary>
internal virtual bool IgnoreAccessibility => false;
/// <summary>
/// Override the dynamic operation context type for all dynamic calls in the module.
/// </summary>
internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType)
{
return contextType;
}
internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics)
{
return null;
}
internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes()
{
return ImmutableArray<AnonymousTypeKey>.Empty;
}
internal virtual int GetNextAnonymousTypeIndex()
{
return 0;
}
internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index)
{
Debug.Assert(Compilation == template.DeclaringCompilation);
name = null;
index = -1;
return false;
}
public sealed override IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context)
{
if (context.MetadataOnly)
{
return SpecializedCollections.EmptyEnumerable<Cci.INamespaceTypeDefinition>();
}
return Compilation.AnonymousTypeManager.GetAllCreatedTemplates()
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context)
{
var namespacesToProcess = new Stack<NamespaceSymbol>();
namespacesToProcess.Push(SourceModule.GlobalNamespace);
while (namespacesToProcess.Count > 0)
{
var ns = namespacesToProcess.Pop();
foreach (var member in ns.GetMembers())
{
if (member.Kind == SymbolKind.Namespace)
{
namespacesToProcess.Push((NamespaceSymbol)member);
}
else
{
yield return ((NamedTypeSymbol)member).GetCciAdapter();
}
}
}
}
private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder)
{
int index;
if (symbol.Kind == SymbolKind.NamedType)
{
if (symbol.DeclaredAccessibility != Accessibility.Public)
{
return;
}
Debug.Assert(symbol.IsDefinition);
index = builder.Count;
builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol.GetCciAdapter(), parentIndex, isForwarder: false));
}
else
{
index = -1;
}
foreach (var member in symbol.GetMembers())
{
var namespaceOrType = member as NamespaceOrTypeSymbol;
if ((object)namespaceOrType != null)
{
GetExportedTypes(namespaceOrType, index, builder);
}
}
}
public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics)
{
Debug.Assert(HaveDeterminedTopLevelTypes);
if (_lazyExportedTypes.IsDefault)
{
_lazyExportedTypes = CalculateExportedTypes();
if (_lazyExportedTypes.Length > 0)
{
ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics);
}
}
return _lazyExportedTypes;
}
/// <summary>
/// Builds an array of public type symbols defined in netmodules included in the compilation
/// and type forwarders defined in this compilation or any included netmodule (in this order).
/// </summary>
private ImmutableArray<Cci.ExportedType> CalculateExportedTypes()
{
SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly;
var builder = ArrayBuilder<Cci.ExportedType>.GetInstance();
if (!OutputKind.IsNetModule())
{
var modules = sourceAssembly.Modules;
for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0]
{
GetExportedTypes(modules[i].GlobalNamespace, -1, builder);
}
}
Debug.Assert(OutputKind.IsNetModule() == sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule());
GetForwardedTypes(sourceAssembly, builder);
return builder.ToImmutableAndFree();
}
#nullable enable
/// <summary>
/// Returns a set of top-level forwarded types
/// </summary>
internal static HashSet<NamedTypeSymbol> GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder<Cci.ExportedType>? builder)
{
var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>();
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder);
if (!sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule())
{
GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder);
}
return seenTopLevelForwardedTypes;
}
#nullable disable
private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics)
{
var sourceAssembly = SourceModule.ContainingSourceAssembly;
var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance);
foreach (var exportedType in exportedTypes)
{
var type = (NamedTypeSymbol)exportedType.Type.GetInternalSymbol();
Debug.Assert(type.IsDefinition);
if (!type.IsTopLevelType())
{
continue;
}
// exported types are not emitted in EnC deltas (hence generation 0):
string fullEmittedName = MetadataHelpers.BuildQualifiedName(
((Cci.INamespaceTypeReference)type.GetCciAdapter()).NamespaceName,
Cci.MetadataWriter.GetMangledName(type.GetCciAdapter(), generation: 0));
// First check against types declared in the primary module
if (ContainsTopLevelType(fullEmittedName))
{
if ((object)type.ContainingAssembly == sourceAssembly)
{
diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule);
}
else
{
diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type);
}
continue;
}
NamedTypeSymbol contender;
// Now check against other exported types
if (exportedNamesMap.TryGetValue(fullEmittedName, out contender))
{
if ((object)type.ContainingAssembly == sourceAssembly)
{
// all exported types precede forwarded types, therefore contender cannot be a forwarded type.
Debug.Assert(contender.ContainingAssembly == sourceAssembly);
diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule);
}
else if ((object)contender.ContainingAssembly == sourceAssembly)
{
// Forwarded type conflicts with exported type
diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule);
}
else
{
// Forwarded type conflicts with another forwarded type
diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly);
}
continue;
}
exportedNamesMap.Add(fullEmittedName, type);
}
}
#nullable enable
private static void GetForwardedTypes(
HashSet<NamedTypeSymbol> seenTopLevelTypes,
CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData,
ArrayBuilder<Cci.ExportedType>? builder)
{
if (wellKnownAttributeData?.ForwardedTypes?.Count > 0)
{
// (type, index of the parent exported type in builder, or -1 if the type is a top-level type)
var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance();
// Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names.
IEnumerable<NamedTypeSymbol> orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes;
if (builder is object)
{
orderedForwardedTypes = orderedForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat));
}
foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes)
{
NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition;
Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?");
// Since we need to allow multiple constructions of the same generic type at the source
// level, we need to de-dup the original definitions before emitting.
if (!seenTopLevelTypes.Add(originalDefinition)) continue;
if (builder is object)
{
// Return all nested types.
// Note the order: depth first, children in reverse order (to match dev10, not a requirement).
Debug.Assert(stack.Count == 0);
stack.Push((originalDefinition, -1));
while (stack.Count > 0)
{
var (type, parentIndex) = stack.Pop();
// In general, we don't want private types to appear in the ExportedTypes table.
// BREAK: dev11 emits these types. The problem was discovered in dev10, but failed
// to meet the bar Bug: Dev10/258038 and was left as-is.
if (type.DeclaredAccessibility == Accessibility.Private)
{
// NOTE: this will also exclude nested types of type
continue;
}
// NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection.
int index = builder.Count;
builder.Add(new Cci.ExportedType(type.GetCciAdapter(), parentIndex, isForwarder: true));
// Iterate backwards so they get popped in forward order.
ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered.
for (int i = nested.Length - 1; i >= 0; i--)
{
stack.Push((nested[i], index));
}
}
}
}
stack.Free();
}
}
#nullable disable
internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar()
{
foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols())
{
if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a))
{
yield return a;
}
}
}
private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
Debug.Assert(diagnostics != null);
var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType);
DiagnosticInfo info = typeSymbol.GetUseSiteInfo().DiagnosticInfo;
if (info != null)
{
Symbol.ReportUseSiteDiagnostic(info,
diagnostics,
syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton);
}
return typeSymbol;
}
internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics),
diagnostics: diagnostics,
syntaxNodeOpt: syntaxNodeOpt,
needDeclaration: true);
}
public sealed override Cci.IMethodReference GetInitArrayHelper()
{
return ((MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle))?.GetCciAdapter();
}
public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType)
{
var namedType = typeRef.GetInternalSymbol() as NamedTypeSymbol;
if ((object)namedType != null)
{
if (platformType == Cci.PlatformType.SystemType)
{
return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type);
}
return namedType.SpecialType == (SpecialType)platformType;
}
return false;
}
protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context)
{
AssemblySymbol corLibrary = CorLibrary;
if (!corLibrary.IsMissing &&
!corLibrary.IsLinked &&
!ReferenceEquals(corLibrary, SourceModule.ContainingAssembly))
{
return Translate(corLibrary, context.Diagnostics);
}
return null;
}
internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics)
{
if (ReferenceEquals(SourceModule.ContainingAssembly, assembly))
{
return (Cci.IAssemblyReference)this;
}
Cci.IModuleReference reference;
if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference))
{
return (Cci.IAssemblyReference)reference;
}
AssemblyReference asmRef = new AssemblyReference(assembly);
AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef);
if (cachedAsmRef == asmRef)
{
ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics);
}
// TryAdd because whatever is associated with assembly should be associated with Modules[0]
AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef);
return cachedAsmRef;
}
internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics)
{
if (ReferenceEquals(SourceModule, module))
{
return this;
}
if ((object)module == null)
{
return null;
}
Cci.IModuleReference moduleRef;
if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef))
{
return moduleRef;
}
moduleRef = TranslateModule(module, diagnostics);
moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef);
return moduleRef;
}
protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics)
{
AssemblySymbol container = module.ContainingAssembly;
if ((object)container != null && ReferenceEquals(container.Modules[0], module))
{
Cci.IModuleReference moduleRef = new AssemblyReference(container);
Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef);
if (cachedModuleRef == moduleRef)
{
ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics);
}
else
{
moduleRef = cachedModuleRef;
}
return moduleRef;
}
else
{
return new ModuleReference(this, module);
}
}
internal Cci.INamedTypeReference Translate(
NamedTypeSymbol namedTypeSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool fromImplements = false,
bool needDeclaration = false)
{
Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct());
Debug.Assert(diagnostics != null);
// Anonymous type being translated
if (namedTypeSymbol.IsAnonymousType)
{
Debug.Assert(!needDeclaration);
namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol);
}
else if (namedTypeSymbol.IsTupleType)
{
CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics);
}
// Substitute error types with a special singleton object.
// Unreported bad types can come through NoPia embedding, for example.
if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType)
{
ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition;
DiagnosticInfo diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo;
if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType)
{
errorType = (ErrorTypeSymbol)namedTypeSymbol;
diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo;
}
// Try to decrease noise by not complaining about the same type over and over again.
if (_reportedErrorTypesMap.Add(errorType))
{
diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location));
}
return CodeAnalysis.Emit.ErrorType.Singleton;
}
if (!namedTypeSymbol.IsDefinition)
{
// generic instantiation for sure
Debug.Assert(!needDeclaration);
if (namedTypeSymbol.IsUnboundGenericType)
{
namedTypeSymbol = namedTypeSymbol.OriginalDefinition;
}
else
{
return (Cci.INamedTypeReference)GetCciAdapter(namedTypeSymbol);
}
}
else if (!needDeclaration)
{
object reference;
Cci.INamedTypeReference typeRef;
NamedTypeSymbol container = namedTypeSymbol.ContainingType;
if (namedTypeSymbol.Arity > 0)
{
if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference))
{
return (Cci.INamedTypeReference)reference;
}
if ((object)container != null)
{
if (IsGenericType(container))
{
// Container is a generic instance too.
typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol);
}
else
{
typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol);
}
}
else
{
typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol);
}
typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef);
return typeRef;
}
else if (IsGenericType(container))
{
Debug.Assert((object)container != null);
if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference))
{
return (Cci.INamedTypeReference)reference;
}
typeRef = new SpecializedNestedTypeReference(namedTypeSymbol);
typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef);
return typeRef;
}
else if (namedTypeSymbol.NativeIntegerUnderlyingType is NamedTypeSymbol underlyingType)
{
namedTypeSymbol = underlyingType;
}
}
// NoPia: See if this is a type, which definition we should copy into our assembly.
Debug.Assert(namedTypeSymbol.IsDefinition);
return _embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics) ?? namedTypeSymbol.GetCciAdapter();
}
private object GetCciAdapter(Symbol symbol)
{
return _genericInstanceMap.GetOrAdd(symbol, s => s.GetCciAdapter());
}
private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics)
{
// check that underlying type of a ValueTuple is indeed a value type (or error)
// this should never happen, in theory,
// but if it does happen we should make it a failure.
// NOTE: declaredBase could be null for interfaces
var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics;
if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType)
{
return;
}
// Try to decrease noise by not complaining about the same type over and over again.
if (!_reportedErrorTypesMap.Add(namedTypeSymbol))
{
return;
}
var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location;
if ((object)declaredBase != null)
{
var diagnosticInfo = declaredBase.GetUseSiteInfo().DiagnosticInfo;
if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error)
{
diagnostics.Add(diagnosticInfo, location);
return;
}
}
diagnostics.Add(
new CSDiagnostic(
new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName),
location));
}
public static bool IsGenericType(NamedTypeSymbol toCheck)
{
while ((object)toCheck != null)
{
if (toCheck.Arity > 0)
{
return true;
}
toCheck = toCheck.ContainingType;
}
return false;
}
internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param)
{
if (!param.IsDefinition)
throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name));
return param.GetCciAdapter();
}
internal sealed override Cci.ITypeReference Translate(
TypeSymbol typeSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
Debug.Assert(diagnostics != null);
switch (typeSymbol.Kind)
{
case SymbolKind.DynamicType:
return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics);
case SymbolKind.ArrayType:
return Translate((ArrayTypeSymbol)typeSymbol);
case SymbolKind.ErrorType:
case SymbolKind.NamedType:
return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics);
case SymbolKind.PointerType:
return Translate((PointerTypeSymbol)typeSymbol);
case SymbolKind.TypeParameter:
return Translate((TypeParameterSymbol)typeSymbol);
case SymbolKind.FunctionPointerType:
return Translate((FunctionPointerTypeSymbol)typeSymbol);
}
throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind);
}
internal Cci.IFieldReference Translate(
FieldSymbol fieldSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool needDeclaration = false)
{
Debug.Assert(fieldSymbol.IsDefinitionOrDistinct());
Debug.Assert(!fieldSymbol.IsVirtualTupleField &&
(object)(fieldSymbol.TupleUnderlyingField ?? fieldSymbol) == fieldSymbol &&
fieldSymbol is not TupleErrorFieldSymbol, "tuple fields should be rewritten to underlying by now");
if (!fieldSymbol.IsDefinition)
{
Debug.Assert(!needDeclaration);
return (Cci.IFieldReference)GetCciAdapter(fieldSymbol);
}
else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType))
{
object reference;
Cci.IFieldReference fieldRef;
if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference))
{
return (Cci.IFieldReference)reference;
}
fieldRef = new SpecializedFieldReference(fieldSymbol);
fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef);
return fieldRef;
}
return _embeddedTypesManagerOpt?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics) ?? fieldSymbol.GetCciAdapter();
}
public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol)
{
//
// We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies.
//
// Top-level:
// private -> public
// protected -> public (compiles with a warning)
// public
// internal -> public
//
// In a nested class:
//
// private
// protected
// public
// internal -> public
//
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Public:
return Cci.TypeMemberVisibility.Public;
case Accessibility.Private:
if (symbol.ContainingType?.TypeKind == TypeKind.Submission)
{
// top-level private member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Private;
}
case Accessibility.Internal:
if (symbol.ContainingAssembly.IsInteractive)
{
// top-level or nested internal member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Assembly;
}
case Accessibility.Protected:
if (symbol.ContainingType.TypeKind == TypeKind.Submission)
{
// top-level protected member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.Family;
}
case Accessibility.ProtectedAndInternal:
Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission);
return Cci.TypeMemberVisibility.FamilyAndAssembly;
case Accessibility.ProtectedOrInternal:
if (symbol.ContainingAssembly.IsInteractive)
{
// top-level or nested protected internal member:
return Cci.TypeMemberVisibility.Public;
}
else
{
return Cci.TypeMemberVisibility.FamilyOrAssembly;
}
default:
throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility);
}
}
internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration)
{
return Translate(symbol, null, diagnostics, null, needDeclaration);
}
internal Cci.IMethodReference Translate(
MethodSymbol methodSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
BoundArgListOperator optArgList = null,
bool needDeclaration = false)
{
Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor(requireZeroInit: true));
Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration));
Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration);
if (optArgList != null && optArgList.Arguments.Length > 0)
{
Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length];
int ordinal = methodSymbol.ParameterCount;
for (int i = 0; i < @params.Length; i++)
{
@params[i] = new ArgListParameterTypeInformation(ordinal,
!optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None,
Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics));
ordinal++;
}
return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull());
}
else
{
return unexpandedMethodRef;
}
}
private Cci.IMethodReference Translate(
MethodSymbol methodSymbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics,
bool needDeclaration)
{
object reference;
Cci.IMethodReference methodRef;
NamedTypeSymbol container = methodSymbol.ContainingType;
// Method of anonymous type being translated
if (container.IsAnonymousType)
{
Debug.Assert(!needDeclaration);
methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol);
}
Debug.Assert(methodSymbol.IsDefinitionOrDistinct());
if (!methodSymbol.IsDefinition)
{
Debug.Assert(!needDeclaration);
Debug.Assert(!(methodSymbol.OriginalDefinition is NativeIntegerMethodSymbol));
Debug.Assert(!(methodSymbol.ConstructedFrom is NativeIntegerMethodSymbol));
return (Cci.IMethodReference)GetCciAdapter(methodSymbol);
}
else if (!needDeclaration)
{
bool methodIsGeneric = methodSymbol.IsGenericMethod;
bool typeIsGeneric = IsGenericType(container);
if (methodIsGeneric || typeIsGeneric)
{
if (_genericInstanceMap.TryGetValue(methodSymbol, out reference))
{
return (Cci.IMethodReference)reference;
}
if (methodIsGeneric)
{
if (typeIsGeneric)
{
// Specialized and generic instance at the same time.
methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol);
}
else
{
methodRef = new GenericMethodInstanceReference(methodSymbol);
}
}
else
{
Debug.Assert(typeIsGeneric);
methodRef = new SpecializedMethodReference(methodSymbol);
}
methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef);
return methodRef;
}
else if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: MethodSymbol underlyingMethod })
{
methodSymbol = underlyingMethod;
}
}
if (_embeddedTypesManagerOpt != null)
{
return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
return methodSymbol.GetCciAdapter();
}
internal Cci.IMethodReference TranslateOverriddenMethodReference(
MethodSymbol methodSymbol,
CSharpSyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
Cci.IMethodReference methodRef;
NamedTypeSymbol container = methodSymbol.ContainingType;
if (IsGenericType(container))
{
if (methodSymbol.IsDefinition)
{
object reference;
if (_genericInstanceMap.TryGetValue(methodSymbol, out reference))
{
methodRef = (Cci.IMethodReference)reference;
}
else
{
methodRef = new SpecializedMethodReference(methodSymbol);
methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef);
}
}
else
{
methodRef = new SpecializedMethodReference(methodSymbol);
}
}
else
{
Debug.Assert(methodSymbol.IsDefinition);
if (_embeddedTypesManagerOpt != null)
{
methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics);
}
else
{
methodRef = methodSymbol.GetCciAdapter();
}
}
return methodRef;
}
internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params)
{
Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct()));
bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First());
Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating");
if (!mustBeTranslated)
{
#if DEBUG
return @params.SelectAsArray<ParameterSymbol, Cci.IParameterTypeInformation>(p => p.GetCciAdapter());
#else
return StaticCast<Cci.IParameterTypeInformation>.From(@params);
#endif
}
return TranslateAll(@params);
}
private static bool MustBeWrapped(ParameterSymbol param)
{
// we represent parameters of generic methods as definitions
// CCI wants them represented as IParameterTypeInformation
// so we need to create a wrapper of parameters iff
// 1) parameters are definitions and
// 2) container is generic
// NOTE: all parameters must always agree on whether they need wrapping
if (param.IsDefinition)
{
var container = param.ContainingSymbol;
if (ContainerIsGeneric(container))
{
return true;
}
}
return false;
}
private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params)
{
var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance();
foreach (var param in @params)
{
builder.Add(CreateParameterTypeInformationWrapper(param));
}
return builder.ToImmutableAndFree();
}
private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param)
{
object reference;
Cci.IParameterTypeInformation paramRef;
if (_genericInstanceMap.TryGetValue(param, out reference))
{
return (Cci.IParameterTypeInformation)reference;
}
paramRef = new ParameterTypeInformation(param);
paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef);
return paramRef;
}
private static bool ContainerIsGeneric(Symbol container)
{
return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod ||
IsGenericType(container.ContainingType);
}
internal Cci.ITypeReference Translate(
DynamicTypeSymbol symbol,
SyntaxNode syntaxNodeOpt,
DiagnosticBag diagnostics)
{
// Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table.
// We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter
// masquerades the TypeRef as System.Object when used to encode signatures.
return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics);
}
internal Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol)
{
return (Cci.IArrayTypeReference)GetCciAdapter(symbol);
}
internal Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol)
{
return (Cci.IPointerTypeReference)GetCciAdapter(symbol);
}
internal Cci.IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol)
{
return (Cci.IFunctionPointerTypeReference)GetCciAdapter(symbol);
}
/// <summary>
/// Set the underlying implementation type for a given fixed-size buffer field.
/// </summary>
public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field)
{
if (_fixedImplementationTypes == null)
{
Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null);
}
lock (_fixedImplementationTypes)
{
NamedTypeSymbol result;
if (_fixedImplementationTypes.TryGetValue(field, out result))
{
return result;
}
result = new FixedFieldImplementationType(field);
_fixedImplementationTypes.Add(field, result);
AddSynthesizedDefinition(result.ContainingType, result.GetCciAdapter());
return result;
}
}
internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field)
{
// Note that this method is called only after ALL fixed buffer types have been placed in the map.
// At that point the map is all filled in and will not change further. Therefore it is safe to
// pull values from the map without locking.
NamedTypeSymbol result;
var found = _fixedImplementationTypes.TryGetValue(field, out result);
Debug.Assert(found);
return result;
}
protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics)
{
return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter();
}
internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute();
internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsReadOnlyAttribute();
}
internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsUnmanagedAttribute();
}
internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return TrySynthesizeIsByRefLikeAttribute();
}
/// <summary>
/// Given a type <paramref name="type"/>, which is either a nullable reference type OR
/// is a constructed type with a nullable reference type present in its type argument tree,
/// returns a synthesized NullableAttribute with encoded nullable transforms array.
/// </summary>
internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type)
{
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
var flagsBuilder = ArrayBuilder<byte>.GetInstance();
type.AddNullableTransforms(flagsBuilder);
SynthesizedAttributeData attribute;
if (!flagsBuilder.Any())
{
attribute = null;
}
else
{
Debug.Assert(flagsBuilder.All(f => f <= 2));
byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(flagsBuilder);
if (commonValue != null)
{
attribute = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault());
}
else
{
NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte);
var byteArrayType = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType));
var value = flagsBuilder.SelectAsArray((flag, byteType) => new TypedConstant(byteType, TypedConstantKind.Primitive, flag), byteType);
attribute = SynthesizeNullableAttribute(
WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags,
ImmutableArray.Create(new TypedConstant(byteArrayType, value)));
}
}
flagsBuilder.Free();
return attribute;
}
internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue)
{
if (nullableValue == nullableContextValue ||
(nullableContextValue == null && nullableValue == 0))
{
return null;
}
NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte);
return SynthesizeNullableAttribute(
WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte,
ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, nullableValue)));
}
internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value)
{
var module = Compilation.SourceModule;
if ((object)module != symbol && (object)module != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
return SynthesizeNullableContextAttribute(
ImmutableArray.Create(new TypedConstant(Compilation.GetSpecialType(SpecialType.System_Byte), TypedConstantKind.Primitive, value)));
}
internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, arguments, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute()
{
return Compilation.TrySynthesizeAttribute(SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, isOptionalUse: true);
}
internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type)
{
Debug.Assert((object)type != null);
Debug.Assert(type.ContainsNativeInteger());
if ((object)Compilation.SourceModule != symbol.ContainingModule)
{
// For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute.
return null;
}
var builder = ArrayBuilder<bool>.GetInstance();
CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, type);
Debug.Assert(builder.Any());
Debug.Assert(builder.Contains(true));
SynthesizedAttributeData attribute;
if (builder.Count == 1 && builder[0])
{
attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, ImmutableArray<TypedConstant>.Empty);
}
else
{
NamedTypeSymbol booleanType = Compilation.GetSpecialType(SpecialType.System_Boolean);
Debug.Assert((object)booleanType != null);
var transformFlags = builder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType);
var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType));
var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags));
attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, arguments);
}
builder.Free();
return attribute;
}
internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
// https://github.com/dotnet/roslyn/issues/30062 Should not be optional.
return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true);
}
internal bool ShouldEmitNullablePublicOnlyAttribute()
{
// No need to look at this.GetNeedsGeneratedAttributes() since those bits are
// only set for members generated by the rewriter which are not public.
return Compilation.GetUsesNullableAttributes() && Compilation.EmitNullablePublicOnly;
}
internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments)
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, arguments);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor);
}
protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute()
{
// For modules, this attribute should be present. Only assemblies generate and embed this type.
return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor);
}
private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute)
{
Debug.Assert(!_needsGeneratedAttributes_IsFrozen);
if ((GetNeedsGeneratedAttributesInternal() & attribute) != 0)
{
return;
}
// Don't report any errors. They should be reported during binding.
if (Compilation.CheckIfAttributeShouldBeEmbedded(attribute, diagnosticsOpt: null, locationOpt: null))
{
SetNeedsGeneratedAttributes(attribute);
}
}
internal void EnsureIsReadOnlyAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute);
}
internal void EnsureIsUnmanagedAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute);
}
internal void EnsureNullableAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute);
}
internal void EnsureNullableContextAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute);
}
internal void EnsureNativeIntegerAttributeExists()
{
EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute);
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context)
{
return GetAdditionalTopLevelTypes()
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public override IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context)
{
return GetEmbeddedTypes(context.Diagnostics)
#if DEBUG
.Select(type => type.GetCciAdapter())
#endif
;
}
public sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics)
{
return GetEmbeddedTypes(new BindingDiagnosticBag(diagnostics));
}
internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics)
{
return base.GetEmbeddedTypes(diagnostics.DiagnosticBag);
}
}
}
| 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/Lowering/ClosureConversion/ClosureConversion.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#if DEBUG
//#define CHECK_LOCALS // define CHECK_LOCALS to help debug some rewriting problems that would otherwise cause code-gen failures
#endif
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The rewriter for removing lambda expressions from method bodies and introducing closure classes
/// as containers for captured variables along the lines of the example in section 6.5.3 of the
/// C# language specification. A closure is the lowered form of a nested function, consisting of a
/// synthesized method and a set of environments containing the captured variables.
///
/// The entry point is the public method <see cref="Rewrite"/>. It operates as follows:
///
/// First, an analysis of the whole method body is performed that determines which variables are
/// captured, what their scopes are, and what the nesting relationship is between scopes that
/// have captured variables. The result of this analysis is left in <see cref="_analysis"/>.
///
/// Then we make a frame, or compiler-generated class, represented by an instance of
/// <see cref="SynthesizedClosureEnvironment"/> for each scope with captured variables. The generated frames are kept
/// in <see cref="_frames"/>. Each frame is given a single field for each captured
/// variable in the corresponding scope. These are maintained in <see cref="MethodToClassRewriter.proxies"/>.
///
/// Next, we walk and rewrite the input bound tree, keeping track of the following:
/// (1) The current set of active frame pointers, in <see cref="_framePointers"/>
/// (2) The current method being processed (this changes within a lambda's body), in <see cref="_currentMethod"/>
/// (3) The "this" symbol for the current method in <see cref="_currentFrameThis"/>, and
/// (4) The symbol that is used to access the innermost frame pointer (it could be a local variable or "this" parameter)
///
/// Lastly, we visit the top-level method and each of the lowered methods
/// to rewrite references (e.g., calls and delegate conversions) to local
/// functions. We visit references to local functions separately from
/// lambdas because we may see the reference before we lower the target
/// local function. Lambdas, on the other hand, are always convertible as
/// they are being lowered.
///
/// There are a few key transformations done in the rewriting.
/// (1) Lambda expressions are turned into delegate creation expressions, and the body of the lambda is
/// moved into a new, compiler-generated method of a selected frame class.
/// (2) On entry to a scope with captured variables, we create a frame object and store it in a local variable.
/// (3) References to captured variables are transformed into references to fields of a frame class.
///
/// In addition, the rewriting deposits into <see cref="TypeCompilationState.SynthesizedMethods"/>
/// a (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pair for each generated method.
///
/// <see cref="Rewrite"/> produces its output in two forms. First, it returns a new bound statement
/// for the caller to use for the body of the original method. Second, it returns a collection of
/// (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pairs for additional methods that the lambda rewriter produced.
/// These additional methods contain the bodies of the lambdas moved into ordinary methods of their
/// respective frame classes, and the caller is responsible for processing them just as it does with
/// the returned bound node. For example, the caller will typically perform iterator method and
/// asynchronous method transformations, and emit IL instructions into an assembly.
/// </summary>
internal sealed partial class ClosureConversion : MethodToClassRewriter
{
private readonly Analysis _analysis;
private readonly MethodSymbol _topLevelMethod;
private readonly MethodSymbol _substitutedSourceMethod;
private readonly int _topLevelMethodOrdinal;
// lambda frame for static lambdas.
// initialized lazily and could be null if there are no static lambdas
private SynthesizedClosureEnvironment _lazyStaticLambdaFrame;
// A mapping from every lambda parameter to its corresponding method's parameter.
private readonly Dictionary<ParameterSymbol, ParameterSymbol> _parameterMap = new Dictionary<ParameterSymbol, ParameterSymbol>();
// for each block with lifted (captured) variables, the corresponding frame type
private readonly Dictionary<BoundNode, Analysis.ClosureEnvironment> _frames = new Dictionary<BoundNode, Analysis.ClosureEnvironment>();
// the current set of frame pointers in scope. Each is either a local variable (where introduced),
// or the "this" parameter when at the top level. Keys in this map are never constructed types.
private readonly Dictionary<NamedTypeSymbol, Symbol> _framePointers = new Dictionary<NamedTypeSymbol, Symbol>();
// The set of original locals that should be assigned to proxies
// if lifted. This is useful for the expression evaluator where
// the original locals are left as is.
private readonly HashSet<LocalSymbol> _assignLocals;
// The current method or lambda being processed.
private MethodSymbol _currentMethod;
// The "this" symbol for the current method.
private ParameterSymbol _currentFrameThis;
private readonly ArrayBuilder<LambdaDebugInfo> _lambdaDebugInfoBuilder;
// ID dispenser for field names of frame references
private int _synthesizedFieldNameIdDispenser;
// The symbol (field or local) holding the innermost frame
private Symbol _innermostFramePointer;
// The mapping of type parameters for the current lambda body
private TypeMap _currentLambdaBodyTypeMap;
// The current set of type parameters (mapped from the enclosing method's type parameters)
private ImmutableArray<TypeParameterSymbol> _currentTypeParameters;
// Initialization for the proxy of the upper frame if it needs to be deferred.
// Such situation happens when lifting this in a ctor.
private BoundExpression _thisProxyInitDeferred;
// Set to true once we've seen the base (or self) constructor invocation in a constructor
private bool _seenBaseCall;
// Set to true while translating code inside of an expression lambda.
private bool _inExpressionLambda;
// When a lambda captures only 'this' of the enclosing method, we cache it in a local
// variable. This is the set of such local variables that must be added to the enclosing
// method's top-level block.
private ArrayBuilder<LocalSymbol> _addedLocals;
// Similarly, this is the set of statements that must be added to the enclosing method's
// top-level block initializing those variables to null.
private ArrayBuilder<BoundStatement> _addedStatements;
/// <summary>
/// Temporary bag for methods synthesized by the rewriting. Added to
/// <see cref="TypeCompilationState.SynthesizedMethods"/> at the end of rewriting.
/// </summary>
private ArrayBuilder<TypeCompilationState.MethodWithBody> _synthesizedMethods;
/// <summary>
/// TODO(https://github.com/dotnet/roslyn/projects/26): Delete this.
/// This should only be used by <see cref="NeedsProxy(Symbol)"/> which
/// hasn't had logic to move the proxy analysis into <see cref="Analysis"/>,
/// where the <see cref="Analysis.ScopeTree"/> could be walked to build
/// the proxy list.
/// </summary>
private readonly ImmutableHashSet<Symbol> _allCapturedVariables;
#nullable enable
private ClosureConversion(
Analysis analysis,
NamedTypeSymbol thisType,
ParameterSymbol thisParameterOpt,
MethodSymbol method,
int methodOrdinal,
MethodSymbol substitutedSourceMethod,
ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics,
HashSet<LocalSymbol> assignLocals)
: base(slotAllocatorOpt, compilationState, diagnostics)
{
RoslynDebug.Assert(analysis != null);
RoslynDebug.Assert((object)thisType != null);
RoslynDebug.Assert(method != null);
RoslynDebug.Assert(compilationState != null);
RoslynDebug.Assert(diagnostics != null);
_topLevelMethod = method;
_substitutedSourceMethod = substitutedSourceMethod;
_topLevelMethodOrdinal = methodOrdinal;
_lambdaDebugInfoBuilder = lambdaDebugInfoBuilder;
_currentMethod = method;
_analysis = analysis;
_assignLocals = assignLocals;
_currentTypeParameters = method.TypeParameters;
_currentLambdaBodyTypeMap = TypeMap.Empty;
_innermostFramePointer = _currentFrameThis = thisParameterOpt;
_framePointers[thisType] = thisParameterOpt;
_seenBaseCall = method.MethodKind != MethodKind.Constructor; // only used for ctors
_synthesizedFieldNameIdDispenser = 1;
var allCapturedVars = ImmutableHashSet.CreateBuilder<Symbol>();
Analysis.VisitNestedFunctions(analysis.ScopeTree, (scope, function) =>
{
allCapturedVars.UnionWith(function.CapturedVariables);
});
_allCapturedVariables = allCapturedVars.ToImmutable();
}
#nullable disable
protected override bool NeedsProxy(Symbol localOrParameter)
{
Debug.Assert(localOrParameter is LocalSymbol || localOrParameter is ParameterSymbol ||
(localOrParameter as MethodSymbol)?.MethodKind == MethodKind.LocalFunction);
return _allCapturedVariables.Contains(localOrParameter);
}
/// <summary>
/// Rewrite the given node to eliminate lambda expressions. Also returned are the method symbols and their
/// bound bodies for the extracted lambda bodies. These would typically be emitted by the caller such as
/// MethodBodyCompiler. See this class' documentation
/// for a more thorough explanation of the algorithm and its use by clients.
/// </summary>
/// <param name="loweredBody">The bound node to be rewritten</param>
/// <param name="thisType">The type of the top-most frame</param>
/// <param name="thisParameter">The "this" parameter in the top-most frame, or null if static method</param>
/// <param name="method">The containing method of the node to be rewritten</param>
/// <param name="methodOrdinal">Index of the method symbol in its containing type member list.</param>
/// <param name="substitutedSourceMethod">If this is non-null, then <paramref name="method"/> will be treated as this for uses of parent symbols. For use in EE.</param>
/// <param name="lambdaDebugInfoBuilder">Information on lambdas defined in <paramref name="method"/> needed for debugging.</param>
/// <param name="closureDebugInfoBuilder">Information on closures defined in <paramref name="method"/> needed for debugging.</param>
/// <param name="slotAllocatorOpt">Slot allocator.</param>
/// <param name="compilationState">The caller's buffer into which we produce additional methods to be emitted by the caller</param>
/// <param name="diagnostics">Diagnostic bag for diagnostics</param>
/// <param name="assignLocals">The set of original locals that should be assigned to proxies if lifted</param>
public static BoundStatement Rewrite(
BoundStatement loweredBody,
NamedTypeSymbol thisType,
ParameterSymbol thisParameter,
MethodSymbol method,
int methodOrdinal,
MethodSymbol substitutedSourceMethod,
ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
ArrayBuilder<ClosureDebugInfo> closureDebugInfoBuilder,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics,
HashSet<LocalSymbol> assignLocals)
{
Debug.Assert((object)thisType != null);
Debug.Assert(((object)thisParameter == null) || (TypeSymbol.Equals(thisParameter.Type, thisType, TypeCompareKind.ConsiderEverything2)));
Debug.Assert(compilationState.ModuleBuilderOpt != null);
Debug.Assert(diagnostics.DiagnosticBag is object);
var analysis = Analysis.Analyze(
loweredBody,
method,
methodOrdinal,
substitutedSourceMethod,
slotAllocatorOpt,
compilationState,
closureDebugInfoBuilder,
diagnostics.DiagnosticBag);
CheckLocalsDefined(loweredBody);
var rewriter = new ClosureConversion(
analysis,
thisType,
thisParameter,
method,
methodOrdinal,
substitutedSourceMethod,
lambdaDebugInfoBuilder,
slotAllocatorOpt,
compilationState,
diagnostics,
assignLocals);
rewriter.SynthesizeClosureEnvironments(closureDebugInfoBuilder);
rewriter.SynthesizeClosureMethods();
var body = rewriter.AddStatementsIfNeeded(
(BoundStatement)rewriter.Visit(loweredBody));
// Add the completed methods to the compilation state
if (rewriter._synthesizedMethods != null)
{
if (compilationState.SynthesizedMethods == null)
{
compilationState.SynthesizedMethods = rewriter._synthesizedMethods;
}
else
{
compilationState.SynthesizedMethods.AddRange(rewriter._synthesizedMethods);
rewriter._synthesizedMethods.Free();
}
}
CheckLocalsDefined(body);
analysis.Free();
return body;
}
private BoundStatement AddStatementsIfNeeded(BoundStatement body)
{
if (_addedLocals != null)
{
_addedStatements.Add(body);
body = new BoundBlock(body.Syntax, _addedLocals.ToImmutableAndFree(), _addedStatements.ToImmutableAndFree()) { WasCompilerGenerated = true };
_addedLocals = null;
_addedStatements = null;
}
else
{
Debug.Assert(_addedStatements == null);
}
return body;
}
protected override TypeMap TypeMap
{
get { return _currentLambdaBodyTypeMap; }
}
protected override MethodSymbol CurrentMethod
{
get { return _currentMethod; }
}
protected override NamedTypeSymbol ContainingType
{
get { return _topLevelMethod.ContainingType; }
}
/// <summary>
/// Check that the top-level node is well-defined, in the sense that all
/// locals that are used are defined in some enclosing scope.
/// </summary>
static partial void CheckLocalsDefined(BoundNode node);
/// <summary>
/// Adds <see cref="SynthesizedClosureEnvironment"/> synthesized types to the compilation state
/// and creates hoisted fields for all locals captured by the environments.
/// </summary>
private void SynthesizeClosureEnvironments(ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
{
Analysis.VisitScopeTree(_analysis.ScopeTree, scope =>
{
if (scope.DeclaredEnvironment is { } env)
{
Debug.Assert(!_frames.ContainsKey(scope.BoundNode));
var frame = MakeFrame(scope, env);
env.SynthesizedEnvironment = frame;
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(ContainingType, frame.GetCciAdapter());
if (frame.Constructor != null)
{
AddSynthesizedMethod(
frame.Constructor,
FlowAnalysisPass.AppendImplicitReturn(
MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, Diagnostics),
frame.Constructor));
}
_frames.Add(scope.BoundNode, env);
}
});
SynthesizedClosureEnvironment MakeFrame(Analysis.Scope scope, Analysis.ClosureEnvironment env)
{
var scopeBoundNode = scope.BoundNode;
var syntax = scopeBoundNode.Syntax;
Debug.Assert(syntax != null);
DebugId methodId = _analysis.GetTopLevelMethodId();
DebugId closureId = _analysis.GetClosureId(syntax, closureDebugInfo);
var containingMethod = scope.ContainingFunctionOpt?.OriginalMethodSymbol ?? _topLevelMethod;
if ((object)_substitutedSourceMethod != null && containingMethod == _topLevelMethod)
{
containingMethod = _substitutedSourceMethod;
}
var synthesizedEnv = new SynthesizedClosureEnvironment(
_topLevelMethod,
containingMethod,
env.IsStruct,
syntax,
methodId,
closureId);
foreach (var captured in env.CapturedVariables)
{
Debug.Assert(!proxies.ContainsKey(captured));
var hoistedField = LambdaCapturedVariable.Create(synthesizedEnv, captured, ref _synthesizedFieldNameIdDispenser);
proxies.Add(captured, new CapturedToFrameSymbolReplacement(hoistedField, isReusable: false));
synthesizedEnv.AddHoistedField(hoistedField);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(synthesizedEnv, hoistedField.GetCciAdapter());
}
return synthesizedEnv;
}
}
/// <summary>
/// Synthesize closure methods for all nested functions.
/// </summary>
private void SynthesizeClosureMethods()
{
Analysis.VisitNestedFunctions(_analysis.ScopeTree, (scope, nestedFunction) =>
{
var originalMethod = nestedFunction.OriginalMethodSymbol;
var syntax = originalMethod.DeclaringSyntaxReferences[0].GetSyntax();
int closureOrdinal;
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
DebugId topLevelMethodId;
DebugId lambdaId;
if (nestedFunction.ContainingEnvironmentOpt != null)
{
containerAsFrame = nestedFunction.ContainingEnvironmentOpt.SynthesizedEnvironment;
closureKind = ClosureKind.General;
translatedLambdaContainer = containerAsFrame;
closureOrdinal = containerAsFrame.ClosureOrdinal;
}
else if (nestedFunction.CapturesThis)
{
containerAsFrame = null;
translatedLambdaContainer = _topLevelMethod.ContainingType;
closureKind = ClosureKind.ThisOnly;
closureOrdinal = LambdaDebugInfo.ThisOnlyClosureOrdinal;
}
else if ((nestedFunction.CapturedEnvironments.Count == 0 &&
originalMethod.MethodKind == MethodKind.LambdaMethod &&
_analysis.MethodsConvertedToDelegates.Contains(originalMethod)) ||
// If we are in a variant interface, runtime might not consider the
// method synthesized directly within the interface as variant safe.
// For simplicity we do not perform precise analysis whether this would
// definitely be the case. If we are in a variant interface, we always force
// creation of a display class.
VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is object)
{
translatedLambdaContainer = containerAsFrame = GetStaticFrame(Diagnostics, syntax);
closureKind = ClosureKind.Singleton;
closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
}
else
{
// Lower directly onto the containing type
translatedLambdaContainer = _topLevelMethod.ContainingType;
containerAsFrame = null;
closureKind = ClosureKind.Static;
closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
}
Debug.Assert((object)translatedLambdaContainer != _topLevelMethod.ContainingType ||
VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is null);
// Move the body of the lambda to a freshly generated synthetic method on its frame.
topLevelMethodId = _analysis.GetTopLevelMethodId();
lambdaId = GetLambdaId(syntax, closureKind, closureOrdinal);
var synthesizedMethod = new SynthesizedClosureMethod(
translatedLambdaContainer,
getStructEnvironments(nestedFunction),
closureKind,
_topLevelMethod,
topLevelMethodId,
originalMethod,
nestedFunction.BlockSyntax,
lambdaId);
nestedFunction.SynthesizedLoweredMethod = synthesizedMethod;
});
static ImmutableArray<SynthesizedClosureEnvironment> getStructEnvironments(Analysis.NestedFunction function)
{
var environments = ArrayBuilder<SynthesizedClosureEnvironment>.GetInstance();
foreach (var env in function.CapturedEnvironments)
{
if (env.IsStruct)
{
environments.Add(env.SynthesizedEnvironment);
}
}
return environments.ToImmutableAndFree();
}
}
/// <summary>
/// Get the static container for closures or create one if one doesn't already exist.
/// </summary>
/// <param name="syntax">
/// associate the frame with the first lambda that caused it to exist.
/// we need to associate this with some syntax.
/// unfortunately either containing method or containing class could be synthetic
/// therefore could have no syntax.
/// </param>
private SynthesizedClosureEnvironment GetStaticFrame(BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
if ((object)_lazyStaticLambdaFrame == null)
{
var isNonGeneric = !_topLevelMethod.IsGenericMethod;
if (isNonGeneric)
{
_lazyStaticLambdaFrame = CompilationState.StaticLambdaFrame;
}
if ((object)_lazyStaticLambdaFrame == null)
{
DebugId methodId;
if (isNonGeneric)
{
methodId = new DebugId(DebugId.UndefinedOrdinal, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
else
{
methodId = _analysis.GetTopLevelMethodId();
}
DebugId closureId = default(DebugId);
// using _topLevelMethod as containing member because the static frame does not have generic parameters, except for the top level method's
var containingMethod = isNonGeneric ? null : (_substitutedSourceMethod ?? _topLevelMethod);
_lazyStaticLambdaFrame = new SynthesizedClosureEnvironment(
_topLevelMethod,
containingMethod,
isStruct: false,
scopeSyntaxOpt: null,
methodId: methodId,
closureId: closureId);
// non-generic static lambdas can share the frame
if (isNonGeneric)
{
CompilationState.StaticLambdaFrame = _lazyStaticLambdaFrame;
}
var frame = _lazyStaticLambdaFrame;
// add frame type and cache field
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(this.ContainingType, frame.GetCciAdapter());
// add its ctor (note Constructor can be null if TypeKind.Struct is passed in to LambdaFrame.ctor, but Class is passed in above)
AddSynthesizedMethod(
frame.Constructor,
FlowAnalysisPass.AppendImplicitReturn(
MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, diagnostics),
frame.Constructor));
// add cctor
// Frame.inst = new Frame()
var F = new SyntheticBoundNodeFactory(frame.StaticConstructor, syntax, CompilationState, diagnostics);
var body = F.Block(
F.Assignment(
F.Field(null, frame.SingletonCache),
F.New(frame.Constructor)),
new BoundReturnStatement(syntax, RefKind.None, null));
AddSynthesizedMethod(frame.StaticConstructor, body);
}
}
return _lazyStaticLambdaFrame;
}
/// <summary>
/// Produce a bound expression representing a pointer to a frame of a particular frame type.
/// </summary>
/// <param name="syntax">The syntax to attach to the bound nodes produced</param>
/// <param name="frameType">The type of frame to be returned</param>
/// <returns>A bound node that computes the pointer to the required frame</returns>
private BoundExpression FrameOfType(SyntaxNode syntax, NamedTypeSymbol frameType)
{
BoundExpression result = FramePointer(syntax, frameType.OriginalDefinition);
Debug.Assert(TypeSymbol.Equals(result.Type, frameType, TypeCompareKind.ConsiderEverything2));
return result;
}
/// <summary>
/// Produce a bound expression representing a pointer to a frame of a particular frame class.
/// Note that for generic frames, the frameClass parameter is the generic definition, but
/// the resulting expression will be constructed with the current type parameters.
/// </summary>
/// <param name="syntax">The syntax to attach to the bound nodes produced</param>
/// <param name="frameClass">The class type of frame to be returned</param>
/// <returns>A bound node that computes the pointer to the required frame</returns>
protected override BoundExpression FramePointer(SyntaxNode syntax, NamedTypeSymbol frameClass)
{
Debug.Assert(frameClass.IsDefinition);
// If in an instance method of the right type, we can just return the "this" pointer.
if ((object)_currentFrameThis != null && TypeSymbol.Equals(_currentFrameThis.Type, frameClass, TypeCompareKind.ConsiderEverything2))
{
return new BoundThisReference(syntax, frameClass);
}
// If the current method has by-ref struct closure parameters, and one of them is correct, use it.
var lambda = _currentMethod as SynthesizedClosureMethod;
if (lambda != null)
{
var start = lambda.ParameterCount - lambda.ExtraSynthesizedParameterCount;
for (var i = start; i < lambda.ParameterCount; i++)
{
var potentialParameter = lambda.Parameters[i];
if (TypeSymbol.Equals(potentialParameter.Type.OriginalDefinition, frameClass, TypeCompareKind.ConsiderEverything2))
{
return new BoundParameter(syntax, potentialParameter);
}
}
}
// Otherwise we need to return the value from a frame pointer local variable...
Symbol framePointer = _framePointers[frameClass];
CapturedSymbolReplacement proxyField;
if (proxies.TryGetValue(framePointer, out proxyField))
{
// However, frame pointer local variables themselves can be "captured". In that case
// the inner frames contain pointers to the enclosing frames. That is, nested
// frame pointers are organized in a linked list.
return proxyField.Replacement(syntax, frameType => FramePointer(syntax, frameType));
}
var localFrame = (LocalSymbol)framePointer;
return new BoundLocal(syntax, localFrame, null, localFrame.Type);
}
private static void InsertAndFreePrologue<T>(ArrayBuilder<BoundStatement> result, ArrayBuilder<T> prologue) where T : BoundNode
{
foreach (var node in prologue)
{
if (node is BoundStatement stmt)
{
result.Add(stmt);
}
else
{
result.Add(new BoundExpressionStatement(node.Syntax, (BoundExpression)(BoundNode)node));
}
}
prologue.Free();
}
/// <summary>
/// Introduce a frame around the translation of the given node.
/// </summary>
/// <param name="node">The node whose translation should be translated to contain a frame</param>
/// <param name="env">The environment for the translated node</param>
/// <param name="F">A function that computes the translation of the node. It receives lists of added statements and added symbols</param>
/// <returns>The translated statement, as returned from F</returns>
private BoundNode IntroduceFrame(BoundNode node, Analysis.ClosureEnvironment env, Func<ArrayBuilder<BoundExpression>, ArrayBuilder<LocalSymbol>, BoundNode> F)
{
var frame = env.SynthesizedEnvironment;
var frameTypeParameters = ImmutableArray.Create(_currentTypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t)), 0, frame.Arity);
NamedTypeSymbol frameType = frame.ConstructIfGeneric(frameTypeParameters);
Debug.Assert(frame.ScopeSyntaxOpt != null);
LocalSymbol framePointer = new SynthesizedLocal(_topLevelMethod, TypeWithAnnotations.Create(frameType), SynthesizedLocalKind.LambdaDisplayClass, frame.ScopeSyntaxOpt);
SyntaxNode syntax = node.Syntax;
// assign new frame to the frame variable
var prologue = ArrayBuilder<BoundExpression>.GetInstance();
if ((object)frame.Constructor != null)
{
MethodSymbol constructor = frame.Constructor.AsMember(frameType);
Debug.Assert(TypeSymbol.Equals(frameType, constructor.ContainingType, TypeCompareKind.ConsiderEverything2));
prologue.Add(new BoundAssignmentOperator(syntax,
new BoundLocal(syntax, framePointer, null, frameType),
new BoundObjectCreationExpression(syntax: syntax, constructor: constructor),
frameType));
}
CapturedSymbolReplacement oldInnermostFrameProxy = null;
if ((object)_innermostFramePointer != null)
{
proxies.TryGetValue(_innermostFramePointer, out oldInnermostFrameProxy);
if (env.CapturesParent)
{
var capturedFrame = LambdaCapturedVariable.Create(frame, _innermostFramePointer, ref _synthesizedFieldNameIdDispenser);
FieldSymbol frameParent = capturedFrame.AsMember(frameType);
BoundExpression left = new BoundFieldAccess(syntax, new BoundLocal(syntax, framePointer, null, frameType), frameParent, null);
BoundExpression right = FrameOfType(syntax, frameParent.Type as NamedTypeSymbol);
BoundExpression assignment = new BoundAssignmentOperator(syntax, left, right, left.Type);
prologue.Add(assignment);
if (CompilationState.Emitting)
{
Debug.Assert(capturedFrame.Type.IsReferenceType); // Make sure we're not accidentally capturing a struct by value
frame.AddHoistedField(capturedFrame);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(frame, capturedFrame.GetCciAdapter());
}
proxies[_innermostFramePointer] = new CapturedToFrameSymbolReplacement(capturedFrame, isReusable: false);
}
}
// Capture any parameters of this block. This would typically occur
// at the top level of a method or lambda with captured parameters.
foreach (var variable in env.CapturedVariables)
{
InitVariableProxy(syntax, variable, framePointer, prologue);
}
Symbol oldInnermostFramePointer = _innermostFramePointer;
if (!framePointer.Type.IsValueType)
{
_innermostFramePointer = framePointer;
}
var addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
addedLocals.Add(framePointer);
_framePointers.Add(frame, framePointer);
var result = F(prologue, addedLocals);
_innermostFramePointer = oldInnermostFramePointer;
if ((object)_innermostFramePointer != null)
{
if (oldInnermostFrameProxy != null)
{
proxies[_innermostFramePointer] = oldInnermostFrameProxy;
}
else
{
proxies.Remove(_innermostFramePointer);
}
}
return result;
}
private void InitVariableProxy(SyntaxNode syntax, Symbol symbol, LocalSymbol framePointer, ArrayBuilder<BoundExpression> prologue)
{
CapturedSymbolReplacement proxy;
if (proxies.TryGetValue(symbol, out proxy))
{
BoundExpression value;
switch (symbol.Kind)
{
case SymbolKind.Parameter:
var parameter = (ParameterSymbol)symbol;
ParameterSymbol parameterToUse;
if (!_parameterMap.TryGetValue(parameter, out parameterToUse))
{
parameterToUse = parameter;
}
value = new BoundParameter(syntax, parameterToUse);
break;
case SymbolKind.Local:
var local = (LocalSymbol)symbol;
if (_assignLocals == null || !_assignLocals.Contains(local))
{
return;
}
LocalSymbol localToUse;
if (!localMap.TryGetValue(local, out localToUse))
{
localToUse = local;
}
value = new BoundLocal(syntax, localToUse, null, localToUse.Type);
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
var left = proxy.Replacement(syntax, frameType1 => new BoundLocal(syntax, framePointer, null, framePointer.Type));
var assignToProxy = new BoundAssignmentOperator(syntax, left, value, value.Type);
if (_currentMethod.MethodKind == MethodKind.Constructor &&
symbol == _currentMethod.ThisParameter &&
!_seenBaseCall)
{
// Containing method is a constructor
// Initialization statement for the "this" proxy must be inserted
// after the constructor initializer statement block
Debug.Assert(_thisProxyInitDeferred == null);
_thisProxyInitDeferred = assignToProxy;
}
else
{
prologue.Add(assignToProxy);
}
}
}
#region Visit Methods
protected override BoundNode VisitUnhoistedParameter(BoundParameter node)
{
ParameterSymbol replacementParameter;
if (_parameterMap.TryGetValue(node.ParameterSymbol, out replacementParameter))
{
return new BoundParameter(node.Syntax, replacementParameter, node.HasErrors);
}
return base.VisitUnhoistedParameter(node);
}
public override BoundNode VisitThisReference(BoundThisReference node)
{
// "topLevelMethod.ThisParameter == null" can occur in a delegate creation expression because the method group
// in the argument can have a "this" receiver even when "this"
// is not captured because a static method is selected. But we do preserve
// the method group and its receiver in the bound tree.
// No need to capture "this" in such case.
// TODO: Why don't we drop "this" while lowering if method is static?
// Actually, considering that method group expression does not evaluate to a particular value
// why do we have it in the lowered tree at all?
return (_currentMethod == _topLevelMethod || _topLevelMethod.ThisParameter == null ?
node :
FramePointer(node.Syntax, (NamedTypeSymbol)node.Type));
}
public override BoundNode VisitBaseReference(BoundBaseReference node)
{
return (!_currentMethod.IsStatic && TypeSymbol.Equals(_currentMethod.ContainingType, _topLevelMethod.ContainingType, TypeCompareKind.ConsiderEverything2))
? node
: FramePointer(node.Syntax, _topLevelMethod.ContainingType); // technically, not the correct static type
}
/// <summary>
/// Rewrites a reference to an unlowered local function to the newly
/// lowered local function.
/// </summary>
private void RemapLocalFunction(
SyntaxNode syntax,
MethodSymbol localFunc,
out BoundExpression receiver,
out MethodSymbol method,
ref ImmutableArray<BoundExpression> arguments,
ref ImmutableArray<RefKind> argRefKinds)
{
Debug.Assert(localFunc.MethodKind == MethodKind.LocalFunction);
var function = Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, localFunc.OriginalDefinition);
var loweredSymbol = function.SynthesizedLoweredMethod;
// If the local function captured variables then they will be stored
// in frames and the frames need to be passed as extra parameters.
var frameCount = loweredSymbol.ExtraSynthesizedParameterCount;
if (frameCount != 0)
{
Debug.Assert(!arguments.IsDefault);
// Build a new list of arguments to pass to the local function
// call that includes any necessary capture frames
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(loweredSymbol.ParameterCount);
argumentsBuilder.AddRange(arguments);
var start = loweredSymbol.ParameterCount - frameCount;
for (int i = start; i < loweredSymbol.ParameterCount; i++)
{
// will always be a LambdaFrame, it's always a capture frame
var frameType = (NamedTypeSymbol)loweredSymbol.Parameters[i].Type.OriginalDefinition;
Debug.Assert(frameType is SynthesizedClosureEnvironment);
if (frameType.Arity > 0)
{
var typeParameters = ((SynthesizedClosureEnvironment)frameType).ConstructedFromTypeParameters;
Debug.Assert(typeParameters.Length == frameType.Arity);
var subst = this.TypeMap.SubstituteTypeParameters(typeParameters);
frameType = frameType.Construct(subst);
}
var frame = FrameOfType(syntax, frameType);
argumentsBuilder.Add(frame);
}
// frame arguments are passed by ref
// add corresponding refkinds
var refkindsBuilder = ArrayBuilder<RefKind>.GetInstance(argumentsBuilder.Count);
if (!argRefKinds.IsDefault)
{
refkindsBuilder.AddRange(argRefKinds);
}
else
{
refkindsBuilder.AddMany(RefKind.None, arguments.Length);
}
refkindsBuilder.AddMany(RefKind.Ref, frameCount);
arguments = argumentsBuilder.ToImmutableAndFree();
argRefKinds = refkindsBuilder.ToImmutableAndFree();
}
method = loweredSymbol;
NamedTypeSymbol constructedFrame;
RemapLambdaOrLocalFunction(syntax,
localFunc,
SubstituteTypeArguments(localFunc.TypeArgumentsWithAnnotations),
loweredSymbol.ClosureKind,
ref method,
out receiver,
out constructedFrame);
}
/// <summary>
/// Substitutes references from old type arguments to new type arguments
/// in the lowered methods.
/// </summary>
/// <example>
/// Consider the following method:
/// void M() {
/// void L<T>(T t) => Console.Write(t);
/// L("A");
/// }
///
/// In this example, L<T> is a local function that will be
/// lowered into its own method and the type parameter T will be
/// alpha renamed to something else (let's call it T'). In this case,
/// all references to the original type parameter T in L must be
/// rewritten to the renamed parameter, T'.
/// </example>
private ImmutableArray<TypeWithAnnotations> SubstituteTypeArguments(ImmutableArray<TypeWithAnnotations> typeArguments)
{
Debug.Assert(!typeArguments.IsDefault);
if (typeArguments.IsEmpty)
{
return typeArguments;
}
// We must perform this process repeatedly as local
// functions may nest inside one another and capture type
// parameters from the enclosing local functions. Each
// iteration of nesting will cause alpha-renaming of the captured
// parameters, meaning that we must replace until there are no
// more alpha-rename mappings.
//
// The method symbol references are different from all other
// substituted types in this context because the method symbol in
// local function references is not rewritten until all local
// functions have already been lowered. Everything else is rewritten
// by the visitors as the definition is lowered. This means that
// only one substitution happens per lowering, but we need to do
// N substitutions all at once, where N is the number of lowerings.
var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArguments.Length);
foreach (var typeArg in typeArguments)
{
TypeWithAnnotations oldTypeArg;
TypeWithAnnotations newTypeArg = typeArg;
do
{
oldTypeArg = newTypeArg;
newTypeArg = this.TypeMap.SubstituteType(oldTypeArg);
}
while (!TypeSymbol.Equals(oldTypeArg.Type, newTypeArg.Type, TypeCompareKind.ConsiderEverything));
// When type substitution does not change the type, it is expected to return the very same object.
// Therefore the loop is terminated when that type (as an object) does not change.
Debug.Assert((object)oldTypeArg.Type == newTypeArg.Type);
// The types are the same, so the last pass performed no substitutions.
// Therefore the annotations ought to be the same too.
Debug.Assert(oldTypeArg.NullableAnnotation == newTypeArg.NullableAnnotation);
builder.Add(newTypeArg);
}
return builder.ToImmutableAndFree();
}
private void RemapLambdaOrLocalFunction(
SyntaxNode syntax,
MethodSymbol originalMethod,
ImmutableArray<TypeWithAnnotations> typeArgumentsOpt,
ClosureKind closureKind,
ref MethodSymbol synthesizedMethod,
out BoundExpression receiver,
out NamedTypeSymbol constructedFrame)
{
var translatedLambdaContainer = synthesizedMethod.ContainingType;
var containerAsFrame = translatedLambdaContainer as SynthesizedClosureEnvironment;
// All of _currentTypeParameters might not be preserved here due to recursively calling upwards in the chain of local functions/lambdas
Debug.Assert((typeArgumentsOpt.IsDefault && !originalMethod.IsGenericMethod) || (typeArgumentsOpt.Length == originalMethod.Arity));
var totalTypeArgumentCount = (containerAsFrame?.Arity ?? 0) + synthesizedMethod.Arity;
var realTypeArguments = ImmutableArray.Create(_currentTypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t)), 0, totalTypeArgumentCount - originalMethod.Arity);
if (!typeArgumentsOpt.IsDefault)
{
realTypeArguments = realTypeArguments.Concat(typeArgumentsOpt);
}
if ((object)containerAsFrame != null && containerAsFrame.Arity != 0)
{
var containerTypeArguments = ImmutableArray.Create(realTypeArguments, 0, containerAsFrame.Arity);
realTypeArguments = ImmutableArray.Create(realTypeArguments, containerAsFrame.Arity, realTypeArguments.Length - containerAsFrame.Arity);
constructedFrame = containerAsFrame.Construct(containerTypeArguments);
}
else
{
constructedFrame = translatedLambdaContainer;
}
synthesizedMethod = synthesizedMethod.AsMember(constructedFrame);
if (synthesizedMethod.IsGenericMethod)
{
synthesizedMethod = synthesizedMethod.Construct(realTypeArguments);
}
else
{
Debug.Assert(realTypeArguments.Length == 0);
}
// for instance lambdas, receiver is the frame
// for static lambdas, get the singleton receiver
if (closureKind == ClosureKind.Singleton)
{
var field = containerAsFrame.SingletonCache.AsMember(constructedFrame);
receiver = new BoundFieldAccess(syntax, null, field, constantValueOpt: null);
}
else if (closureKind == ClosureKind.Static)
{
receiver = new BoundTypeExpression(syntax, null, synthesizedMethod.ContainingType);
}
else // ThisOnly and General
{
receiver = FrameOfType(syntax, constructedFrame);
}
}
public override BoundNode VisitCall(BoundCall node)
{
if (node.Method.MethodKind == MethodKind.LocalFunction)
{
var args = VisitList(node.Arguments);
var argRefKinds = node.ArgumentRefKindsOpt;
var type = VisitType(node.Type);
Debug.Assert(node.ArgsToParamsOpt.IsDefault, "should be done with argument reordering by now");
RemapLocalFunction(
node.Syntax,
node.Method,
out var receiver,
out var method,
ref args,
ref argRefKinds);
return node.Update(
receiver,
method,
args,
node.ArgumentNamesOpt,
argRefKinds,
node.IsDelegateCall,
node.Expanded,
node.InvokedAsExtensionMethod,
node.ArgsToParamsOpt,
node.DefaultArguments,
node.ResultKind,
type);
}
var visited = base.VisitCall(node);
if (visited.Kind != BoundKind.Call)
{
return visited;
}
var rewritten = (BoundCall)visited;
// Check if we need to init the 'this' proxy in a ctor call
if (!_seenBaseCall)
{
if (_currentMethod == _topLevelMethod && node.IsConstructorInitializer())
{
_seenBaseCall = true;
if (_thisProxyInitDeferred != null)
{
// Insert the this proxy assignment after the ctor call.
// Create bound sequence: { ctor call, thisProxyInitDeferred }
return new BoundSequence(
syntax: node.Syntax,
locals: ImmutableArray<LocalSymbol>.Empty,
sideEffects: ImmutableArray.Create<BoundExpression>(rewritten),
value: _thisProxyInitDeferred,
type: rewritten.Type);
}
}
}
return rewritten;
}
private BoundSequence RewriteSequence(BoundSequence node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
foreach (var effect in node.SideEffects)
{
var replacement = (BoundExpression)this.Visit(effect);
if (replacement != null) prologue.Add(replacement);
}
var newValue = (BoundExpression)this.Visit(node.Value);
var newType = this.VisitType(node.Type);
return node.Update(newLocals.ToImmutableAndFree(), prologue.ToImmutableAndFree(), newValue, newType);
}
public override BoundNode VisitBlock(BoundBlock node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
RewriteBlock(node, prologue, newLocals));
}
else
{
return RewriteBlock(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
private BoundBlock RewriteBlock(BoundBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
if (prologue.Count > 0)
{
newStatements.Add(BoundSequencePoint.CreateHidden());
}
InsertAndFreePrologue(newStatements, prologue);
foreach (var statement in node.Statements)
{
var replacement = (BoundStatement)this.Visit(statement);
if (replacement != null)
{
newStatements.Add(replacement);
}
}
// TODO: we may not need to update if there was nothing to rewrite.
return node.Update(newLocals.ToImmutableAndFree(), node.LocalFunctions, newStatements.ToImmutableAndFree());
}
public override BoundNode VisitScope(BoundScope node)
{
Debug.Assert(!node.Locals.IsEmpty);
var newLocals = ArrayBuilder<LocalSymbol>.GetInstance();
RewriteLocals(node.Locals, newLocals);
var statements = VisitList(node.Statements);
if (newLocals.Count == 0)
{
newLocals.Free();
return new BoundStatementList(node.Syntax, statements);
}
return node.Update(newLocals.ToImmutableAndFree(), statements);
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
return RewriteCatch(node, prologue, newLocals);
});
}
else
{
return RewriteCatch(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
private BoundNode RewriteCatch(BoundCatchBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
var rewrittenCatchLocals = newLocals.ToImmutableAndFree();
// If exception variable got lifted, IntroduceFrame will give us frame init prologue.
// It needs to run before the exception variable is accessed.
// To ensure that, we will make exception variable a sequence that performs prologue as its side-effects.
BoundExpression rewrittenExceptionSource = null;
var rewrittenFilterPrologue = (BoundStatementList)this.Visit(node.ExceptionFilterPrologueOpt);
var rewrittenFilter = (BoundExpression)this.Visit(node.ExceptionFilterOpt);
if (node.ExceptionSourceOpt != null)
{
rewrittenExceptionSource = (BoundExpression)Visit(node.ExceptionSourceOpt);
if (prologue.Count > 0)
{
rewrittenExceptionSource = new BoundSequence(
rewrittenExceptionSource.Syntax,
ImmutableArray.Create<LocalSymbol>(),
prologue.ToImmutable(),
rewrittenExceptionSource,
rewrittenExceptionSource.Type);
}
}
else if (prologue.Count > 0)
{
Debug.Assert(rewrittenFilter != null);
var prologueBuilder = ArrayBuilder<BoundStatement>.GetInstance(prologue.Count);
foreach (var p in prologue)
{
prologueBuilder.Add(new BoundExpressionStatement(p.Syntax, p) { WasCompilerGenerated = true });
}
if (rewrittenFilterPrologue != null)
{
prologueBuilder.AddRange(rewrittenFilterPrologue.Statements);
}
rewrittenFilterPrologue = new BoundStatementList(rewrittenFilter.Syntax, prologueBuilder.ToImmutableAndFree());
}
// done with this.
prologue.Free();
// rewrite filter and body
// NOTE: this will proxy all accesses to exception local if that got lifted.
var exceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt);
var rewrittenBlock = (BoundBlock)this.Visit(node.Body);
return node.Update(
rewrittenCatchLocals,
rewrittenExceptionSource,
exceptionTypeOpt,
rewrittenFilterPrologue,
rewrittenFilter,
rewrittenBlock,
node.IsSynthesizedAsyncCatchAll);
}
public override BoundNode VisitSequence(BoundSequence node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
return RewriteSequence(node, prologue, newLocals);
});
}
else
{
return RewriteSequence(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
public override BoundNode VisitStatementList(BoundStatementList node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
// That can occur for a BoundStatementList if it is the body of a method with captured parameters.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
InsertAndFreePrologue(newStatements, prologue);
foreach (var s in node.Statements)
{
newStatements.Add((BoundStatement)this.Visit(s));
}
return new BoundBlock(node.Syntax, newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree(), node.HasErrors);
});
}
else
{
return base.VisitStatementList(node);
}
}
public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
{
// A delegate creation expression of the form "new Action( ()=>{} )" is treated exactly like
// (Action)(()=>{})
if (node.Argument.Kind == BoundKind.Lambda)
{
return RewriteLambdaConversion((BoundLambda)node.Argument);
}
if (node.MethodOpt?.MethodKind == MethodKind.LocalFunction)
{
var arguments = default(ImmutableArray<BoundExpression>);
var argRefKinds = default(ImmutableArray<RefKind>);
RemapLocalFunction(
node.Syntax,
node.MethodOpt,
out var receiver,
out var method,
ref arguments,
ref argRefKinds);
return new BoundDelegateCreationExpression(
node.Syntax,
receiver,
method,
node.IsExtensionMethod,
VisitType(node.Type));
}
return base.VisitDelegateCreationExpression(node);
}
public override BoundNode VisitFunctionPointerLoad(BoundFunctionPointerLoad node)
{
if (node.TargetMethod.MethodKind == MethodKind.LocalFunction)
{
Debug.Assert(node.TargetMethod is { RequiresInstanceReceiver: false, IsStatic: true });
ImmutableArray<BoundExpression> arguments = default;
ImmutableArray<RefKind> argRefKinds = default;
RemapLocalFunction(
node.Syntax,
node.TargetMethod,
out BoundExpression receiver,
out MethodSymbol remappedMethod,
ref arguments,
ref argRefKinds);
Debug.Assert(arguments.IsDefault &&
argRefKinds.IsDefault &&
receiver.Kind == BoundKind.TypeExpression &&
remappedMethod is { RequiresInstanceReceiver: false, IsStatic: true });
return node.Update(remappedMethod, constrainedToTypeOpt: node.ConstrainedToTypeOpt, node.Type);
}
return base.VisitFunctionPointerLoad(node);
}
public override BoundNode VisitConversion(BoundConversion conversion)
{
// a conversion with a method should have been rewritten, e.g. to an invocation
Debug.Assert(_inExpressionLambda || conversion.Conversion.MethodSymbol is null);
Debug.Assert(conversion.ConversionKind != ConversionKind.MethodGroup);
if (conversion.ConversionKind == ConversionKind.AnonymousFunction)
{
var result = (BoundExpression)RewriteLambdaConversion((BoundLambda)conversion.Operand);
if (_inExpressionLambda && conversion.ExplicitCastInCode)
{
result = new BoundConversion(
syntax: conversion.Syntax,
operand: result,
conversion: conversion.Conversion,
isBaseConversion: false,
@checked: false,
explicitCastInCode: true,
conversionGroupOpt: conversion.ConversionGroupOpt,
constantValueOpt: conversion.ConstantValueOpt,
type: conversion.Type);
}
return result;
}
return base.VisitConversion(conversion);
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
BoundNode lambdaScope;
DebugId topLevelMethodId;
DebugId lambdaId;
RewriteLambdaOrLocalFunction(
node,
out closureKind,
out translatedLambdaContainer,
out containerAsFrame,
out lambdaScope,
out topLevelMethodId,
out lambdaId);
return new BoundNoOpStatement(node.Syntax, NoOpStatementFlavor.Default);
}
private DebugId GetLambdaId(SyntaxNode syntax, ClosureKind closureKind, int closureOrdinal)
{
Debug.Assert(syntax != null);
SyntaxNode lambdaOrLambdaBodySyntax;
bool isLambdaBody;
if (syntax is AnonymousFunctionExpressionSyntax anonymousFunction)
{
lambdaOrLambdaBodySyntax = anonymousFunction.Body;
isLambdaBody = true;
}
else if (syntax is LocalFunctionStatementSyntax localFunction)
{
lambdaOrLambdaBodySyntax = (SyntaxNode)localFunction.Body ?? localFunction.ExpressionBody?.Expression;
if (lambdaOrLambdaBodySyntax is null)
{
lambdaOrLambdaBodySyntax = localFunction;
isLambdaBody = false;
}
else
{
isLambdaBody = true;
}
}
else if (LambdaUtilities.IsQueryPairLambda(syntax))
{
// "pair" query lambdas
lambdaOrLambdaBodySyntax = syntax;
isLambdaBody = false;
Debug.Assert(closureKind == ClosureKind.Singleton);
}
else
{
// query lambdas
lambdaOrLambdaBodySyntax = syntax;
isLambdaBody = true;
}
Debug.Assert(!isLambdaBody || LambdaUtilities.IsLambdaBody(lambdaOrLambdaBodySyntax));
// determine lambda ordinal and calculate syntax offset
DebugId lambdaId;
DebugId previousLambdaId;
if (slotAllocatorOpt != null && slotAllocatorOpt.TryGetPreviousLambda(lambdaOrLambdaBodySyntax, isLambdaBody, out previousLambdaId))
{
lambdaId = previousLambdaId;
}
else
{
lambdaId = new DebugId(_lambdaDebugInfoBuilder.Count, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
int syntaxOffset = _topLevelMethod.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(lambdaOrLambdaBodySyntax), lambdaOrLambdaBodySyntax.SyntaxTree);
_lambdaDebugInfoBuilder.Add(new LambdaDebugInfo(syntaxOffset, lambdaId, closureOrdinal));
return lambdaId;
}
private SynthesizedClosureMethod RewriteLambdaOrLocalFunction(
IBoundLambdaOrFunction node,
out ClosureKind closureKind,
out NamedTypeSymbol translatedLambdaContainer,
out SynthesizedClosureEnvironment containerAsFrame,
out BoundNode lambdaScope,
out DebugId topLevelMethodId,
out DebugId lambdaId)
{
Analysis.NestedFunction function = Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, node.Symbol);
var synthesizedMethod = function.SynthesizedLoweredMethod;
Debug.Assert(synthesizedMethod != null);
closureKind = synthesizedMethod.ClosureKind;
translatedLambdaContainer = synthesizedMethod.ContainingType;
containerAsFrame = translatedLambdaContainer as SynthesizedClosureEnvironment;
topLevelMethodId = _analysis.GetTopLevelMethodId();
lambdaId = synthesizedMethod.LambdaId;
if (function.ContainingEnvironmentOpt != null)
{
// Find the scope of the containing environment
BoundNode tmpScope = null;
Analysis.VisitScopeTree(_analysis.ScopeTree, scope =>
{
if (scope.DeclaredEnvironment == function.ContainingEnvironmentOpt)
{
tmpScope = scope.BoundNode;
}
});
Debug.Assert(tmpScope != null);
lambdaScope = tmpScope;
}
else
{
lambdaScope = null;
}
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, synthesizedMethod.GetCciAdapter());
foreach (var parameter in node.Symbol.Parameters)
{
_parameterMap.Add(parameter, synthesizedMethod.Parameters[parameter.Ordinal]);
}
// rewrite the lambda body as the generated method's body
var oldMethod = _currentMethod;
var oldFrameThis = _currentFrameThis;
var oldTypeParameters = _currentTypeParameters;
var oldInnermostFramePointer = _innermostFramePointer;
var oldTypeMap = _currentLambdaBodyTypeMap;
var oldAddedStatements = _addedStatements;
var oldAddedLocals = _addedLocals;
_addedStatements = null;
_addedLocals = null;
// switch to the generated method
_currentMethod = synthesizedMethod;
if (closureKind == ClosureKind.Static || closureKind == ClosureKind.Singleton)
{
// no link from a static lambda to its container
_innermostFramePointer = _currentFrameThis = null;
}
else
{
_currentFrameThis = synthesizedMethod.ThisParameter;
_framePointers.TryGetValue(translatedLambdaContainer, out _innermostFramePointer);
}
_currentTypeParameters = containerAsFrame?.TypeParameters.Concat(synthesizedMethod.TypeParameters) ?? synthesizedMethod.TypeParameters;
_currentLambdaBodyTypeMap = synthesizedMethod.TypeMap;
if (node.Body is BoundBlock block)
{
var body = AddStatementsIfNeeded((BoundStatement)VisitBlock(block));
CheckLocalsDefined(body);
AddSynthesizedMethod(synthesizedMethod, body);
}
// return to the old method
_currentMethod = oldMethod;
_currentFrameThis = oldFrameThis;
_currentTypeParameters = oldTypeParameters;
_innermostFramePointer = oldInnermostFramePointer;
_currentLambdaBodyTypeMap = oldTypeMap;
_addedLocals = oldAddedLocals;
_addedStatements = oldAddedStatements;
return synthesizedMethod;
}
private void AddSynthesizedMethod(MethodSymbol method, BoundStatement body)
{
if (_synthesizedMethods == null)
{
_synthesizedMethods = ArrayBuilder<TypeCompilationState.MethodWithBody>.GetInstance();
}
_synthesizedMethods.Add(
new TypeCompilationState.MethodWithBody(
method,
body,
CompilationState.CurrentImportChain));
}
private BoundNode RewriteLambdaConversion(BoundLambda node)
{
var wasInExpressionLambda = _inExpressionLambda;
_inExpressionLambda = _inExpressionLambda || node.Type.IsExpressionTree();
if (_inExpressionLambda)
{
var newType = VisitType(node.Type);
var newBody = (BoundBlock)Visit(node.Body);
node = node.Update(node.UnboundLambda, node.Symbol, newBody, node.Diagnostics, node.Binder, newType);
var result0 = wasInExpressionLambda ? node : ExpressionLambdaRewriter.RewriteLambda(node, CompilationState, TypeMap, RecursionDepth, Diagnostics);
_inExpressionLambda = wasInExpressionLambda;
return result0;
}
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
BoundNode lambdaScope;
DebugId topLevelMethodId;
DebugId lambdaId;
SynthesizedClosureMethod synthesizedMethod = RewriteLambdaOrLocalFunction(
node,
out closureKind,
out translatedLambdaContainer,
out containerAsFrame,
out lambdaScope,
out topLevelMethodId,
out lambdaId);
MethodSymbol referencedMethod = synthesizedMethod;
BoundExpression receiver;
NamedTypeSymbol constructedFrame;
RemapLambdaOrLocalFunction(node.Syntax, node.Symbol, default(ImmutableArray<TypeWithAnnotations>), closureKind, ref referencedMethod, out receiver, out constructedFrame);
// Rewrite the lambda expression (and the enclosing anonymous method conversion) as a delegate creation expression
TypeSymbol type = this.VisitType(node.Type);
// static lambdas are emitted as instance methods on a singleton receiver
// delegates invoke dispatch is optimized for instance delegates so
// it is preferable to emit lambdas as instance methods even when lambdas
// do not capture anything
BoundExpression result = new BoundDelegateCreationExpression(
node.Syntax,
receiver,
referencedMethod,
isExtensionMethod: false,
type: type);
// if the block containing the lambda is not the innermost block,
// or the lambda is static, then the lambda object should be cached in its frame.
// NOTE: we are not caching static lambdas in static ctors - cannot reuse such cache.
var shouldCacheForStaticMethod = closureKind == ClosureKind.Singleton &&
_currentMethod.MethodKind != MethodKind.StaticConstructor &&
!referencedMethod.IsGenericMethod;
// NOTE: We require "lambdaScope != null".
// We do not want to introduce a field into an actual user's class (not a synthetic frame).
var shouldCacheInLoop = lambdaScope != null &&
lambdaScope != Analysis.GetScopeParent(_analysis.ScopeTree, node.Body).BoundNode &&
InLoopOrLambda(node.Syntax, lambdaScope.Syntax);
if (shouldCacheForStaticMethod || shouldCacheInLoop)
{
// replace the expression "new Delegate(frame.M)" with "frame.cache ?? (frame.cache = new Delegate(frame.M));
var F = new SyntheticBoundNodeFactory(_currentMethod, node.Syntax, CompilationState, Diagnostics);
try
{
BoundExpression cache;
if (shouldCacheForStaticMethod || shouldCacheInLoop && (object)containerAsFrame != null)
{
// Since the cache variable will be in a container with possibly alpha-rewritten generic parameters, we need to
// substitute the original type according to the type map for that container. That substituted type may be
// different from the local variable `type`, which has the node's type substituted for the current container.
var cacheVariableType = containerAsFrame.TypeMap.SubstituteType(node.Type).Type;
var hasTypeParametersFromAnyMethod = cacheVariableType.ContainsMethodTypeParameter();
// If we want to cache a variable by moving its value into a field,
// the variable cannot use any type parameter from the method it is currently declared within.
if (!hasTypeParametersFromAnyMethod)
{
var cacheVariableName = GeneratedNames.MakeLambdaCacheFieldName(
// If we are generating the field into a display class created exclusively for the lambda the lambdaOrdinal itself is unique already,
// no need to include the top-level method ordinal in the field name.
(closureKind == ClosureKind.General) ? -1 : topLevelMethodId.Ordinal,
topLevelMethodId.Generation,
lambdaId.Ordinal,
lambdaId.Generation);
var cacheField = new SynthesizedLambdaCacheFieldSymbol(translatedLambdaContainer, cacheVariableType, cacheVariableName, _topLevelMethod, isReadOnly: false, isStatic: closureKind == ClosureKind.Singleton);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, cacheField.GetCciAdapter());
cache = F.Field(receiver, cacheField.AsMember(constructedFrame)); //NOTE: the field was added to the unconstructed frame type.
result = F.Coalesce(cache, F.AssignmentExpression(cache, result));
}
}
else
{
// the lambda captures at most the "this" of the enclosing method. We cache its delegate in a local variable.
var cacheLocal = F.SynthesizedLocal(type, kind: SynthesizedLocalKind.CachedAnonymousMethodDelegate);
if (_addedLocals == null) _addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
_addedLocals.Add(cacheLocal);
if (_addedStatements == null) _addedStatements = ArrayBuilder<BoundStatement>.GetInstance();
cache = F.Local(cacheLocal);
_addedStatements.Add(F.Assignment(cache, F.Null(type)));
result = F.Coalesce(cache, F.AssignmentExpression(cache, result));
}
}
catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
{
Diagnostics.Add(ex.Diagnostic);
return new BoundBadExpression(F.Syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<BoundExpression>(node), node.Type);
}
}
return result;
}
// This helper checks syntactically whether there is a loop or lambda expression
// between given lambda syntax and the syntax that corresponds to its closure.
// we use this heuristic as a hint that the lambda delegate may be created
// multiple times with same closure.
// In such cases it makes sense to cache the delegate.
//
// Examples:
// int x = 123;
// for (int i = 1; i< 10; i++)
// {
// if (i< 2)
// {
// arr[i].Execute(arg => arg + x); // delegate should be cached
// }
// }
// for (int i = 1; i< 10; i++)
// {
// var val = i;
// if (i< 2)
// {
// int y = i + i;
// System.Console.WriteLine(y);
// arr[i].Execute(arg => arg + val); // delegate should NOT be cached (closure created inside the loop)
// }
// }
//
private static bool InLoopOrLambda(SyntaxNode lambdaSyntax, SyntaxNode scopeSyntax)
{
var curSyntax = lambdaSyntax.Parent;
while (curSyntax != null && curSyntax != scopeSyntax)
{
switch (curSyntax.Kind())
{
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
return true;
}
curSyntax = curSyntax.Parent;
}
return false;
}
public override BoundNode VisitLambda(BoundLambda node)
{
// these nodes have been handled in the context of the enclosing anonymous method conversion.
throw ExceptionUtilities.Unreachable;
}
#endregion
#if CHECK_LOCALS
/// <summary>
/// Ensure that local variables are always in scope where used in bound trees
/// </summary>
/// <param name="node"></param>
static partial void CheckLocalsDefined(BoundNode node)
{
LocalsDefinedScanner.INSTANCE.Visit(node);
}
class LocalsDefinedScanner : BoundTreeWalker
{
internal static LocalsDefinedScanner INSTANCE = new LocalsDefinedScanner();
HashSet<Symbol> localsDefined = new HashSet<Symbol>();
public override BoundNode VisitLocal(BoundLocal node)
{
Debug.Assert(node.LocalSymbol.IsConst || localsDefined.Contains(node.LocalSymbol));
return base.VisitLocal(node);
}
public override BoundNode VisitSequence(BoundSequence node)
{
try
{
if (!node.Locals.IsNullOrEmpty)
foreach (var l in node.Locals)
localsDefined.Add(l);
return base.VisitSequence(node);
}
finally
{
if (!node.Locals.IsNullOrEmpty)
foreach (var l in node.Locals)
localsDefined.Remove(l);
}
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
try
{
if ((object)node.LocalOpt != null) localsDefined.Add(node.LocalOpt);
return base.VisitCatchBlock(node);
}
finally
{
if ((object)node.LocalOpt != null) localsDefined.Remove(node.LocalOpt);
}
}
public override BoundNode VisitSwitchStatement(BoundSwitchStatement node)
{
try
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Add(l);
return base.VisitSwitchStatement(node);
}
finally
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Remove(l);
}
}
public override BoundNode VisitBlock(BoundBlock node)
{
try
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Add(l);
return base.VisitBlock(node);
}
finally
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Remove(l);
}
}
}
#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
#if DEBUG
//#define CHECK_LOCALS // define CHECK_LOCALS to help debug some rewriting problems that would otherwise cause code-gen failures
#endif
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// The rewriter for removing lambda expressions from method bodies and introducing closure classes
/// as containers for captured variables along the lines of the example in section 6.5.3 of the
/// C# language specification. A closure is the lowered form of a nested function, consisting of a
/// synthesized method and a set of environments containing the captured variables.
///
/// The entry point is the public method <see cref="Rewrite"/>. It operates as follows:
///
/// First, an analysis of the whole method body is performed that determines which variables are
/// captured, what their scopes are, and what the nesting relationship is between scopes that
/// have captured variables. The result of this analysis is left in <see cref="_analysis"/>.
///
/// Then we make a frame, or compiler-generated class, represented by an instance of
/// <see cref="SynthesizedClosureEnvironment"/> for each scope with captured variables. The generated frames are kept
/// in <see cref="_frames"/>. Each frame is given a single field for each captured
/// variable in the corresponding scope. These are maintained in <see cref="MethodToClassRewriter.proxies"/>.
///
/// Next, we walk and rewrite the input bound tree, keeping track of the following:
/// (1) The current set of active frame pointers, in <see cref="_framePointers"/>
/// (2) The current method being processed (this changes within a lambda's body), in <see cref="_currentMethod"/>
/// (3) The "this" symbol for the current method in <see cref="_currentFrameThis"/>, and
/// (4) The symbol that is used to access the innermost frame pointer (it could be a local variable or "this" parameter)
///
/// Lastly, we visit the top-level method and each of the lowered methods
/// to rewrite references (e.g., calls and delegate conversions) to local
/// functions. We visit references to local functions separately from
/// lambdas because we may see the reference before we lower the target
/// local function. Lambdas, on the other hand, are always convertible as
/// they are being lowered.
///
/// There are a few key transformations done in the rewriting.
/// (1) Lambda expressions are turned into delegate creation expressions, and the body of the lambda is
/// moved into a new, compiler-generated method of a selected frame class.
/// (2) On entry to a scope with captured variables, we create a frame object and store it in a local variable.
/// (3) References to captured variables are transformed into references to fields of a frame class.
///
/// In addition, the rewriting deposits into <see cref="TypeCompilationState.SynthesizedMethods"/>
/// a (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pair for each generated method.
///
/// <see cref="Rewrite"/> produces its output in two forms. First, it returns a new bound statement
/// for the caller to use for the body of the original method. Second, it returns a collection of
/// (<see cref="MethodSymbol"/>, <see cref="BoundStatement"/>) pairs for additional methods that the lambda rewriter produced.
/// These additional methods contain the bodies of the lambdas moved into ordinary methods of their
/// respective frame classes, and the caller is responsible for processing them just as it does with
/// the returned bound node. For example, the caller will typically perform iterator method and
/// asynchronous method transformations, and emit IL instructions into an assembly.
/// </summary>
internal sealed partial class ClosureConversion : MethodToClassRewriter
{
private readonly Analysis _analysis;
private readonly MethodSymbol _topLevelMethod;
private readonly MethodSymbol _substitutedSourceMethod;
private readonly int _topLevelMethodOrdinal;
// lambda frame for static lambdas.
// initialized lazily and could be null if there are no static lambdas
private SynthesizedClosureEnvironment _lazyStaticLambdaFrame;
// A mapping from every lambda parameter to its corresponding method's parameter.
private readonly Dictionary<ParameterSymbol, ParameterSymbol> _parameterMap = new Dictionary<ParameterSymbol, ParameterSymbol>();
// for each block with lifted (captured) variables, the corresponding frame type
private readonly Dictionary<BoundNode, Analysis.ClosureEnvironment> _frames = new Dictionary<BoundNode, Analysis.ClosureEnvironment>();
// the current set of frame pointers in scope. Each is either a local variable (where introduced),
// or the "this" parameter when at the top level. Keys in this map are never constructed types.
private readonly Dictionary<NamedTypeSymbol, Symbol> _framePointers = new Dictionary<NamedTypeSymbol, Symbol>();
// The set of original locals that should be assigned to proxies
// if lifted. This is useful for the expression evaluator where
// the original locals are left as is.
private readonly HashSet<LocalSymbol> _assignLocals;
// The current method or lambda being processed.
private MethodSymbol _currentMethod;
// The "this" symbol for the current method.
private ParameterSymbol _currentFrameThis;
private readonly ArrayBuilder<LambdaDebugInfo> _lambdaDebugInfoBuilder;
// ID dispenser for field names of frame references
private int _synthesizedFieldNameIdDispenser;
// The symbol (field or local) holding the innermost frame
private Symbol _innermostFramePointer;
// The mapping of type parameters for the current lambda body
private TypeMap _currentLambdaBodyTypeMap;
// The current set of type parameters (mapped from the enclosing method's type parameters)
private ImmutableArray<TypeParameterSymbol> _currentTypeParameters;
// Initialization for the proxy of the upper frame if it needs to be deferred.
// Such situation happens when lifting this in a ctor.
private BoundExpression _thisProxyInitDeferred;
// Set to true once we've seen the base (or self) constructor invocation in a constructor
private bool _seenBaseCall;
// Set to true while translating code inside of an expression lambda.
private bool _inExpressionLambda;
// When a lambda captures only 'this' of the enclosing method, we cache it in a local
// variable. This is the set of such local variables that must be added to the enclosing
// method's top-level block.
private ArrayBuilder<LocalSymbol> _addedLocals;
// Similarly, this is the set of statements that must be added to the enclosing method's
// top-level block initializing those variables to null.
private ArrayBuilder<BoundStatement> _addedStatements;
/// <summary>
/// Temporary bag for methods synthesized by the rewriting. Added to
/// <see cref="TypeCompilationState.SynthesizedMethods"/> at the end of rewriting.
/// </summary>
private ArrayBuilder<TypeCompilationState.MethodWithBody> _synthesizedMethods;
/// <summary>
/// TODO(https://github.com/dotnet/roslyn/projects/26): Delete this.
/// This should only be used by <see cref="NeedsProxy(Symbol)"/> which
/// hasn't had logic to move the proxy analysis into <see cref="Analysis"/>,
/// where the <see cref="Analysis.ScopeTree"/> could be walked to build
/// the proxy list.
/// </summary>
private readonly ImmutableHashSet<Symbol> _allCapturedVariables;
#nullable enable
private ClosureConversion(
Analysis analysis,
NamedTypeSymbol thisType,
ParameterSymbol thisParameterOpt,
MethodSymbol method,
int methodOrdinal,
MethodSymbol substitutedSourceMethod,
ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics,
HashSet<LocalSymbol> assignLocals)
: base(slotAllocatorOpt, compilationState, diagnostics)
{
RoslynDebug.Assert(analysis != null);
RoslynDebug.Assert((object)thisType != null);
RoslynDebug.Assert(method != null);
RoslynDebug.Assert(compilationState != null);
RoslynDebug.Assert(diagnostics != null);
_topLevelMethod = method;
_substitutedSourceMethod = substitutedSourceMethod;
_topLevelMethodOrdinal = methodOrdinal;
_lambdaDebugInfoBuilder = lambdaDebugInfoBuilder;
_currentMethod = method;
_analysis = analysis;
_assignLocals = assignLocals;
_currentTypeParameters = method.TypeParameters;
_currentLambdaBodyTypeMap = TypeMap.Empty;
_innermostFramePointer = _currentFrameThis = thisParameterOpt;
_framePointers[thisType] = thisParameterOpt;
_seenBaseCall = method.MethodKind != MethodKind.Constructor; // only used for ctors
_synthesizedFieldNameIdDispenser = 1;
var allCapturedVars = ImmutableHashSet.CreateBuilder<Symbol>();
Analysis.VisitNestedFunctions(analysis.ScopeTree, (scope, function) =>
{
allCapturedVars.UnionWith(function.CapturedVariables);
});
_allCapturedVariables = allCapturedVars.ToImmutable();
}
#nullable disable
protected override bool NeedsProxy(Symbol localOrParameter)
{
Debug.Assert(localOrParameter is LocalSymbol || localOrParameter is ParameterSymbol ||
(localOrParameter as MethodSymbol)?.MethodKind == MethodKind.LocalFunction);
return _allCapturedVariables.Contains(localOrParameter);
}
/// <summary>
/// Rewrite the given node to eliminate lambda expressions. Also returned are the method symbols and their
/// bound bodies for the extracted lambda bodies. These would typically be emitted by the caller such as
/// MethodBodyCompiler. See this class' documentation
/// for a more thorough explanation of the algorithm and its use by clients.
/// </summary>
/// <param name="loweredBody">The bound node to be rewritten</param>
/// <param name="thisType">The type of the top-most frame</param>
/// <param name="thisParameter">The "this" parameter in the top-most frame, or null if static method</param>
/// <param name="method">The containing method of the node to be rewritten</param>
/// <param name="methodOrdinal">Index of the method symbol in its containing type member list.</param>
/// <param name="substitutedSourceMethod">If this is non-null, then <paramref name="method"/> will be treated as this for uses of parent symbols. For use in EE.</param>
/// <param name="lambdaDebugInfoBuilder">Information on lambdas defined in <paramref name="method"/> needed for debugging.</param>
/// <param name="closureDebugInfoBuilder">Information on closures defined in <paramref name="method"/> needed for debugging.</param>
/// <param name="slotAllocatorOpt">Slot allocator.</param>
/// <param name="compilationState">The caller's buffer into which we produce additional methods to be emitted by the caller</param>
/// <param name="diagnostics">Diagnostic bag for diagnostics</param>
/// <param name="assignLocals">The set of original locals that should be assigned to proxies if lifted</param>
public static BoundStatement Rewrite(
BoundStatement loweredBody,
NamedTypeSymbol thisType,
ParameterSymbol thisParameter,
MethodSymbol method,
int methodOrdinal,
MethodSymbol substitutedSourceMethod,
ArrayBuilder<LambdaDebugInfo> lambdaDebugInfoBuilder,
ArrayBuilder<ClosureDebugInfo> closureDebugInfoBuilder,
VariableSlotAllocator slotAllocatorOpt,
TypeCompilationState compilationState,
BindingDiagnosticBag diagnostics,
HashSet<LocalSymbol> assignLocals)
{
Debug.Assert((object)thisType != null);
Debug.Assert(((object)thisParameter == null) || (TypeSymbol.Equals(thisParameter.Type, thisType, TypeCompareKind.ConsiderEverything2)));
Debug.Assert(compilationState.ModuleBuilderOpt != null);
Debug.Assert(diagnostics.DiagnosticBag is object);
var analysis = Analysis.Analyze(
loweredBody,
method,
methodOrdinal,
substitutedSourceMethod,
slotAllocatorOpt,
compilationState,
closureDebugInfoBuilder,
diagnostics.DiagnosticBag);
CheckLocalsDefined(loweredBody);
var rewriter = new ClosureConversion(
analysis,
thisType,
thisParameter,
method,
methodOrdinal,
substitutedSourceMethod,
lambdaDebugInfoBuilder,
slotAllocatorOpt,
compilationState,
diagnostics,
assignLocals);
rewriter.SynthesizeClosureEnvironments(closureDebugInfoBuilder);
rewriter.SynthesizeClosureMethods();
var body = rewriter.AddStatementsIfNeeded(
(BoundStatement)rewriter.Visit(loweredBody));
// Add the completed methods to the compilation state
if (rewriter._synthesizedMethods != null)
{
if (compilationState.SynthesizedMethods == null)
{
compilationState.SynthesizedMethods = rewriter._synthesizedMethods;
}
else
{
compilationState.SynthesizedMethods.AddRange(rewriter._synthesizedMethods);
rewriter._synthesizedMethods.Free();
}
}
CheckLocalsDefined(body);
analysis.Free();
return body;
}
private BoundStatement AddStatementsIfNeeded(BoundStatement body)
{
if (_addedLocals != null)
{
_addedStatements.Add(body);
body = new BoundBlock(body.Syntax, _addedLocals.ToImmutableAndFree(), _addedStatements.ToImmutableAndFree()) { WasCompilerGenerated = true };
_addedLocals = null;
_addedStatements = null;
}
else
{
Debug.Assert(_addedStatements == null);
}
return body;
}
protected override TypeMap TypeMap
{
get { return _currentLambdaBodyTypeMap; }
}
protected override MethodSymbol CurrentMethod
{
get { return _currentMethod; }
}
protected override NamedTypeSymbol ContainingType
{
get { return _topLevelMethod.ContainingType; }
}
/// <summary>
/// Check that the top-level node is well-defined, in the sense that all
/// locals that are used are defined in some enclosing scope.
/// </summary>
static partial void CheckLocalsDefined(BoundNode node);
/// <summary>
/// Adds <see cref="SynthesizedClosureEnvironment"/> synthesized types to the compilation state
/// and creates hoisted fields for all locals captured by the environments.
/// </summary>
private void SynthesizeClosureEnvironments(ArrayBuilder<ClosureDebugInfo> closureDebugInfo)
{
Analysis.VisitScopeTree(_analysis.ScopeTree, scope =>
{
if (scope.DeclaredEnvironment is { } env)
{
Debug.Assert(!_frames.ContainsKey(scope.BoundNode));
var frame = MakeFrame(scope, env);
env.SynthesizedEnvironment = frame;
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(ContainingType, frame.GetCciAdapter());
if (frame.Constructor != null)
{
AddSynthesizedMethod(
frame.Constructor,
FlowAnalysisPass.AppendImplicitReturn(
MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, Diagnostics),
frame.Constructor));
}
_frames.Add(scope.BoundNode, env);
}
});
SynthesizedClosureEnvironment MakeFrame(Analysis.Scope scope, Analysis.ClosureEnvironment env)
{
var scopeBoundNode = scope.BoundNode;
var syntax = scopeBoundNode.Syntax;
Debug.Assert(syntax != null);
DebugId methodId = _analysis.GetTopLevelMethodId();
DebugId closureId = _analysis.GetClosureId(syntax, closureDebugInfo);
var containingMethod = scope.ContainingFunctionOpt?.OriginalMethodSymbol ?? _topLevelMethod;
if ((object)_substitutedSourceMethod != null && containingMethod == _topLevelMethod)
{
containingMethod = _substitutedSourceMethod;
}
var synthesizedEnv = new SynthesizedClosureEnvironment(
_topLevelMethod,
containingMethod,
env.IsStruct,
syntax,
methodId,
closureId);
foreach (var captured in env.CapturedVariables)
{
Debug.Assert(!proxies.ContainsKey(captured));
var hoistedField = LambdaCapturedVariable.Create(synthesizedEnv, captured, ref _synthesizedFieldNameIdDispenser);
proxies.Add(captured, new CapturedToFrameSymbolReplacement(hoistedField, isReusable: false));
synthesizedEnv.AddHoistedField(hoistedField);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(synthesizedEnv, hoistedField.GetCciAdapter());
}
return synthesizedEnv;
}
}
/// <summary>
/// Synthesize closure methods for all nested functions.
/// </summary>
private void SynthesizeClosureMethods()
{
Analysis.VisitNestedFunctions(_analysis.ScopeTree, (scope, nestedFunction) =>
{
var originalMethod = nestedFunction.OriginalMethodSymbol;
var syntax = originalMethod.DeclaringSyntaxReferences[0].GetSyntax();
int closureOrdinal;
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
DebugId topLevelMethodId;
DebugId lambdaId;
if (nestedFunction.ContainingEnvironmentOpt != null)
{
containerAsFrame = nestedFunction.ContainingEnvironmentOpt.SynthesizedEnvironment;
closureKind = ClosureKind.General;
translatedLambdaContainer = containerAsFrame;
closureOrdinal = containerAsFrame.ClosureOrdinal;
}
else if (nestedFunction.CapturesThis)
{
containerAsFrame = null;
translatedLambdaContainer = _topLevelMethod.ContainingType;
closureKind = ClosureKind.ThisOnly;
closureOrdinal = LambdaDebugInfo.ThisOnlyClosureOrdinal;
}
else if ((nestedFunction.CapturedEnvironments.Count == 0 &&
originalMethod.MethodKind == MethodKind.LambdaMethod &&
_analysis.MethodsConvertedToDelegates.Contains(originalMethod)) ||
// If we are in a variant interface, runtime might not consider the
// method synthesized directly within the interface as variant safe.
// For simplicity we do not perform precise analysis whether this would
// definitely be the case. If we are in a variant interface, we always force
// creation of a display class.
VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is object)
{
translatedLambdaContainer = containerAsFrame = GetStaticFrame(Diagnostics, syntax);
closureKind = ClosureKind.Singleton;
closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
}
else
{
// Lower directly onto the containing type
translatedLambdaContainer = _topLevelMethod.ContainingType;
containerAsFrame = null;
closureKind = ClosureKind.Static;
closureOrdinal = LambdaDebugInfo.StaticClosureOrdinal;
}
Debug.Assert((object)translatedLambdaContainer != _topLevelMethod.ContainingType ||
VarianceSafety.GetEnclosingVariantInterface(_topLevelMethod) is null);
// Move the body of the lambda to a freshly generated synthetic method on its frame.
topLevelMethodId = _analysis.GetTopLevelMethodId();
lambdaId = GetLambdaId(syntax, closureKind, closureOrdinal);
var synthesizedMethod = new SynthesizedClosureMethod(
translatedLambdaContainer,
getStructEnvironments(nestedFunction),
closureKind,
_topLevelMethod,
topLevelMethodId,
originalMethod,
nestedFunction.BlockSyntax,
lambdaId,
CompilationState);
nestedFunction.SynthesizedLoweredMethod = synthesizedMethod;
});
static ImmutableArray<SynthesizedClosureEnvironment> getStructEnvironments(Analysis.NestedFunction function)
{
var environments = ArrayBuilder<SynthesizedClosureEnvironment>.GetInstance();
foreach (var env in function.CapturedEnvironments)
{
if (env.IsStruct)
{
environments.Add(env.SynthesizedEnvironment);
}
}
return environments.ToImmutableAndFree();
}
}
/// <summary>
/// Get the static container for closures or create one if one doesn't already exist.
/// </summary>
/// <param name="syntax">
/// associate the frame with the first lambda that caused it to exist.
/// we need to associate this with some syntax.
/// unfortunately either containing method or containing class could be synthetic
/// therefore could have no syntax.
/// </param>
private SynthesizedClosureEnvironment GetStaticFrame(BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
if ((object)_lazyStaticLambdaFrame == null)
{
var isNonGeneric = !_topLevelMethod.IsGenericMethod;
if (isNonGeneric)
{
_lazyStaticLambdaFrame = CompilationState.StaticLambdaFrame;
}
if ((object)_lazyStaticLambdaFrame == null)
{
DebugId methodId;
if (isNonGeneric)
{
methodId = new DebugId(DebugId.UndefinedOrdinal, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
else
{
methodId = _analysis.GetTopLevelMethodId();
}
DebugId closureId = default(DebugId);
// using _topLevelMethod as containing member because the static frame does not have generic parameters, except for the top level method's
var containingMethod = isNonGeneric ? null : (_substitutedSourceMethod ?? _topLevelMethod);
_lazyStaticLambdaFrame = new SynthesizedClosureEnvironment(
_topLevelMethod,
containingMethod,
isStruct: false,
scopeSyntaxOpt: null,
methodId: methodId,
closureId: closureId);
// non-generic static lambdas can share the frame
if (isNonGeneric)
{
CompilationState.StaticLambdaFrame = _lazyStaticLambdaFrame;
}
var frame = _lazyStaticLambdaFrame;
// add frame type and cache field
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(this.ContainingType, frame.GetCciAdapter());
// add its ctor (note Constructor can be null if TypeKind.Struct is passed in to LambdaFrame.ctor, but Class is passed in above)
AddSynthesizedMethod(
frame.Constructor,
FlowAnalysisPass.AppendImplicitReturn(
MethodCompiler.BindMethodBody(frame.Constructor, CompilationState, diagnostics),
frame.Constructor));
// add cctor
// Frame.inst = new Frame()
var F = new SyntheticBoundNodeFactory(frame.StaticConstructor, syntax, CompilationState, diagnostics);
var body = F.Block(
F.Assignment(
F.Field(null, frame.SingletonCache),
F.New(frame.Constructor)),
new BoundReturnStatement(syntax, RefKind.None, null));
AddSynthesizedMethod(frame.StaticConstructor, body);
}
}
return _lazyStaticLambdaFrame;
}
/// <summary>
/// Produce a bound expression representing a pointer to a frame of a particular frame type.
/// </summary>
/// <param name="syntax">The syntax to attach to the bound nodes produced</param>
/// <param name="frameType">The type of frame to be returned</param>
/// <returns>A bound node that computes the pointer to the required frame</returns>
private BoundExpression FrameOfType(SyntaxNode syntax, NamedTypeSymbol frameType)
{
BoundExpression result = FramePointer(syntax, frameType.OriginalDefinition);
Debug.Assert(TypeSymbol.Equals(result.Type, frameType, TypeCompareKind.ConsiderEverything2));
return result;
}
/// <summary>
/// Produce a bound expression representing a pointer to a frame of a particular frame class.
/// Note that for generic frames, the frameClass parameter is the generic definition, but
/// the resulting expression will be constructed with the current type parameters.
/// </summary>
/// <param name="syntax">The syntax to attach to the bound nodes produced</param>
/// <param name="frameClass">The class type of frame to be returned</param>
/// <returns>A bound node that computes the pointer to the required frame</returns>
protected override BoundExpression FramePointer(SyntaxNode syntax, NamedTypeSymbol frameClass)
{
Debug.Assert(frameClass.IsDefinition);
// If in an instance method of the right type, we can just return the "this" pointer.
if ((object)_currentFrameThis != null && TypeSymbol.Equals(_currentFrameThis.Type, frameClass, TypeCompareKind.ConsiderEverything2))
{
return new BoundThisReference(syntax, frameClass);
}
// If the current method has by-ref struct closure parameters, and one of them is correct, use it.
var lambda = _currentMethod as SynthesizedClosureMethod;
if (lambda != null)
{
var start = lambda.ParameterCount - lambda.ExtraSynthesizedParameterCount;
for (var i = start; i < lambda.ParameterCount; i++)
{
var potentialParameter = lambda.Parameters[i];
if (TypeSymbol.Equals(potentialParameter.Type.OriginalDefinition, frameClass, TypeCompareKind.ConsiderEverything2))
{
return new BoundParameter(syntax, potentialParameter);
}
}
}
// Otherwise we need to return the value from a frame pointer local variable...
Symbol framePointer = _framePointers[frameClass];
CapturedSymbolReplacement proxyField;
if (proxies.TryGetValue(framePointer, out proxyField))
{
// However, frame pointer local variables themselves can be "captured". In that case
// the inner frames contain pointers to the enclosing frames. That is, nested
// frame pointers are organized in a linked list.
return proxyField.Replacement(syntax, frameType => FramePointer(syntax, frameType));
}
var localFrame = (LocalSymbol)framePointer;
return new BoundLocal(syntax, localFrame, null, localFrame.Type);
}
private static void InsertAndFreePrologue<T>(ArrayBuilder<BoundStatement> result, ArrayBuilder<T> prologue) where T : BoundNode
{
foreach (var node in prologue)
{
if (node is BoundStatement stmt)
{
result.Add(stmt);
}
else
{
result.Add(new BoundExpressionStatement(node.Syntax, (BoundExpression)(BoundNode)node));
}
}
prologue.Free();
}
/// <summary>
/// Introduce a frame around the translation of the given node.
/// </summary>
/// <param name="node">The node whose translation should be translated to contain a frame</param>
/// <param name="env">The environment for the translated node</param>
/// <param name="F">A function that computes the translation of the node. It receives lists of added statements and added symbols</param>
/// <returns>The translated statement, as returned from F</returns>
private BoundNode IntroduceFrame(BoundNode node, Analysis.ClosureEnvironment env, Func<ArrayBuilder<BoundExpression>, ArrayBuilder<LocalSymbol>, BoundNode> F)
{
var frame = env.SynthesizedEnvironment;
var frameTypeParameters = ImmutableArray.Create(_currentTypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t)), 0, frame.Arity);
NamedTypeSymbol frameType = frame.ConstructIfGeneric(frameTypeParameters);
Debug.Assert(frame.ScopeSyntaxOpt != null);
LocalSymbol framePointer = new SynthesizedLocal(_topLevelMethod, TypeWithAnnotations.Create(frameType), SynthesizedLocalKind.LambdaDisplayClass, frame.ScopeSyntaxOpt);
SyntaxNode syntax = node.Syntax;
// assign new frame to the frame variable
var prologue = ArrayBuilder<BoundExpression>.GetInstance();
if ((object)frame.Constructor != null)
{
MethodSymbol constructor = frame.Constructor.AsMember(frameType);
Debug.Assert(TypeSymbol.Equals(frameType, constructor.ContainingType, TypeCompareKind.ConsiderEverything2));
prologue.Add(new BoundAssignmentOperator(syntax,
new BoundLocal(syntax, framePointer, null, frameType),
new BoundObjectCreationExpression(syntax: syntax, constructor: constructor),
frameType));
}
CapturedSymbolReplacement oldInnermostFrameProxy = null;
if ((object)_innermostFramePointer != null)
{
proxies.TryGetValue(_innermostFramePointer, out oldInnermostFrameProxy);
if (env.CapturesParent)
{
var capturedFrame = LambdaCapturedVariable.Create(frame, _innermostFramePointer, ref _synthesizedFieldNameIdDispenser);
FieldSymbol frameParent = capturedFrame.AsMember(frameType);
BoundExpression left = new BoundFieldAccess(syntax, new BoundLocal(syntax, framePointer, null, frameType), frameParent, null);
BoundExpression right = FrameOfType(syntax, frameParent.Type as NamedTypeSymbol);
BoundExpression assignment = new BoundAssignmentOperator(syntax, left, right, left.Type);
prologue.Add(assignment);
if (CompilationState.Emitting)
{
Debug.Assert(capturedFrame.Type.IsReferenceType); // Make sure we're not accidentally capturing a struct by value
frame.AddHoistedField(capturedFrame);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(frame, capturedFrame.GetCciAdapter());
}
proxies[_innermostFramePointer] = new CapturedToFrameSymbolReplacement(capturedFrame, isReusable: false);
}
}
// Capture any parameters of this block. This would typically occur
// at the top level of a method or lambda with captured parameters.
foreach (var variable in env.CapturedVariables)
{
InitVariableProxy(syntax, variable, framePointer, prologue);
}
Symbol oldInnermostFramePointer = _innermostFramePointer;
if (!framePointer.Type.IsValueType)
{
_innermostFramePointer = framePointer;
}
var addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
addedLocals.Add(framePointer);
_framePointers.Add(frame, framePointer);
var result = F(prologue, addedLocals);
_innermostFramePointer = oldInnermostFramePointer;
if ((object)_innermostFramePointer != null)
{
if (oldInnermostFrameProxy != null)
{
proxies[_innermostFramePointer] = oldInnermostFrameProxy;
}
else
{
proxies.Remove(_innermostFramePointer);
}
}
return result;
}
private void InitVariableProxy(SyntaxNode syntax, Symbol symbol, LocalSymbol framePointer, ArrayBuilder<BoundExpression> prologue)
{
CapturedSymbolReplacement proxy;
if (proxies.TryGetValue(symbol, out proxy))
{
BoundExpression value;
switch (symbol.Kind)
{
case SymbolKind.Parameter:
var parameter = (ParameterSymbol)symbol;
ParameterSymbol parameterToUse;
if (!_parameterMap.TryGetValue(parameter, out parameterToUse))
{
parameterToUse = parameter;
}
value = new BoundParameter(syntax, parameterToUse);
break;
case SymbolKind.Local:
var local = (LocalSymbol)symbol;
if (_assignLocals == null || !_assignLocals.Contains(local))
{
return;
}
LocalSymbol localToUse;
if (!localMap.TryGetValue(local, out localToUse))
{
localToUse = local;
}
value = new BoundLocal(syntax, localToUse, null, localToUse.Type);
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
var left = proxy.Replacement(syntax, frameType1 => new BoundLocal(syntax, framePointer, null, framePointer.Type));
var assignToProxy = new BoundAssignmentOperator(syntax, left, value, value.Type);
if (_currentMethod.MethodKind == MethodKind.Constructor &&
symbol == _currentMethod.ThisParameter &&
!_seenBaseCall)
{
// Containing method is a constructor
// Initialization statement for the "this" proxy must be inserted
// after the constructor initializer statement block
Debug.Assert(_thisProxyInitDeferred == null);
_thisProxyInitDeferred = assignToProxy;
}
else
{
prologue.Add(assignToProxy);
}
}
}
#region Visit Methods
protected override BoundNode VisitUnhoistedParameter(BoundParameter node)
{
ParameterSymbol replacementParameter;
if (_parameterMap.TryGetValue(node.ParameterSymbol, out replacementParameter))
{
return new BoundParameter(node.Syntax, replacementParameter, node.HasErrors);
}
return base.VisitUnhoistedParameter(node);
}
public override BoundNode VisitThisReference(BoundThisReference node)
{
// "topLevelMethod.ThisParameter == null" can occur in a delegate creation expression because the method group
// in the argument can have a "this" receiver even when "this"
// is not captured because a static method is selected. But we do preserve
// the method group and its receiver in the bound tree.
// No need to capture "this" in such case.
// TODO: Why don't we drop "this" while lowering if method is static?
// Actually, considering that method group expression does not evaluate to a particular value
// why do we have it in the lowered tree at all?
return (_currentMethod == _topLevelMethod || _topLevelMethod.ThisParameter == null ?
node :
FramePointer(node.Syntax, (NamedTypeSymbol)node.Type));
}
public override BoundNode VisitBaseReference(BoundBaseReference node)
{
return (!_currentMethod.IsStatic && TypeSymbol.Equals(_currentMethod.ContainingType, _topLevelMethod.ContainingType, TypeCompareKind.ConsiderEverything2))
? node
: FramePointer(node.Syntax, _topLevelMethod.ContainingType); // technically, not the correct static type
}
/// <summary>
/// Rewrites a reference to an unlowered local function to the newly
/// lowered local function.
/// </summary>
private void RemapLocalFunction(
SyntaxNode syntax,
MethodSymbol localFunc,
out BoundExpression receiver,
out MethodSymbol method,
ref ImmutableArray<BoundExpression> arguments,
ref ImmutableArray<RefKind> argRefKinds)
{
Debug.Assert(localFunc.MethodKind == MethodKind.LocalFunction);
var function = Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, localFunc.OriginalDefinition);
var loweredSymbol = function.SynthesizedLoweredMethod;
// If the local function captured variables then they will be stored
// in frames and the frames need to be passed as extra parameters.
var frameCount = loweredSymbol.ExtraSynthesizedParameterCount;
if (frameCount != 0)
{
Debug.Assert(!arguments.IsDefault);
// Build a new list of arguments to pass to the local function
// call that includes any necessary capture frames
var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(loweredSymbol.ParameterCount);
argumentsBuilder.AddRange(arguments);
var start = loweredSymbol.ParameterCount - frameCount;
for (int i = start; i < loweredSymbol.ParameterCount; i++)
{
// will always be a LambdaFrame, it's always a capture frame
var frameType = (NamedTypeSymbol)loweredSymbol.Parameters[i].Type.OriginalDefinition;
Debug.Assert(frameType is SynthesizedClosureEnvironment);
if (frameType.Arity > 0)
{
var typeParameters = ((SynthesizedClosureEnvironment)frameType).ConstructedFromTypeParameters;
Debug.Assert(typeParameters.Length == frameType.Arity);
var subst = this.TypeMap.SubstituteTypeParameters(typeParameters);
frameType = frameType.Construct(subst);
}
var frame = FrameOfType(syntax, frameType);
argumentsBuilder.Add(frame);
}
// frame arguments are passed by ref
// add corresponding refkinds
var refkindsBuilder = ArrayBuilder<RefKind>.GetInstance(argumentsBuilder.Count);
if (!argRefKinds.IsDefault)
{
refkindsBuilder.AddRange(argRefKinds);
}
else
{
refkindsBuilder.AddMany(RefKind.None, arguments.Length);
}
refkindsBuilder.AddMany(RefKind.Ref, frameCount);
arguments = argumentsBuilder.ToImmutableAndFree();
argRefKinds = refkindsBuilder.ToImmutableAndFree();
}
method = loweredSymbol;
NamedTypeSymbol constructedFrame;
RemapLambdaOrLocalFunction(syntax,
localFunc,
SubstituteTypeArguments(localFunc.TypeArgumentsWithAnnotations),
loweredSymbol.ClosureKind,
ref method,
out receiver,
out constructedFrame);
}
/// <summary>
/// Substitutes references from old type arguments to new type arguments
/// in the lowered methods.
/// </summary>
/// <example>
/// Consider the following method:
/// void M() {
/// void L<T>(T t) => Console.Write(t);
/// L("A");
/// }
///
/// In this example, L<T> is a local function that will be
/// lowered into its own method and the type parameter T will be
/// alpha renamed to something else (let's call it T'). In this case,
/// all references to the original type parameter T in L must be
/// rewritten to the renamed parameter, T'.
/// </example>
private ImmutableArray<TypeWithAnnotations> SubstituteTypeArguments(ImmutableArray<TypeWithAnnotations> typeArguments)
{
Debug.Assert(!typeArguments.IsDefault);
if (typeArguments.IsEmpty)
{
return typeArguments;
}
// We must perform this process repeatedly as local
// functions may nest inside one another and capture type
// parameters from the enclosing local functions. Each
// iteration of nesting will cause alpha-renaming of the captured
// parameters, meaning that we must replace until there are no
// more alpha-rename mappings.
//
// The method symbol references are different from all other
// substituted types in this context because the method symbol in
// local function references is not rewritten until all local
// functions have already been lowered. Everything else is rewritten
// by the visitors as the definition is lowered. This means that
// only one substitution happens per lowering, but we need to do
// N substitutions all at once, where N is the number of lowerings.
var builder = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArguments.Length);
foreach (var typeArg in typeArguments)
{
TypeWithAnnotations oldTypeArg;
TypeWithAnnotations newTypeArg = typeArg;
do
{
oldTypeArg = newTypeArg;
newTypeArg = this.TypeMap.SubstituteType(oldTypeArg);
}
while (!TypeSymbol.Equals(oldTypeArg.Type, newTypeArg.Type, TypeCompareKind.ConsiderEverything));
// When type substitution does not change the type, it is expected to return the very same object.
// Therefore the loop is terminated when that type (as an object) does not change.
Debug.Assert((object)oldTypeArg.Type == newTypeArg.Type);
// The types are the same, so the last pass performed no substitutions.
// Therefore the annotations ought to be the same too.
Debug.Assert(oldTypeArg.NullableAnnotation == newTypeArg.NullableAnnotation);
builder.Add(newTypeArg);
}
return builder.ToImmutableAndFree();
}
private void RemapLambdaOrLocalFunction(
SyntaxNode syntax,
MethodSymbol originalMethod,
ImmutableArray<TypeWithAnnotations> typeArgumentsOpt,
ClosureKind closureKind,
ref MethodSymbol synthesizedMethod,
out BoundExpression receiver,
out NamedTypeSymbol constructedFrame)
{
var translatedLambdaContainer = synthesizedMethod.ContainingType;
var containerAsFrame = translatedLambdaContainer as SynthesizedClosureEnvironment;
// All of _currentTypeParameters might not be preserved here due to recursively calling upwards in the chain of local functions/lambdas
Debug.Assert((typeArgumentsOpt.IsDefault && !originalMethod.IsGenericMethod) || (typeArgumentsOpt.Length == originalMethod.Arity));
var totalTypeArgumentCount = (containerAsFrame?.Arity ?? 0) + synthesizedMethod.Arity;
var realTypeArguments = ImmutableArray.Create(_currentTypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t)), 0, totalTypeArgumentCount - originalMethod.Arity);
if (!typeArgumentsOpt.IsDefault)
{
realTypeArguments = realTypeArguments.Concat(typeArgumentsOpt);
}
if ((object)containerAsFrame != null && containerAsFrame.Arity != 0)
{
var containerTypeArguments = ImmutableArray.Create(realTypeArguments, 0, containerAsFrame.Arity);
realTypeArguments = ImmutableArray.Create(realTypeArguments, containerAsFrame.Arity, realTypeArguments.Length - containerAsFrame.Arity);
constructedFrame = containerAsFrame.Construct(containerTypeArguments);
}
else
{
constructedFrame = translatedLambdaContainer;
}
synthesizedMethod = synthesizedMethod.AsMember(constructedFrame);
if (synthesizedMethod.IsGenericMethod)
{
synthesizedMethod = synthesizedMethod.Construct(realTypeArguments);
}
else
{
Debug.Assert(realTypeArguments.Length == 0);
}
// for instance lambdas, receiver is the frame
// for static lambdas, get the singleton receiver
if (closureKind == ClosureKind.Singleton)
{
var field = containerAsFrame.SingletonCache.AsMember(constructedFrame);
receiver = new BoundFieldAccess(syntax, null, field, constantValueOpt: null);
}
else if (closureKind == ClosureKind.Static)
{
receiver = new BoundTypeExpression(syntax, null, synthesizedMethod.ContainingType);
}
else // ThisOnly and General
{
receiver = FrameOfType(syntax, constructedFrame);
}
}
public override BoundNode VisitCall(BoundCall node)
{
if (node.Method.MethodKind == MethodKind.LocalFunction)
{
var args = VisitList(node.Arguments);
var argRefKinds = node.ArgumentRefKindsOpt;
var type = VisitType(node.Type);
Debug.Assert(node.ArgsToParamsOpt.IsDefault, "should be done with argument reordering by now");
RemapLocalFunction(
node.Syntax,
node.Method,
out var receiver,
out var method,
ref args,
ref argRefKinds);
return node.Update(
receiver,
method,
args,
node.ArgumentNamesOpt,
argRefKinds,
node.IsDelegateCall,
node.Expanded,
node.InvokedAsExtensionMethod,
node.ArgsToParamsOpt,
node.DefaultArguments,
node.ResultKind,
type);
}
var visited = base.VisitCall(node);
if (visited.Kind != BoundKind.Call)
{
return visited;
}
var rewritten = (BoundCall)visited;
// Check if we need to init the 'this' proxy in a ctor call
if (!_seenBaseCall)
{
if (_currentMethod == _topLevelMethod && node.IsConstructorInitializer())
{
_seenBaseCall = true;
if (_thisProxyInitDeferred != null)
{
// Insert the this proxy assignment after the ctor call.
// Create bound sequence: { ctor call, thisProxyInitDeferred }
return new BoundSequence(
syntax: node.Syntax,
locals: ImmutableArray<LocalSymbol>.Empty,
sideEffects: ImmutableArray.Create<BoundExpression>(rewritten),
value: _thisProxyInitDeferred,
type: rewritten.Type);
}
}
}
return rewritten;
}
private BoundSequence RewriteSequence(BoundSequence node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
foreach (var effect in node.SideEffects)
{
var replacement = (BoundExpression)this.Visit(effect);
if (replacement != null) prologue.Add(replacement);
}
var newValue = (BoundExpression)this.Visit(node.Value);
var newType = this.VisitType(node.Type);
return node.Update(newLocals.ToImmutableAndFree(), prologue.ToImmutableAndFree(), newValue, newType);
}
public override BoundNode VisitBlock(BoundBlock node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
RewriteBlock(node, prologue, newLocals));
}
else
{
return RewriteBlock(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
private BoundBlock RewriteBlock(BoundBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
if (prologue.Count > 0)
{
newStatements.Add(BoundSequencePoint.CreateHidden());
}
InsertAndFreePrologue(newStatements, prologue);
foreach (var statement in node.Statements)
{
var replacement = (BoundStatement)this.Visit(statement);
if (replacement != null)
{
newStatements.Add(replacement);
}
}
// TODO: we may not need to update if there was nothing to rewrite.
return node.Update(newLocals.ToImmutableAndFree(), node.LocalFunctions, newStatements.ToImmutableAndFree());
}
public override BoundNode VisitScope(BoundScope node)
{
Debug.Assert(!node.Locals.IsEmpty);
var newLocals = ArrayBuilder<LocalSymbol>.GetInstance();
RewriteLocals(node.Locals, newLocals);
var statements = VisitList(node.Statements);
if (newLocals.Count == 0)
{
newLocals.Free();
return new BoundStatementList(node.Syntax, statements);
}
return node.Update(newLocals.ToImmutableAndFree(), statements);
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
return RewriteCatch(node, prologue, newLocals);
});
}
else
{
return RewriteCatch(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
private BoundNode RewriteCatch(BoundCatchBlock node, ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals)
{
RewriteLocals(node.Locals, newLocals);
var rewrittenCatchLocals = newLocals.ToImmutableAndFree();
// If exception variable got lifted, IntroduceFrame will give us frame init prologue.
// It needs to run before the exception variable is accessed.
// To ensure that, we will make exception variable a sequence that performs prologue as its side-effects.
BoundExpression rewrittenExceptionSource = null;
var rewrittenFilterPrologue = (BoundStatementList)this.Visit(node.ExceptionFilterPrologueOpt);
var rewrittenFilter = (BoundExpression)this.Visit(node.ExceptionFilterOpt);
if (node.ExceptionSourceOpt != null)
{
rewrittenExceptionSource = (BoundExpression)Visit(node.ExceptionSourceOpt);
if (prologue.Count > 0)
{
rewrittenExceptionSource = new BoundSequence(
rewrittenExceptionSource.Syntax,
ImmutableArray.Create<LocalSymbol>(),
prologue.ToImmutable(),
rewrittenExceptionSource,
rewrittenExceptionSource.Type);
}
}
else if (prologue.Count > 0)
{
Debug.Assert(rewrittenFilter != null);
var prologueBuilder = ArrayBuilder<BoundStatement>.GetInstance(prologue.Count);
foreach (var p in prologue)
{
prologueBuilder.Add(new BoundExpressionStatement(p.Syntax, p) { WasCompilerGenerated = true });
}
if (rewrittenFilterPrologue != null)
{
prologueBuilder.AddRange(rewrittenFilterPrologue.Statements);
}
rewrittenFilterPrologue = new BoundStatementList(rewrittenFilter.Syntax, prologueBuilder.ToImmutableAndFree());
}
// done with this.
prologue.Free();
// rewrite filter and body
// NOTE: this will proxy all accesses to exception local if that got lifted.
var exceptionTypeOpt = this.VisitType(node.ExceptionTypeOpt);
var rewrittenBlock = (BoundBlock)this.Visit(node.Body);
return node.Update(
rewrittenCatchLocals,
rewrittenExceptionSource,
exceptionTypeOpt,
rewrittenFilterPrologue,
rewrittenFilter,
rewrittenBlock,
node.IsSynthesizedAsyncCatchAll);
}
public override BoundNode VisitSequence(BoundSequence node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
return RewriteSequence(node, prologue, newLocals);
});
}
else
{
return RewriteSequence(node, ArrayBuilder<BoundExpression>.GetInstance(), ArrayBuilder<LocalSymbol>.GetInstance());
}
}
public override BoundNode VisitStatementList(BoundStatementList node)
{
// Test if this frame has captured variables and requires the introduction of a closure class.
// That can occur for a BoundStatementList if it is the body of a method with captured parameters.
if (_frames.TryGetValue(node, out var frame))
{
return IntroduceFrame(node, frame, (ArrayBuilder<BoundExpression> prologue, ArrayBuilder<LocalSymbol> newLocals) =>
{
var newStatements = ArrayBuilder<BoundStatement>.GetInstance();
InsertAndFreePrologue(newStatements, prologue);
foreach (var s in node.Statements)
{
newStatements.Add((BoundStatement)this.Visit(s));
}
return new BoundBlock(node.Syntax, newLocals.ToImmutableAndFree(), newStatements.ToImmutableAndFree(), node.HasErrors);
});
}
else
{
return base.VisitStatementList(node);
}
}
public override BoundNode VisitDelegateCreationExpression(BoundDelegateCreationExpression node)
{
// A delegate creation expression of the form "new Action( ()=>{} )" is treated exactly like
// (Action)(()=>{})
if (node.Argument.Kind == BoundKind.Lambda)
{
return RewriteLambdaConversion((BoundLambda)node.Argument);
}
if (node.MethodOpt?.MethodKind == MethodKind.LocalFunction)
{
var arguments = default(ImmutableArray<BoundExpression>);
var argRefKinds = default(ImmutableArray<RefKind>);
RemapLocalFunction(
node.Syntax,
node.MethodOpt,
out var receiver,
out var method,
ref arguments,
ref argRefKinds);
return new BoundDelegateCreationExpression(
node.Syntax,
receiver,
method,
node.IsExtensionMethod,
VisitType(node.Type));
}
return base.VisitDelegateCreationExpression(node);
}
public override BoundNode VisitFunctionPointerLoad(BoundFunctionPointerLoad node)
{
if (node.TargetMethod.MethodKind == MethodKind.LocalFunction)
{
Debug.Assert(node.TargetMethod is { RequiresInstanceReceiver: false, IsStatic: true });
ImmutableArray<BoundExpression> arguments = default;
ImmutableArray<RefKind> argRefKinds = default;
RemapLocalFunction(
node.Syntax,
node.TargetMethod,
out BoundExpression receiver,
out MethodSymbol remappedMethod,
ref arguments,
ref argRefKinds);
Debug.Assert(arguments.IsDefault &&
argRefKinds.IsDefault &&
receiver.Kind == BoundKind.TypeExpression &&
remappedMethod is { RequiresInstanceReceiver: false, IsStatic: true });
return node.Update(remappedMethod, constrainedToTypeOpt: node.ConstrainedToTypeOpt, node.Type);
}
return base.VisitFunctionPointerLoad(node);
}
public override BoundNode VisitConversion(BoundConversion conversion)
{
// a conversion with a method should have been rewritten, e.g. to an invocation
Debug.Assert(_inExpressionLambda || conversion.Conversion.MethodSymbol is null);
Debug.Assert(conversion.ConversionKind != ConversionKind.MethodGroup);
if (conversion.ConversionKind == ConversionKind.AnonymousFunction)
{
var result = (BoundExpression)RewriteLambdaConversion((BoundLambda)conversion.Operand);
if (_inExpressionLambda && conversion.ExplicitCastInCode)
{
result = new BoundConversion(
syntax: conversion.Syntax,
operand: result,
conversion: conversion.Conversion,
isBaseConversion: false,
@checked: false,
explicitCastInCode: true,
conversionGroupOpt: conversion.ConversionGroupOpt,
constantValueOpt: conversion.ConstantValueOpt,
type: conversion.Type);
}
return result;
}
return base.VisitConversion(conversion);
}
public override BoundNode VisitLocalFunctionStatement(BoundLocalFunctionStatement node)
{
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
BoundNode lambdaScope;
DebugId topLevelMethodId;
DebugId lambdaId;
RewriteLambdaOrLocalFunction(
node,
out closureKind,
out translatedLambdaContainer,
out containerAsFrame,
out lambdaScope,
out topLevelMethodId,
out lambdaId);
return new BoundNoOpStatement(node.Syntax, NoOpStatementFlavor.Default);
}
private DebugId GetLambdaId(SyntaxNode syntax, ClosureKind closureKind, int closureOrdinal)
{
Debug.Assert(syntax != null);
SyntaxNode lambdaOrLambdaBodySyntax;
bool isLambdaBody;
if (syntax is AnonymousFunctionExpressionSyntax anonymousFunction)
{
lambdaOrLambdaBodySyntax = anonymousFunction.Body;
isLambdaBody = true;
}
else if (syntax is LocalFunctionStatementSyntax localFunction)
{
lambdaOrLambdaBodySyntax = (SyntaxNode)localFunction.Body ?? localFunction.ExpressionBody?.Expression;
if (lambdaOrLambdaBodySyntax is null)
{
lambdaOrLambdaBodySyntax = localFunction;
isLambdaBody = false;
}
else
{
isLambdaBody = true;
}
}
else if (LambdaUtilities.IsQueryPairLambda(syntax))
{
// "pair" query lambdas
lambdaOrLambdaBodySyntax = syntax;
isLambdaBody = false;
Debug.Assert(closureKind == ClosureKind.Singleton);
}
else
{
// query lambdas
lambdaOrLambdaBodySyntax = syntax;
isLambdaBody = true;
}
Debug.Assert(!isLambdaBody || LambdaUtilities.IsLambdaBody(lambdaOrLambdaBodySyntax));
// determine lambda ordinal and calculate syntax offset
DebugId lambdaId;
DebugId previousLambdaId;
if (slotAllocatorOpt != null && slotAllocatorOpt.TryGetPreviousLambda(lambdaOrLambdaBodySyntax, isLambdaBody, out previousLambdaId))
{
lambdaId = previousLambdaId;
}
else
{
lambdaId = new DebugId(_lambdaDebugInfoBuilder.Count, CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal);
}
int syntaxOffset = _topLevelMethod.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(lambdaOrLambdaBodySyntax), lambdaOrLambdaBodySyntax.SyntaxTree);
_lambdaDebugInfoBuilder.Add(new LambdaDebugInfo(syntaxOffset, lambdaId, closureOrdinal));
return lambdaId;
}
private SynthesizedClosureMethod RewriteLambdaOrLocalFunction(
IBoundLambdaOrFunction node,
out ClosureKind closureKind,
out NamedTypeSymbol translatedLambdaContainer,
out SynthesizedClosureEnvironment containerAsFrame,
out BoundNode lambdaScope,
out DebugId topLevelMethodId,
out DebugId lambdaId)
{
Analysis.NestedFunction function = Analysis.GetNestedFunctionInTree(_analysis.ScopeTree, node.Symbol);
var synthesizedMethod = function.SynthesizedLoweredMethod;
Debug.Assert(synthesizedMethod != null);
closureKind = synthesizedMethod.ClosureKind;
translatedLambdaContainer = synthesizedMethod.ContainingType;
containerAsFrame = translatedLambdaContainer as SynthesizedClosureEnvironment;
topLevelMethodId = _analysis.GetTopLevelMethodId();
lambdaId = synthesizedMethod.LambdaId;
if (function.ContainingEnvironmentOpt != null)
{
// Find the scope of the containing environment
BoundNode tmpScope = null;
Analysis.VisitScopeTree(_analysis.ScopeTree, scope =>
{
if (scope.DeclaredEnvironment == function.ContainingEnvironmentOpt)
{
tmpScope = scope.BoundNode;
}
});
Debug.Assert(tmpScope != null);
lambdaScope = tmpScope;
}
else
{
lambdaScope = null;
}
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, synthesizedMethod.GetCciAdapter());
foreach (var parameter in node.Symbol.Parameters)
{
_parameterMap.Add(parameter, synthesizedMethod.Parameters[parameter.Ordinal]);
}
// rewrite the lambda body as the generated method's body
var oldMethod = _currentMethod;
var oldFrameThis = _currentFrameThis;
var oldTypeParameters = _currentTypeParameters;
var oldInnermostFramePointer = _innermostFramePointer;
var oldTypeMap = _currentLambdaBodyTypeMap;
var oldAddedStatements = _addedStatements;
var oldAddedLocals = _addedLocals;
_addedStatements = null;
_addedLocals = null;
// switch to the generated method
_currentMethod = synthesizedMethod;
if (closureKind == ClosureKind.Static || closureKind == ClosureKind.Singleton)
{
// no link from a static lambda to its container
_innermostFramePointer = _currentFrameThis = null;
}
else
{
_currentFrameThis = synthesizedMethod.ThisParameter;
_framePointers.TryGetValue(translatedLambdaContainer, out _innermostFramePointer);
}
_currentTypeParameters = containerAsFrame?.TypeParameters.Concat(synthesizedMethod.TypeParameters) ?? synthesizedMethod.TypeParameters;
_currentLambdaBodyTypeMap = synthesizedMethod.TypeMap;
if (node.Body is BoundBlock block)
{
var body = AddStatementsIfNeeded((BoundStatement)VisitBlock(block));
CheckLocalsDefined(body);
AddSynthesizedMethod(synthesizedMethod, body);
}
// return to the old method
_currentMethod = oldMethod;
_currentFrameThis = oldFrameThis;
_currentTypeParameters = oldTypeParameters;
_innermostFramePointer = oldInnermostFramePointer;
_currentLambdaBodyTypeMap = oldTypeMap;
_addedLocals = oldAddedLocals;
_addedStatements = oldAddedStatements;
return synthesizedMethod;
}
private void AddSynthesizedMethod(MethodSymbol method, BoundStatement body)
{
if (_synthesizedMethods == null)
{
_synthesizedMethods = ArrayBuilder<TypeCompilationState.MethodWithBody>.GetInstance();
}
_synthesizedMethods.Add(
new TypeCompilationState.MethodWithBody(
method,
body,
CompilationState.CurrentImportChain));
}
private BoundNode RewriteLambdaConversion(BoundLambda node)
{
var wasInExpressionLambda = _inExpressionLambda;
_inExpressionLambda = _inExpressionLambda || node.Type.IsExpressionTree();
if (_inExpressionLambda)
{
var newType = VisitType(node.Type);
var newBody = (BoundBlock)Visit(node.Body);
node = node.Update(node.UnboundLambda, node.Symbol, newBody, node.Diagnostics, node.Binder, newType);
var result0 = wasInExpressionLambda ? node : ExpressionLambdaRewriter.RewriteLambda(node, CompilationState, TypeMap, RecursionDepth, Diagnostics);
_inExpressionLambda = wasInExpressionLambda;
return result0;
}
ClosureKind closureKind;
NamedTypeSymbol translatedLambdaContainer;
SynthesizedClosureEnvironment containerAsFrame;
BoundNode lambdaScope;
DebugId topLevelMethodId;
DebugId lambdaId;
SynthesizedClosureMethod synthesizedMethod = RewriteLambdaOrLocalFunction(
node,
out closureKind,
out translatedLambdaContainer,
out containerAsFrame,
out lambdaScope,
out topLevelMethodId,
out lambdaId);
MethodSymbol referencedMethod = synthesizedMethod;
BoundExpression receiver;
NamedTypeSymbol constructedFrame;
RemapLambdaOrLocalFunction(node.Syntax, node.Symbol, default(ImmutableArray<TypeWithAnnotations>), closureKind, ref referencedMethod, out receiver, out constructedFrame);
// Rewrite the lambda expression (and the enclosing anonymous method conversion) as a delegate creation expression
TypeSymbol type = this.VisitType(node.Type);
// static lambdas are emitted as instance methods on a singleton receiver
// delegates invoke dispatch is optimized for instance delegates so
// it is preferable to emit lambdas as instance methods even when lambdas
// do not capture anything
BoundExpression result = new BoundDelegateCreationExpression(
node.Syntax,
receiver,
referencedMethod,
isExtensionMethod: false,
type: type);
// if the block containing the lambda is not the innermost block,
// or the lambda is static, then the lambda object should be cached in its frame.
// NOTE: we are not caching static lambdas in static ctors - cannot reuse such cache.
var shouldCacheForStaticMethod = closureKind == ClosureKind.Singleton &&
_currentMethod.MethodKind != MethodKind.StaticConstructor &&
!referencedMethod.IsGenericMethod;
// NOTE: We require "lambdaScope != null".
// We do not want to introduce a field into an actual user's class (not a synthetic frame).
var shouldCacheInLoop = lambdaScope != null &&
lambdaScope != Analysis.GetScopeParent(_analysis.ScopeTree, node.Body).BoundNode &&
InLoopOrLambda(node.Syntax, lambdaScope.Syntax);
if (shouldCacheForStaticMethod || shouldCacheInLoop)
{
// replace the expression "new Delegate(frame.M)" with "frame.cache ?? (frame.cache = new Delegate(frame.M));
var F = new SyntheticBoundNodeFactory(_currentMethod, node.Syntax, CompilationState, Diagnostics);
try
{
BoundExpression cache;
if (shouldCacheForStaticMethod || shouldCacheInLoop && (object)containerAsFrame != null)
{
// Since the cache variable will be in a container with possibly alpha-rewritten generic parameters, we need to
// substitute the original type according to the type map for that container. That substituted type may be
// different from the local variable `type`, which has the node's type substituted for the current container.
var cacheVariableType = containerAsFrame.TypeMap.SubstituteType(node.Type).Type;
var hasTypeParametersFromAnyMethod = cacheVariableType.ContainsMethodTypeParameter();
// If we want to cache a variable by moving its value into a field,
// the variable cannot use any type parameter from the method it is currently declared within.
if (!hasTypeParametersFromAnyMethod)
{
var cacheVariableName = GeneratedNames.MakeLambdaCacheFieldName(
// If we are generating the field into a display class created exclusively for the lambda the lambdaOrdinal itself is unique already,
// no need to include the top-level method ordinal in the field name.
(closureKind == ClosureKind.General) ? -1 : topLevelMethodId.Ordinal,
topLevelMethodId.Generation,
lambdaId.Ordinal,
lambdaId.Generation);
var cacheField = new SynthesizedLambdaCacheFieldSymbol(translatedLambdaContainer, cacheVariableType, cacheVariableName, _topLevelMethod, isReadOnly: false, isStatic: closureKind == ClosureKind.Singleton);
CompilationState.ModuleBuilderOpt.AddSynthesizedDefinition(translatedLambdaContainer, cacheField.GetCciAdapter());
cache = F.Field(receiver, cacheField.AsMember(constructedFrame)); //NOTE: the field was added to the unconstructed frame type.
result = F.Coalesce(cache, F.AssignmentExpression(cache, result));
}
}
else
{
// the lambda captures at most the "this" of the enclosing method. We cache its delegate in a local variable.
var cacheLocal = F.SynthesizedLocal(type, kind: SynthesizedLocalKind.CachedAnonymousMethodDelegate);
if (_addedLocals == null) _addedLocals = ArrayBuilder<LocalSymbol>.GetInstance();
_addedLocals.Add(cacheLocal);
if (_addedStatements == null) _addedStatements = ArrayBuilder<BoundStatement>.GetInstance();
cache = F.Local(cacheLocal);
_addedStatements.Add(F.Assignment(cache, F.Null(type)));
result = F.Coalesce(cache, F.AssignmentExpression(cache, result));
}
}
catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex)
{
Diagnostics.Add(ex.Diagnostic);
return new BoundBadExpression(F.Syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<BoundExpression>(node), node.Type);
}
}
return result;
}
// This helper checks syntactically whether there is a loop or lambda expression
// between given lambda syntax and the syntax that corresponds to its closure.
// we use this heuristic as a hint that the lambda delegate may be created
// multiple times with same closure.
// In such cases it makes sense to cache the delegate.
//
// Examples:
// int x = 123;
// for (int i = 1; i< 10; i++)
// {
// if (i< 2)
// {
// arr[i].Execute(arg => arg + x); // delegate should be cached
// }
// }
// for (int i = 1; i< 10; i++)
// {
// var val = i;
// if (i< 2)
// {
// int y = i + i;
// System.Console.WriteLine(y);
// arr[i].Execute(arg => arg + val); // delegate should NOT be cached (closure created inside the loop)
// }
// }
//
private static bool InLoopOrLambda(SyntaxNode lambdaSyntax, SyntaxNode scopeSyntax)
{
var curSyntax = lambdaSyntax.Parent;
while (curSyntax != null && curSyntax != scopeSyntax)
{
switch (curSyntax.Kind())
{
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
return true;
}
curSyntax = curSyntax.Parent;
}
return false;
}
public override BoundNode VisitLambda(BoundLambda node)
{
// these nodes have been handled in the context of the enclosing anonymous method conversion.
throw ExceptionUtilities.Unreachable;
}
#endregion
#if CHECK_LOCALS
/// <summary>
/// Ensure that local variables are always in scope where used in bound trees
/// </summary>
/// <param name="node"></param>
static partial void CheckLocalsDefined(BoundNode node)
{
LocalsDefinedScanner.INSTANCE.Visit(node);
}
class LocalsDefinedScanner : BoundTreeWalker
{
internal static LocalsDefinedScanner INSTANCE = new LocalsDefinedScanner();
HashSet<Symbol> localsDefined = new HashSet<Symbol>();
public override BoundNode VisitLocal(BoundLocal node)
{
Debug.Assert(node.LocalSymbol.IsConst || localsDefined.Contains(node.LocalSymbol));
return base.VisitLocal(node);
}
public override BoundNode VisitSequence(BoundSequence node)
{
try
{
if (!node.Locals.IsNullOrEmpty)
foreach (var l in node.Locals)
localsDefined.Add(l);
return base.VisitSequence(node);
}
finally
{
if (!node.Locals.IsNullOrEmpty)
foreach (var l in node.Locals)
localsDefined.Remove(l);
}
}
public override BoundNode VisitCatchBlock(BoundCatchBlock node)
{
try
{
if ((object)node.LocalOpt != null) localsDefined.Add(node.LocalOpt);
return base.VisitCatchBlock(node);
}
finally
{
if ((object)node.LocalOpt != null) localsDefined.Remove(node.LocalOpt);
}
}
public override BoundNode VisitSwitchStatement(BoundSwitchStatement node)
{
try
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Add(l);
return base.VisitSwitchStatement(node);
}
finally
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Remove(l);
}
}
public override BoundNode VisitBlock(BoundBlock node)
{
try
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Add(l);
return base.VisitBlock(node);
}
finally
{
if (!node.LocalsOpt.IsNullOrEmpty)
foreach (var l in node.LocalsOpt)
localsDefined.Remove(l);
}
}
}
#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/Lowering/ClosureConversion/SynthesizedClosureMethod.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using System.Diagnostics;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A method that results from the translation of a single lambda expression.
/// </summary>
internal sealed class SynthesizedClosureMethod : SynthesizedMethodBaseSymbol, ISynthesizedMethodBodyImplementationSymbol
{
private readonly ImmutableArray<NamedTypeSymbol> _structEnvironments;
internal MethodSymbol TopLevelMethod { get; }
internal readonly DebugId LambdaId;
internal SynthesizedClosureMethod(
NamedTypeSymbol containingType,
ImmutableArray<SynthesizedClosureEnvironment> structEnvironments,
ClosureKind closureKind,
MethodSymbol topLevelMethod,
DebugId topLevelMethodId,
MethodSymbol originalMethod,
SyntaxReference blockSyntax,
DebugId lambdaId)
: base(containingType,
originalMethod,
blockSyntax,
originalMethod.DeclaringSyntaxReferences[0].GetLocation(),
originalMethod is LocalFunctionSymbol
? MakeName(topLevelMethod.Name, originalMethod.Name, topLevelMethodId, closureKind, lambdaId)
: MakeName(topLevelMethod.Name, topLevelMethodId, closureKind, lambdaId),
MakeDeclarationModifiers(closureKind, originalMethod))
{
TopLevelMethod = topLevelMethod;
ClosureKind = closureKind;
LambdaId = lambdaId;
TypeMap typeMap;
ImmutableArray<TypeParameterSymbol> typeParameters;
var lambdaFrame = ContainingType as SynthesizedClosureEnvironment;
switch (closureKind)
{
case ClosureKind.Singleton: // all type parameters on method (except the top level method's)
case ClosureKind.General: // only lambda's type parameters on method (rest on class)
RoslynDebug.Assert(!(lambdaFrame is null));
typeMap = lambdaFrame.TypeMap.WithConcatAlphaRename(
originalMethod,
this,
out typeParameters,
out _,
lambdaFrame.OriginalContainingMethodOpt);
break;
case ClosureKind.ThisOnly: // all type parameters on method
case ClosureKind.Static:
RoslynDebug.Assert(lambdaFrame is null);
typeMap = TypeMap.Empty.WithConcatAlphaRename(
originalMethod,
this,
out typeParameters,
out _,
stopAt: null);
break;
default:
throw ExceptionUtilities.UnexpectedValue(closureKind);
}
if (!structEnvironments.IsDefaultOrEmpty && typeParameters.Length != 0)
{
var constructedStructClosures = ArrayBuilder<NamedTypeSymbol>.GetInstance();
foreach (var env in structEnvironments)
{
NamedTypeSymbol constructed;
if (env.Arity == 0)
{
constructed = env;
}
else
{
var originals = env.ConstructedFromTypeParameters;
var newArgs = typeMap.SubstituteTypeParameters(originals);
constructed = env.Construct(newArgs);
}
constructedStructClosures.Add(constructed);
}
_structEnvironments = constructedStructClosures.ToImmutableAndFree();
}
else
{
_structEnvironments = ImmutableArray<NamedTypeSymbol>.CastUp(structEnvironments);
}
AssignTypeMapAndTypeParameters(typeMap, typeParameters);
// static local functions should be emitted as static.
Debug.Assert(!(originalMethod is LocalFunctionSymbol) || !originalMethod.IsStatic || IsStatic);
}
private static DeclarationModifiers MakeDeclarationModifiers(ClosureKind closureKind, MethodSymbol originalMethod)
{
var mods = closureKind == ClosureKind.ThisOnly ? DeclarationModifiers.Private : DeclarationModifiers.Internal;
if (closureKind == ClosureKind.Static)
{
mods |= DeclarationModifiers.Static;
}
if (originalMethod.IsAsync)
{
mods |= DeclarationModifiers.Async;
}
if (originalMethod.IsExtern)
{
mods |= DeclarationModifiers.Extern;
}
return mods;
}
private static string MakeName(string topLevelMethodName, string localFunctionName, DebugId topLevelMethodId, ClosureKind closureKind, DebugId lambdaId)
{
return GeneratedNames.MakeLocalFunctionName(
topLevelMethodName,
localFunctionName,
(closureKind == ClosureKind.General) ? -1 : topLevelMethodId.Ordinal,
topLevelMethodId.Generation,
lambdaId.Ordinal,
lambdaId.Generation);
}
private static string MakeName(string topLevelMethodName, DebugId topLevelMethodId, ClosureKind closureKind, DebugId lambdaId)
{
// Lambda method name must contain the declaring method ordinal to be unique unless the method is emitted into a closure class exclusive to the declaring method.
// Lambdas that only close over "this" are emitted directly into the top-level method containing type.
// Lambdas that don't close over anything (static) are emitted into a shared closure singleton.
return GeneratedNames.MakeLambdaMethodName(
topLevelMethodName,
(closureKind == ClosureKind.General) ? -1 : topLevelMethodId.Ordinal,
topLevelMethodId.Generation,
lambdaId.Ordinal,
lambdaId.Generation);
}
// The lambda symbol might have declared no parameters in the case
//
// D d = delegate {};
//
// but there still might be parameters that need to be generated for the
// synthetic method. If there are no lambda parameters, try the delegate
// parameters instead.
//
// UNDONE: In the native compiler in this scenario we make up new names for
// UNDONE: synthetic parameters; in this implementation we use the parameter
// UNDONE: names from the delegate. Does it really matter?
protected override ImmutableArray<ParameterSymbol> BaseMethodParameters => this.BaseMethod.Parameters;
protected override ImmutableArray<TypeSymbol> ExtraSynthesizedRefParameters
=> ImmutableArray<TypeSymbol>.CastUp(_structEnvironments);
internal int ExtraSynthesizedParameterCount => this._structEnvironments.IsDefault ? 0 : this._structEnvironments.Length;
internal override bool InheritsBaseMethodAttributes => true;
internal override bool GenerateDebugInfo => !this.IsAsync;
internal override bool IsExpressionBodied => false;
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
// Syntax offset of a syntax node contained in a lambda body is calculated by the containing top-level method.
// The offset is thus relative to the top-level method body start.
return TopLevelMethod.CalculateLocalSyntaxOffset(localPosition, localTree);
}
IMethodSymbolInternal? ISynthesizedMethodBodyImplementationSymbol.Method => TopLevelMethod;
// The lambda method body needs to be updated when the containing top-level method body is updated.
bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => true;
public ClosureKind ClosureKind { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.PooledObjects;
using System.Diagnostics;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A method that results from the translation of a single lambda expression.
/// </summary>
internal sealed class SynthesizedClosureMethod : SynthesizedMethodBaseSymbol, ISynthesizedMethodBodyImplementationSymbol
{
private readonly ImmutableArray<NamedTypeSymbol> _structEnvironments;
internal MethodSymbol TopLevelMethod { get; }
internal readonly DebugId LambdaId;
internal SynthesizedClosureMethod(
NamedTypeSymbol containingType,
ImmutableArray<SynthesizedClosureEnvironment> structEnvironments,
ClosureKind closureKind,
MethodSymbol topLevelMethod,
DebugId topLevelMethodId,
MethodSymbol originalMethod,
SyntaxReference blockSyntax,
DebugId lambdaId,
TypeCompilationState compilationState)
: base(containingType,
originalMethod,
blockSyntax,
originalMethod.DeclaringSyntaxReferences[0].GetLocation(),
originalMethod is LocalFunctionSymbol
? MakeName(topLevelMethod.Name, originalMethod.Name, topLevelMethodId, closureKind, lambdaId)
: MakeName(topLevelMethod.Name, topLevelMethodId, closureKind, lambdaId),
MakeDeclarationModifiers(closureKind, originalMethod))
{
TopLevelMethod = topLevelMethod;
ClosureKind = closureKind;
LambdaId = lambdaId;
TypeMap typeMap;
ImmutableArray<TypeParameterSymbol> typeParameters;
var lambdaFrame = ContainingType as SynthesizedClosureEnvironment;
switch (closureKind)
{
case ClosureKind.Singleton: // all type parameters on method (except the top level method's)
case ClosureKind.General: // only lambda's type parameters on method (rest on class)
RoslynDebug.Assert(!(lambdaFrame is null));
typeMap = lambdaFrame.TypeMap.WithConcatAlphaRename(
originalMethod,
this,
out typeParameters,
out _,
lambdaFrame.OriginalContainingMethodOpt);
break;
case ClosureKind.ThisOnly: // all type parameters on method
case ClosureKind.Static:
RoslynDebug.Assert(lambdaFrame is null);
typeMap = TypeMap.Empty.WithConcatAlphaRename(
originalMethod,
this,
out typeParameters,
out _,
stopAt: null);
break;
default:
throw ExceptionUtilities.UnexpectedValue(closureKind);
}
if (!structEnvironments.IsDefaultOrEmpty && typeParameters.Length != 0)
{
var constructedStructClosures = ArrayBuilder<NamedTypeSymbol>.GetInstance();
foreach (var env in structEnvironments)
{
NamedTypeSymbol constructed;
if (env.Arity == 0)
{
constructed = env;
}
else
{
var originals = env.ConstructedFromTypeParameters;
var newArgs = typeMap.SubstituteTypeParameters(originals);
constructed = env.Construct(newArgs);
}
constructedStructClosures.Add(constructed);
}
_structEnvironments = constructedStructClosures.ToImmutableAndFree();
}
else
{
_structEnvironments = ImmutableArray<NamedTypeSymbol>.CastUp(structEnvironments);
}
AssignTypeMapAndTypeParameters(typeMap, typeParameters);
EnsureAttributesExist(compilationState);
// static local functions should be emitted as static.
Debug.Assert(!(originalMethod is LocalFunctionSymbol) || !originalMethod.IsStatic || IsStatic);
}
private void EnsureAttributesExist(TypeCompilationState compilationState)
{
var moduleBuilder = compilationState.ModuleBuilderOpt;
if (moduleBuilder is null)
{
return;
}
if (RefKind == RefKind.RefReadOnly)
{
moduleBuilder.EnsureIsReadOnlyAttributeExists();
}
ParameterHelpers.EnsureIsReadOnlyAttributeExists(moduleBuilder, Parameters);
if (ReturnType.ContainsNativeInteger())
{
moduleBuilder.EnsureNativeIntegerAttributeExists();
}
ParameterHelpers.EnsureNativeIntegerAttributeExists(moduleBuilder, Parameters);
if (compilationState.Compilation.ShouldEmitNullableAttributes(this))
{
if (ShouldEmitNullableContextValue(out _))
{
moduleBuilder.EnsureNullableContextAttributeExists();
}
if (ReturnTypeWithAnnotations.NeedsNullableAttribute())
{
moduleBuilder.EnsureNullableAttributeExists();
}
}
ParameterHelpers.EnsureNullableAttributeExists(moduleBuilder, this, Parameters);
}
private static DeclarationModifiers MakeDeclarationModifiers(ClosureKind closureKind, MethodSymbol originalMethod)
{
var mods = closureKind == ClosureKind.ThisOnly ? DeclarationModifiers.Private : DeclarationModifiers.Internal;
if (closureKind == ClosureKind.Static)
{
mods |= DeclarationModifiers.Static;
}
if (originalMethod.IsAsync)
{
mods |= DeclarationModifiers.Async;
}
if (originalMethod.IsExtern)
{
mods |= DeclarationModifiers.Extern;
}
return mods;
}
private static string MakeName(string topLevelMethodName, string localFunctionName, DebugId topLevelMethodId, ClosureKind closureKind, DebugId lambdaId)
{
return GeneratedNames.MakeLocalFunctionName(
topLevelMethodName,
localFunctionName,
(closureKind == ClosureKind.General) ? -1 : topLevelMethodId.Ordinal,
topLevelMethodId.Generation,
lambdaId.Ordinal,
lambdaId.Generation);
}
private static string MakeName(string topLevelMethodName, DebugId topLevelMethodId, ClosureKind closureKind, DebugId lambdaId)
{
// Lambda method name must contain the declaring method ordinal to be unique unless the method is emitted into a closure class exclusive to the declaring method.
// Lambdas that only close over "this" are emitted directly into the top-level method containing type.
// Lambdas that don't close over anything (static) are emitted into a shared closure singleton.
return GeneratedNames.MakeLambdaMethodName(
topLevelMethodName,
(closureKind == ClosureKind.General) ? -1 : topLevelMethodId.Ordinal,
topLevelMethodId.Generation,
lambdaId.Ordinal,
lambdaId.Generation);
}
// The lambda symbol might have declared no parameters in the case
//
// D d = delegate {};
//
// but there still might be parameters that need to be generated for the
// synthetic method. If there are no lambda parameters, try the delegate
// parameters instead.
//
// UNDONE: In the native compiler in this scenario we make up new names for
// UNDONE: synthetic parameters; in this implementation we use the parameter
// UNDONE: names from the delegate. Does it really matter?
protected override ImmutableArray<ParameterSymbol> BaseMethodParameters => this.BaseMethod.Parameters;
protected override ImmutableArray<TypeSymbol> ExtraSynthesizedRefParameters
=> ImmutableArray<TypeSymbol>.CastUp(_structEnvironments);
internal int ExtraSynthesizedParameterCount => this._structEnvironments.IsDefault ? 0 : this._structEnvironments.Length;
internal override bool InheritsBaseMethodAttributes => true;
internal override bool GenerateDebugInfo => !this.IsAsync;
internal override bool IsExpressionBodied => false;
internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree)
{
// Syntax offset of a syntax node contained in a lambda body is calculated by the containing top-level method.
// The offset is thus relative to the top-level method body start.
return TopLevelMethod.CalculateLocalSyntaxOffset(localPosition, localTree);
}
IMethodSymbolInternal? ISynthesizedMethodBodyImplementationSymbol.Method => TopLevelMethod;
// The lambda method body needs to be updated when the containing top-level method body is updated.
bool ISynthesizedMethodBodyImplementationSymbol.HasMethodBodyDependency => true;
public ClosureKind ClosureKind { get; }
}
}
| 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/Source/ParameterHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal static class ParameterHelpers
{
public static ImmutableArray<ParameterSymbol> MakeParameters(
Binder binder,
Symbol owner,
BaseParameterListSyntax syntax,
out SyntaxToken arglistToken,
BindingDiagnosticBag diagnostics,
bool allowRefOrOut,
bool allowThis,
bool addRefReadOnlyModifier)
{
return MakeParameters<ParameterSyntax, ParameterSymbol, Symbol>(
binder,
owner,
syntax.Parameters,
out arglistToken,
diagnostics,
allowRefOrOut,
allowThis,
addRefReadOnlyModifier,
suppressUseSiteDiagnostics: false,
lastIndex: syntax.Parameters.Count - 1,
parameterCreationFunc: (Binder context, Symbol owner, TypeWithAnnotations parameterType,
ParameterSyntax syntax, RefKind refKind, int ordinal,
SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier,
BindingDiagnosticBag declarationDiagnostics) =>
{
return SourceParameterSymbol.Create(
context,
owner,
parameterType,
syntax,
refKind,
syntax.Identifier,
ordinal,
isParams: paramsKeyword.Kind() != SyntaxKind.None,
isExtensionMethodThis: ordinal == 0 && thisKeyword.Kind() != SyntaxKind.None,
addRefReadOnlyModifier,
declarationDiagnostics);
});
}
public static ImmutableArray<FunctionPointerParameterSymbol> MakeFunctionPointerParameters(
Binder binder,
FunctionPointerMethodSymbol owner,
SeparatedSyntaxList<FunctionPointerParameterSyntax> parametersList,
BindingDiagnosticBag diagnostics,
bool suppressUseSiteDiagnostics)
{
return MakeParameters<FunctionPointerParameterSyntax, FunctionPointerParameterSymbol, FunctionPointerMethodSymbol>(
binder,
owner,
parametersList,
out _,
diagnostics,
allowRefOrOut: true,
allowThis: false,
addRefReadOnlyModifier: true,
suppressUseSiteDiagnostics,
parametersList.Count - 2,
parameterCreationFunc: (Binder binder, FunctionPointerMethodSymbol owner, TypeWithAnnotations parameterType,
FunctionPointerParameterSyntax syntax, RefKind refKind, int ordinal,
SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier,
BindingDiagnosticBag diagnostics) =>
{
// Non-function pointer locations have other locations to encode in/ref readonly/outness. For function pointers,
// these modreqs are the only locations where this can be encoded. If that changes, we should update this.
Debug.Assert(addRefReadOnlyModifier, "If addReadonlyRef isn't true, we must have found a different location to encode the readonlyness of a function pointer");
ImmutableArray<CustomModifier> customModifiers = refKind switch
{
RefKind.In => CreateInModifiers(binder, diagnostics, syntax),
RefKind.Out => CreateOutModifiers(binder, diagnostics, syntax),
_ => ImmutableArray<CustomModifier>.Empty
};
if (parameterType.IsVoidType())
{
diagnostics.Add(ErrorCode.ERR_NoVoidParameter, syntax.Type.Location);
}
return new FunctionPointerParameterSymbol(
parameterType,
refKind,
ordinal,
owner,
customModifiers);
},
parsingFunctionPointer: true);
}
private static ImmutableArray<TParameterSymbol> MakeParameters<TParameterSyntax, TParameterSymbol, TOwningSymbol>(
Binder binder,
TOwningSymbol owner,
SeparatedSyntaxList<TParameterSyntax> parametersList,
out SyntaxToken arglistToken,
BindingDiagnosticBag diagnostics,
bool allowRefOrOut,
bool allowThis,
bool addRefReadOnlyModifier,
bool suppressUseSiteDiagnostics,
int lastIndex,
Func<Binder, TOwningSymbol, TypeWithAnnotations, TParameterSyntax, RefKind, int, SyntaxToken, SyntaxToken, bool, BindingDiagnosticBag, TParameterSymbol> parameterCreationFunc,
bool parsingFunctionPointer = false)
where TParameterSyntax : BaseParameterSyntax
where TParameterSymbol : ParameterSymbol
where TOwningSymbol : Symbol
{
Debug.Assert(!parsingFunctionPointer || owner is FunctionPointerMethodSymbol);
arglistToken = default(SyntaxToken);
int parameterIndex = 0;
int firstDefault = -1;
var builder = ArrayBuilder<TParameterSymbol>.GetInstance();
var mustBeLastParameter = (ParameterSyntax)null;
foreach (var parameterSyntax in parametersList)
{
if (parameterIndex > lastIndex) break;
CheckParameterModifiers(parameterSyntax, diagnostics, parsingFunctionPointer);
var refKind = GetModifiers(parameterSyntax.Modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword);
if (thisKeyword.Kind() != SyntaxKind.None && !allowThis)
{
diagnostics.Add(ErrorCode.ERR_ThisInBadContext, thisKeyword.GetLocation());
}
if (parameterSyntax is ParameterSyntax concreteParam)
{
if (mustBeLastParameter == null &&
(concreteParam.Modifiers.Any(SyntaxKind.ParamsKeyword) ||
concreteParam.Identifier.Kind() == SyntaxKind.ArgListKeyword))
{
mustBeLastParameter = concreteParam;
}
if (concreteParam.IsArgList)
{
arglistToken = concreteParam.Identifier;
// The native compiler produces "Expected type" here, in the parser. Roslyn produces
// the somewhat more informative "arglist not valid" error.
if (paramsKeyword.Kind() != SyntaxKind.None
|| refnessKeyword.Kind() != SyntaxKind.None
|| thisKeyword.Kind() != SyntaxKind.None)
{
// CS1669: __arglist is not valid in this context
diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, arglistToken.GetLocation());
}
continue;
}
if (concreteParam.Default != null && firstDefault == -1)
{
firstDefault = parameterIndex;
}
}
Debug.Assert(parameterSyntax.Type != null);
var parameterType = binder.BindType(parameterSyntax.Type, diagnostics, suppressUseSiteDiagnostics: suppressUseSiteDiagnostics);
if (!allowRefOrOut && (refKind == RefKind.Ref || refKind == RefKind.Out))
{
Debug.Assert(refnessKeyword.Kind() != SyntaxKind.None);
// error CS0631: ref and out are not valid in this context
diagnostics.Add(ErrorCode.ERR_IllegalRefParam, refnessKeyword.GetLocation());
}
TParameterSymbol parameter = parameterCreationFunc(binder, owner, parameterType, parameterSyntax, refKind, parameterIndex, paramsKeyword, thisKeyword, addRefReadOnlyModifier, diagnostics);
ReportParameterErrors(owner, parameterSyntax, parameter, thisKeyword, paramsKeyword, firstDefault, diagnostics);
builder.Add(parameter);
++parameterIndex;
}
if (mustBeLastParameter != null && mustBeLastParameter != parametersList[lastIndex])
{
diagnostics.Add(
mustBeLastParameter.Identifier.Kind() == SyntaxKind.ArgListKeyword
? ErrorCode.ERR_VarargsLast
: ErrorCode.ERR_ParamsLast,
mustBeLastParameter.GetLocation());
}
ImmutableArray<TParameterSymbol> parameters = builder.ToImmutableAndFree();
if (!parsingFunctionPointer)
{
var methodOwner = owner as MethodSymbol;
var typeParameters = (object)methodOwner != null ?
methodOwner.TypeParameters :
default(ImmutableArray<TypeParameterSymbol>);
Debug.Assert(methodOwner?.MethodKind != MethodKind.LambdaMethod);
bool allowShadowingNames = binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNameShadowingInNestedFunctions) &&
methodOwner?.MethodKind == MethodKind.LocalFunction;
binder.ValidateParameterNameConflicts(typeParameters, parameters.Cast<TParameterSymbol, ParameterSymbol>(), allowShadowingNames, diagnostics);
}
return parameters;
}
internal static void EnsureIsReadOnlyAttributeExists(CSharpCompilation compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation)
{
// These parameters might not come from a compilation (example: lambdas evaluated in EE).
// During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead.
if (compilation == null)
{
return;
}
foreach (var parameter in parameters)
{
if (parameter.RefKind == RefKind.In)
{
compilation.EnsureIsReadOnlyAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation);
}
}
}
internal static void EnsureNativeIntegerAttributeExists(CSharpCompilation compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation)
{
// These parameters might not come from a compilation (example: lambdas evaluated in EE).
// During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead.
if (compilation == null)
{
return;
}
foreach (var parameter in parameters)
{
if (parameter.TypeWithAnnotations.ContainsNativeInteger())
{
compilation.EnsureNativeIntegerAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation);
}
}
}
internal static void EnsureNullableAttributeExists(CSharpCompilation compilation, Symbol container, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation)
{
// These parameters might not come from a compilation (example: lambdas evaluated in EE).
// During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead.
if (compilation == null)
{
return;
}
if (parameters.Length > 0 && compilation.ShouldEmitNullableAttributes(container))
{
foreach (var parameter in parameters)
{
if (parameter.TypeWithAnnotations.NeedsNullableAttribute())
{
compilation.EnsureNullableAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation);
}
}
}
}
private static Location GetParameterLocation(ParameterSymbol parameter) => parameter.GetNonNullSyntaxNode().Location;
private static void CheckParameterModifiers(BaseParameterSyntax parameter, BindingDiagnosticBag diagnostics, bool parsingFunctionPointerParams)
{
var seenThis = false;
var seenRef = false;
var seenOut = false;
var seenParams = false;
var seenIn = false;
foreach (var modifier in parameter.Modifiers)
{
switch (modifier.Kind())
{
case SyntaxKind.ThisKeyword:
if (seenThis)
{
diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword));
}
else if (seenOut)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else if (seenParams)
{
diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation());
}
else
{
seenThis = true;
}
break;
case SyntaxKind.RefKeyword:
if (seenRef)
{
diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
}
else if (seenParams)
{
diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
}
else if (seenOut)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else if (seenIn)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword));
}
else
{
seenRef = true;
}
break;
case SyntaxKind.OutKeyword:
if (seenOut)
{
diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else if (seenThis)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.ThisKeyword));
}
else if (seenParams)
{
diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else if (seenRef)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
}
else if (seenIn)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword));
}
else
{
seenOut = true;
}
break;
case SyntaxKind.ParamsKeyword when !parsingFunctionPointerParams:
if (seenParams)
{
diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword));
}
else if (seenThis)
{
diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation());
}
else if (seenRef)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
}
else if (seenIn)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword));
}
else if (seenOut)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else
{
seenParams = true;
}
break;
case SyntaxKind.InKeyword:
if (seenIn)
{
diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword));
}
else if (seenOut)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else if (seenRef)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
}
else if (seenParams)
{
diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword));
}
else
{
seenIn = true;
}
break;
case SyntaxKind.ParamsKeyword when parsingFunctionPointerParams:
case SyntaxKind.ReadOnlyKeyword when parsingFunctionPointerParams:
diagnostics.Add(ErrorCode.ERR_BadFuncPointerParamModifier, modifier.GetLocation(), SyntaxFacts.GetText(modifier.Kind()));
break;
default:
throw ExceptionUtilities.UnexpectedValue(modifier.Kind());
}
}
}
private static void ReportParameterErrors(
Symbol owner,
BaseParameterSyntax parameterSyntax,
ParameterSymbol parameter,
SyntaxToken thisKeyword,
SyntaxToken paramsKeyword,
int firstDefault,
BindingDiagnosticBag diagnostics)
{
int parameterIndex = parameter.Ordinal;
bool isDefault = parameterSyntax is ParameterSyntax { Default: { } };
if (thisKeyword.Kind() == SyntaxKind.ThisKeyword && parameterIndex != 0)
{
// Report CS1100 on "this". Note that is a change from Dev10
// which reports the error on the type following "this".
// error CS1100: Method '{0}' has a parameter modifier 'this' which is not on the first parameter
diagnostics.Add(ErrorCode.ERR_BadThisParam, thisKeyword.GetLocation(), owner.Name);
}
else if (parameter.IsParams && owner.IsOperator())
{
// error CS1670: params is not valid in this context
diagnostics.Add(ErrorCode.ERR_IllegalParams, paramsKeyword.GetLocation());
}
else if (parameter.IsParams && !parameter.TypeWithAnnotations.IsSZArray())
{
// error CS0225: The params parameter must be a single dimensional array
diagnostics.Add(ErrorCode.ERR_ParamsMustBeArray, paramsKeyword.GetLocation());
}
else if (parameter.TypeWithAnnotations.IsStatic)
{
Debug.Assert(parameter.ContainingSymbol is FunctionPointerMethodSymbol or { ContainingType: not null });
// error CS0721: '{0}': static types cannot be used as parameters
diagnostics.Add(
ErrorFacts.GetStaticClassParameterCode(parameter.ContainingSymbol.ContainingType?.IsInterfaceType() ?? false),
owner.Locations.IsEmpty ? parameterSyntax.GetLocation() : owner.Locations[0],
parameter.Type);
}
else if (firstDefault != -1 && parameterIndex > firstDefault && !isDefault && !parameter.IsParams)
{
// error CS1737: Optional parameters must appear after all required parameters
Location loc = ((ParameterSyntax)(BaseParameterSyntax)parameterSyntax).Identifier.GetNextToken(includeZeroWidth: true).GetLocation(); //could be missing
diagnostics.Add(ErrorCode.ERR_DefaultValueBeforeRequiredValue, loc);
}
else if (parameter.RefKind != RefKind.None &&
parameter.TypeWithAnnotations.IsRestrictedType(ignoreSpanLikeTypes: true))
{
// CS1601: Cannot make reference to variable of type 'System.TypedReference'
diagnostics.Add(ErrorCode.ERR_MethodArgCantBeRefAny, parameterSyntax.Location, parameter.Type);
}
}
internal static bool ReportDefaultParameterErrors(
Binder binder,
Symbol owner,
ParameterSyntax parameterSyntax,
SourceParameterSymbol parameter,
BoundExpression defaultExpression,
BoundExpression convertedExpression,
BindingDiagnosticBag diagnostics)
{
bool hasErrors = false;
// SPEC VIOLATION: The spec says that the conversion from the initializer to the
// parameter type is required to be either an identity or a nullable conversion, but
// that is not right:
//
// void M(short myShort = 10) {}
// * not an identity or nullable conversion but should be legal
//
// void M(object obj = (dynamic)null) {}
// * an identity conversion, but should be illegal
//
// void M(MyStruct? myStruct = default(MyStruct)) {}
// * a nullable conversion, but must be illegal because we cannot generate metadata for it
//
// Even if the expression is thoroughly illegal, we still want to bind it and
// stick it in the parameter because we want to be able to analyze it for
// IntelliSense purposes.
TypeSymbol parameterType = parameter.Type;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics);
Conversion conversion = binder.Conversions.ClassifyImplicitConversionFromExpression(defaultExpression, parameterType, ref useSiteInfo);
diagnostics.Add(defaultExpression.Syntax, useSiteInfo);
var refKind = GetModifiers(parameterSyntax.Modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword);
// CONSIDER: We are inconsistent here regarding where the error is reported; is it
// CONSIDER: reported on the parameter name, or on the value of the initializer?
// CONSIDER: Consider making this consistent.
if (refKind == RefKind.Ref || refKind == RefKind.Out)
{
// error CS1741: A ref or out parameter cannot have a default value
diagnostics.Add(ErrorCode.ERR_RefOutDefaultValue, refnessKeyword.GetLocation());
hasErrors = true;
}
else if (paramsKeyword.Kind() == SyntaxKind.ParamsKeyword)
{
// error CS1751: Cannot specify a default value for a parameter array
diagnostics.Add(ErrorCode.ERR_DefaultValueForParamsParameter, paramsKeyword.GetLocation());
hasErrors = true;
}
else if (thisKeyword.Kind() == SyntaxKind.ThisKeyword)
{
// Only need to report CS1743 for the first parameter. The caller will
// have reported CS1100 if 'this' appeared on another parameter.
if (parameter.Ordinal == 0)
{
// error CS1743: Cannot specify a default value for the 'this' parameter
diagnostics.Add(ErrorCode.ERR_DefaultValueForExtensionParameter, thisKeyword.GetLocation());
hasErrors = true;
}
}
else if (!defaultExpression.HasAnyErrors && !IsValidDefaultValue(defaultExpression.IsImplicitObjectCreation() ? convertedExpression : defaultExpression))
{
// error CS1736: Default parameter value for '{0}' must be a compile-time constant
diagnostics.Add(ErrorCode.ERR_DefaultValueMustBeConstant, parameterSyntax.Default.Value.Location, parameterSyntax.Identifier.ValueText);
hasErrors = true;
}
else if (!conversion.Exists ||
conversion.IsUserDefined ||
conversion.IsIdentity && parameterType.SpecialType == SpecialType.System_Object && defaultExpression.Type.IsDynamic())
{
// If we had no implicit conversion, or a user-defined conversion, report an error.
//
// Even though "object x = (dynamic)null" is a legal identity conversion, we do not allow it.
// CONSIDER: We could. Doesn't hurt anything.
// error CS1750: A value of type '{0}' cannot be used as a default parameter because there are no standard conversions to type '{1}'
diagnostics.Add(ErrorCode.ERR_NoConversionForDefaultParam, parameterSyntax.Identifier.GetLocation(),
defaultExpression.Display, parameterType);
hasErrors = true;
}
else if (conversion.IsReference &&
(parameterType.SpecialType == SpecialType.System_Object || parameterType.Kind == SymbolKind.DynamicType) &&
(object)defaultExpression.Type != null &&
defaultExpression.Type.SpecialType == SpecialType.System_String ||
conversion.IsBoxing)
{
// We don't allow object x = "hello", object x = 123, dynamic x = "hello", etc.
// error CS1763: '{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null
diagnostics.Add(ErrorCode.ERR_NotNullRefDefaultParameter, parameterSyntax.Identifier.GetLocation(),
parameterSyntax.Identifier.ValueText, parameterType);
hasErrors = true;
}
else if (conversion.IsNullable && !defaultExpression.Type.IsNullableType() &&
!(parameterType.GetNullableUnderlyingType().IsEnumType() || parameterType.GetNullableUnderlyingType().IsIntrinsicType()))
{
// We can do:
// M(int? x = default(int))
// M(int? x = default(int?))
// M(MyEnum? e = default(enum))
// M(MyEnum? e = default(enum?))
// M(MyStruct? s = default(MyStruct?))
//
// but we cannot do:
//
// M(MyStruct? s = default(MyStruct))
// error CS1770:
// A value of type '{0}' cannot be used as default parameter for nullable parameter '{1}' because '{0}' is not a simple type
diagnostics.Add(ErrorCode.ERR_NoConversionForNubDefaultParam, parameterSyntax.Identifier.GetLocation(),
defaultExpression.Type, parameterSyntax.Identifier.ValueText);
hasErrors = true;
}
ConstantValueUtils.CheckLangVersionForConstantValue(convertedExpression, diagnostics);
// Certain contexts allow default parameter values syntactically but they are ignored during
// semantic analysis. They are:
// 1. Explicitly implemented interface methods; since the method will always be called
// via the interface, the defaults declared on the implementation will not
// be seen at the call site.
//
// UNDONE: 2. The "actual" side of a partial method; the default values are taken from the
// UNDONE: "declaring" side of the method.
//
// UNDONE: 3. An indexer with only one formal parameter; it is illegal to omit every argument
// UNDONE: to an indexer.
//
// 4. A user-defined operator; it is syntactically impossible to omit the argument.
if (owner.IsExplicitInterfaceImplementation() ||
owner.IsPartialImplementation() ||
owner.IsOperator())
{
// CS1066: The default value specified for parameter '{0}' will have no effect because it applies to a
// member that is used in contexts that do not allow optional arguments
diagnostics.Add(ErrorCode.WRN_DefaultValueForUnconsumedLocation,
parameterSyntax.Identifier.GetLocation(),
parameterSyntax.Identifier.ValueText);
}
return hasErrors;
}
private static bool IsValidDefaultValue(BoundExpression expression)
{
// SPEC VIOLATION:
// By the spec an optional parameter initializer is required to be either:
// * a constant,
// * new S() where S is a value type
// * default(S) where S is a value type.
//
// The native compiler considers default(T) to be a valid
// initializer regardless of whether T is a value type
// reference type, type parameter type, and so on.
// We should consider simply allowing this in the spec.
//
// Also when valuetype S has a parameterless constructor,
// new S() is clearly not a constant expression and should produce an error
if (expression.ConstantValue != null)
{
return true;
}
while (true)
{
switch (expression.Kind)
{
case BoundKind.DefaultLiteral:
case BoundKind.DefaultExpression:
return true;
case BoundKind.ObjectCreationExpression:
return IsValidDefaultValue((BoundObjectCreationExpression)expression);
default:
return false;
}
}
}
private static bool IsValidDefaultValue(BoundObjectCreationExpression expression)
{
return expression.Constructor.IsDefaultValueTypeConstructor(requireZeroInit: true) && expression.InitializerExpressionOpt == null;
}
internal static MethodSymbol FindContainingGenericMethod(Symbol symbol)
{
for (Symbol current = symbol; (object)current != null; current = current.ContainingSymbol)
{
if (current.Kind == SymbolKind.Method)
{
MethodSymbol method = (MethodSymbol)current;
if (method.MethodKind != MethodKind.AnonymousFunction)
{
return method.IsGenericMethod ? method : null;
}
}
}
return null;
}
private static RefKind GetModifiers(SyntaxTokenList modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword)
{
var refKind = RefKind.None;
refnessKeyword = default(SyntaxToken);
paramsKeyword = default(SyntaxToken);
thisKeyword = default(SyntaxToken);
foreach (var modifier in modifiers)
{
switch (modifier.Kind())
{
case SyntaxKind.OutKeyword:
if (refKind == RefKind.None)
{
refnessKeyword = modifier;
refKind = RefKind.Out;
}
break;
case SyntaxKind.RefKeyword:
if (refKind == RefKind.None)
{
refnessKeyword = modifier;
refKind = RefKind.Ref;
}
break;
case SyntaxKind.InKeyword:
if (refKind == RefKind.None)
{
refnessKeyword = modifier;
refKind = RefKind.In;
}
break;
case SyntaxKind.ParamsKeyword:
paramsKeyword = modifier;
break;
case SyntaxKind.ThisKeyword:
thisKeyword = modifier;
break;
}
}
return refKind;
}
internal static ImmutableArray<CustomModifier> ConditionallyCreateInModifiers(RefKind refKind, bool addRefReadOnlyModifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
if (addRefReadOnlyModifier && refKind == RefKind.In)
{
return CreateInModifiers(binder, diagnostics, syntax);
}
else
{
return ImmutableArray<CustomModifier>.Empty;
}
}
internal static ImmutableArray<CustomModifier> CreateInModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
return CreateModifiers(WellKnownType.System_Runtime_InteropServices_InAttribute, binder, diagnostics, syntax);
}
internal static ImmutableArray<CustomModifier> CreateOutModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
return CreateModifiers(WellKnownType.System_Runtime_InteropServices_OutAttribute, binder, diagnostics, syntax);
}
private static ImmutableArray<CustomModifier> CreateModifiers(WellKnownType modifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
var modifierType = binder.GetWellKnownType(modifier, diagnostics, syntax);
return ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal static class ParameterHelpers
{
public static ImmutableArray<ParameterSymbol> MakeParameters(
Binder binder,
Symbol owner,
BaseParameterListSyntax syntax,
out SyntaxToken arglistToken,
BindingDiagnosticBag diagnostics,
bool allowRefOrOut,
bool allowThis,
bool addRefReadOnlyModifier)
{
return MakeParameters<ParameterSyntax, ParameterSymbol, Symbol>(
binder,
owner,
syntax.Parameters,
out arglistToken,
diagnostics,
allowRefOrOut,
allowThis,
addRefReadOnlyModifier,
suppressUseSiteDiagnostics: false,
lastIndex: syntax.Parameters.Count - 1,
parameterCreationFunc: (Binder context, Symbol owner, TypeWithAnnotations parameterType,
ParameterSyntax syntax, RefKind refKind, int ordinal,
SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier,
BindingDiagnosticBag declarationDiagnostics) =>
{
return SourceParameterSymbol.Create(
context,
owner,
parameterType,
syntax,
refKind,
syntax.Identifier,
ordinal,
isParams: paramsKeyword.Kind() != SyntaxKind.None,
isExtensionMethodThis: ordinal == 0 && thisKeyword.Kind() != SyntaxKind.None,
addRefReadOnlyModifier,
declarationDiagnostics);
});
}
public static ImmutableArray<FunctionPointerParameterSymbol> MakeFunctionPointerParameters(
Binder binder,
FunctionPointerMethodSymbol owner,
SeparatedSyntaxList<FunctionPointerParameterSyntax> parametersList,
BindingDiagnosticBag diagnostics,
bool suppressUseSiteDiagnostics)
{
return MakeParameters<FunctionPointerParameterSyntax, FunctionPointerParameterSymbol, FunctionPointerMethodSymbol>(
binder,
owner,
parametersList,
out _,
diagnostics,
allowRefOrOut: true,
allowThis: false,
addRefReadOnlyModifier: true,
suppressUseSiteDiagnostics,
parametersList.Count - 2,
parameterCreationFunc: (Binder binder, FunctionPointerMethodSymbol owner, TypeWithAnnotations parameterType,
FunctionPointerParameterSyntax syntax, RefKind refKind, int ordinal,
SyntaxToken paramsKeyword, SyntaxToken thisKeyword, bool addRefReadOnlyModifier,
BindingDiagnosticBag diagnostics) =>
{
// Non-function pointer locations have other locations to encode in/ref readonly/outness. For function pointers,
// these modreqs are the only locations where this can be encoded. If that changes, we should update this.
Debug.Assert(addRefReadOnlyModifier, "If addReadonlyRef isn't true, we must have found a different location to encode the readonlyness of a function pointer");
ImmutableArray<CustomModifier> customModifiers = refKind switch
{
RefKind.In => CreateInModifiers(binder, diagnostics, syntax),
RefKind.Out => CreateOutModifiers(binder, diagnostics, syntax),
_ => ImmutableArray<CustomModifier>.Empty
};
if (parameterType.IsVoidType())
{
diagnostics.Add(ErrorCode.ERR_NoVoidParameter, syntax.Type.Location);
}
return new FunctionPointerParameterSymbol(
parameterType,
refKind,
ordinal,
owner,
customModifiers);
},
parsingFunctionPointer: true);
}
private static ImmutableArray<TParameterSymbol> MakeParameters<TParameterSyntax, TParameterSymbol, TOwningSymbol>(
Binder binder,
TOwningSymbol owner,
SeparatedSyntaxList<TParameterSyntax> parametersList,
out SyntaxToken arglistToken,
BindingDiagnosticBag diagnostics,
bool allowRefOrOut,
bool allowThis,
bool addRefReadOnlyModifier,
bool suppressUseSiteDiagnostics,
int lastIndex,
Func<Binder, TOwningSymbol, TypeWithAnnotations, TParameterSyntax, RefKind, int, SyntaxToken, SyntaxToken, bool, BindingDiagnosticBag, TParameterSymbol> parameterCreationFunc,
bool parsingFunctionPointer = false)
where TParameterSyntax : BaseParameterSyntax
where TParameterSymbol : ParameterSymbol
where TOwningSymbol : Symbol
{
Debug.Assert(!parsingFunctionPointer || owner is FunctionPointerMethodSymbol);
arglistToken = default(SyntaxToken);
int parameterIndex = 0;
int firstDefault = -1;
var builder = ArrayBuilder<TParameterSymbol>.GetInstance();
var mustBeLastParameter = (ParameterSyntax)null;
foreach (var parameterSyntax in parametersList)
{
if (parameterIndex > lastIndex) break;
CheckParameterModifiers(parameterSyntax, diagnostics, parsingFunctionPointer);
var refKind = GetModifiers(parameterSyntax.Modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword);
if (thisKeyword.Kind() != SyntaxKind.None && !allowThis)
{
diagnostics.Add(ErrorCode.ERR_ThisInBadContext, thisKeyword.GetLocation());
}
if (parameterSyntax is ParameterSyntax concreteParam)
{
if (mustBeLastParameter == null &&
(concreteParam.Modifiers.Any(SyntaxKind.ParamsKeyword) ||
concreteParam.Identifier.Kind() == SyntaxKind.ArgListKeyword))
{
mustBeLastParameter = concreteParam;
}
if (concreteParam.IsArgList)
{
arglistToken = concreteParam.Identifier;
// The native compiler produces "Expected type" here, in the parser. Roslyn produces
// the somewhat more informative "arglist not valid" error.
if (paramsKeyword.Kind() != SyntaxKind.None
|| refnessKeyword.Kind() != SyntaxKind.None
|| thisKeyword.Kind() != SyntaxKind.None)
{
// CS1669: __arglist is not valid in this context
diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, arglistToken.GetLocation());
}
continue;
}
if (concreteParam.Default != null && firstDefault == -1)
{
firstDefault = parameterIndex;
}
}
Debug.Assert(parameterSyntax.Type != null);
var parameterType = binder.BindType(parameterSyntax.Type, diagnostics, suppressUseSiteDiagnostics: suppressUseSiteDiagnostics);
if (!allowRefOrOut && (refKind == RefKind.Ref || refKind == RefKind.Out))
{
Debug.Assert(refnessKeyword.Kind() != SyntaxKind.None);
// error CS0631: ref and out are not valid in this context
diagnostics.Add(ErrorCode.ERR_IllegalRefParam, refnessKeyword.GetLocation());
}
TParameterSymbol parameter = parameterCreationFunc(binder, owner, parameterType, parameterSyntax, refKind, parameterIndex, paramsKeyword, thisKeyword, addRefReadOnlyModifier, diagnostics);
ReportParameterErrors(owner, parameterSyntax, parameter, thisKeyword, paramsKeyword, firstDefault, diagnostics);
builder.Add(parameter);
++parameterIndex;
}
if (mustBeLastParameter != null && mustBeLastParameter != parametersList[lastIndex])
{
diagnostics.Add(
mustBeLastParameter.Identifier.Kind() == SyntaxKind.ArgListKeyword
? ErrorCode.ERR_VarargsLast
: ErrorCode.ERR_ParamsLast,
mustBeLastParameter.GetLocation());
}
ImmutableArray<TParameterSymbol> parameters = builder.ToImmutableAndFree();
if (!parsingFunctionPointer)
{
var methodOwner = owner as MethodSymbol;
var typeParameters = (object)methodOwner != null ?
methodOwner.TypeParameters :
default(ImmutableArray<TypeParameterSymbol>);
Debug.Assert(methodOwner?.MethodKind != MethodKind.LambdaMethod);
bool allowShadowingNames = binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNameShadowingInNestedFunctions) &&
methodOwner?.MethodKind == MethodKind.LocalFunction;
binder.ValidateParameterNameConflicts(typeParameters, parameters.Cast<TParameterSymbol, ParameterSymbol>(), allowShadowingNames, diagnostics);
}
return parameters;
}
#nullable enable
internal static void EnsureIsReadOnlyAttributeExists(PEModuleBuilder moduleBuilder, ImmutableArray<ParameterSymbol> parameters)
{
EnsureIsReadOnlyAttributeExists(moduleBuilder.Compilation, parameters, diagnostics: null, modifyCompilation: false, moduleBuilder);
}
internal static void EnsureIsReadOnlyAttributeExists(CSharpCompilation? compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation)
{
// These parameters might not come from a compilation (example: lambdas evaluated in EE).
// During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead.
if (compilation == null)
{
return;
}
EnsureIsReadOnlyAttributeExists(compilation, parameters, diagnostics, modifyCompilation, moduleBuilder: null);
}
private static void EnsureIsReadOnlyAttributeExists(CSharpCompilation compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation, PEModuleBuilder? moduleBuilder)
{
foreach (var parameter in parameters)
{
if (parameter.RefKind == RefKind.In)
{
if (moduleBuilder is { })
{
moduleBuilder.EnsureIsReadOnlyAttributeExists();
}
else
{
compilation.EnsureIsReadOnlyAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation);
}
}
}
}
internal static void EnsureNativeIntegerAttributeExists(PEModuleBuilder moduleBuilder, ImmutableArray<ParameterSymbol> parameters)
{
EnsureNativeIntegerAttributeExists(moduleBuilder.Compilation, parameters, diagnostics: null, modifyCompilation: false, moduleBuilder);
}
internal static void EnsureNativeIntegerAttributeExists(CSharpCompilation? compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag diagnostics, bool modifyCompilation)
{
// These parameters might not come from a compilation (example: lambdas evaluated in EE).
// During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead.
if (compilation == null)
{
return;
}
EnsureNativeIntegerAttributeExists(compilation, parameters, diagnostics, modifyCompilation, moduleBuilder: null);
}
private static void EnsureNativeIntegerAttributeExists(CSharpCompilation compilation, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation, PEModuleBuilder? moduleBuilder)
{
foreach (var parameter in parameters)
{
if (parameter.TypeWithAnnotations.ContainsNativeInteger())
{
if (moduleBuilder is { })
{
moduleBuilder.EnsureNativeIntegerAttributeExists();
}
else
{
compilation.EnsureNativeIntegerAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation);
}
}
}
}
internal static void EnsureNullableAttributeExists(PEModuleBuilder moduleBuilder, Symbol container, ImmutableArray<ParameterSymbol> parameters)
{
EnsureNullableAttributeExists(moduleBuilder.Compilation, container, parameters, diagnostics: null, modifyCompilation: false, moduleBuilder);
}
internal static void EnsureNullableAttributeExists(CSharpCompilation? compilation, Symbol container, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation)
{
// These parameters might not come from a compilation (example: lambdas evaluated in EE).
// During rewriting, lowering will take care of flagging the appropriate PEModuleBuilder instead.
if (compilation == null)
{
return;
}
EnsureNullableAttributeExists(compilation, container, parameters, diagnostics, modifyCompilation, moduleBuilder: null);
}
private static void EnsureNullableAttributeExists(CSharpCompilation compilation, Symbol container, ImmutableArray<ParameterSymbol> parameters, BindingDiagnosticBag? diagnostics, bool modifyCompilation, PEModuleBuilder? moduleBuilder)
{
if (parameters.Length > 0 && compilation.ShouldEmitNullableAttributes(container))
{
foreach (var parameter in parameters)
{
if (parameter.TypeWithAnnotations.NeedsNullableAttribute())
{
if (moduleBuilder is { })
{
moduleBuilder.EnsureNullableAttributeExists();
}
else
{
compilation.EnsureNullableAttributeExists(diagnostics, GetParameterLocation(parameter), modifyCompilation);
}
}
}
}
}
private static Location GetParameterLocation(ParameterSymbol parameter) => parameter.GetNonNullSyntaxNode().Location;
#nullable disable
private static void CheckParameterModifiers(BaseParameterSyntax parameter, BindingDiagnosticBag diagnostics, bool parsingFunctionPointerParams)
{
var seenThis = false;
var seenRef = false;
var seenOut = false;
var seenParams = false;
var seenIn = false;
foreach (var modifier in parameter.Modifiers)
{
switch (modifier.Kind())
{
case SyntaxKind.ThisKeyword:
if (seenThis)
{
diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword));
}
else if (seenOut)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ThisKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else if (seenParams)
{
diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation());
}
else
{
seenThis = true;
}
break;
case SyntaxKind.RefKeyword:
if (seenRef)
{
diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
}
else if (seenParams)
{
diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
}
else if (seenOut)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else if (seenIn)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.RefKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword));
}
else
{
seenRef = true;
}
break;
case SyntaxKind.OutKeyword:
if (seenOut)
{
diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else if (seenThis)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.ThisKeyword));
}
else if (seenParams)
{
diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else if (seenRef)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
}
else if (seenIn)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.OutKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword));
}
else
{
seenOut = true;
}
break;
case SyntaxKind.ParamsKeyword when !parsingFunctionPointerParams:
if (seenParams)
{
diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword));
}
else if (seenThis)
{
diagnostics.Add(ErrorCode.ERR_BadParamModThis, modifier.GetLocation());
}
else if (seenRef)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
}
else if (seenIn)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.InKeyword));
}
else if (seenOut)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.ParamsKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else
{
seenParams = true;
}
break;
case SyntaxKind.InKeyword:
if (seenIn)
{
diagnostics.Add(ErrorCode.ERR_DupParamMod, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword));
}
else if (seenOut)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.OutKeyword));
}
else if (seenRef)
{
diagnostics.Add(ErrorCode.ERR_BadParameterModifiers, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword), SyntaxFacts.GetText(SyntaxKind.RefKeyword));
}
else if (seenParams)
{
diagnostics.Add(ErrorCode.ERR_ParamsCantBeWithModifier, modifier.GetLocation(), SyntaxFacts.GetText(SyntaxKind.InKeyword));
}
else
{
seenIn = true;
}
break;
case SyntaxKind.ParamsKeyword when parsingFunctionPointerParams:
case SyntaxKind.ReadOnlyKeyword when parsingFunctionPointerParams:
diagnostics.Add(ErrorCode.ERR_BadFuncPointerParamModifier, modifier.GetLocation(), SyntaxFacts.GetText(modifier.Kind()));
break;
default:
throw ExceptionUtilities.UnexpectedValue(modifier.Kind());
}
}
}
private static void ReportParameterErrors(
Symbol owner,
BaseParameterSyntax parameterSyntax,
ParameterSymbol parameter,
SyntaxToken thisKeyword,
SyntaxToken paramsKeyword,
int firstDefault,
BindingDiagnosticBag diagnostics)
{
int parameterIndex = parameter.Ordinal;
bool isDefault = parameterSyntax is ParameterSyntax { Default: { } };
if (thisKeyword.Kind() == SyntaxKind.ThisKeyword && parameterIndex != 0)
{
// Report CS1100 on "this". Note that is a change from Dev10
// which reports the error on the type following "this".
// error CS1100: Method '{0}' has a parameter modifier 'this' which is not on the first parameter
diagnostics.Add(ErrorCode.ERR_BadThisParam, thisKeyword.GetLocation(), owner.Name);
}
else if (parameter.IsParams && owner.IsOperator())
{
// error CS1670: params is not valid in this context
diagnostics.Add(ErrorCode.ERR_IllegalParams, paramsKeyword.GetLocation());
}
else if (parameter.IsParams && !parameter.TypeWithAnnotations.IsSZArray())
{
// error CS0225: The params parameter must be a single dimensional array
diagnostics.Add(ErrorCode.ERR_ParamsMustBeArray, paramsKeyword.GetLocation());
}
else if (parameter.TypeWithAnnotations.IsStatic)
{
Debug.Assert(parameter.ContainingSymbol is FunctionPointerMethodSymbol or { ContainingType: not null });
// error CS0721: '{0}': static types cannot be used as parameters
diagnostics.Add(
ErrorFacts.GetStaticClassParameterCode(parameter.ContainingSymbol.ContainingType?.IsInterfaceType() ?? false),
owner.Locations.IsEmpty ? parameterSyntax.GetLocation() : owner.Locations[0],
parameter.Type);
}
else if (firstDefault != -1 && parameterIndex > firstDefault && !isDefault && !parameter.IsParams)
{
// error CS1737: Optional parameters must appear after all required parameters
Location loc = ((ParameterSyntax)(BaseParameterSyntax)parameterSyntax).Identifier.GetNextToken(includeZeroWidth: true).GetLocation(); //could be missing
diagnostics.Add(ErrorCode.ERR_DefaultValueBeforeRequiredValue, loc);
}
else if (parameter.RefKind != RefKind.None &&
parameter.TypeWithAnnotations.IsRestrictedType(ignoreSpanLikeTypes: true))
{
// CS1601: Cannot make reference to variable of type 'System.TypedReference'
diagnostics.Add(ErrorCode.ERR_MethodArgCantBeRefAny, parameterSyntax.Location, parameter.Type);
}
}
internal static bool ReportDefaultParameterErrors(
Binder binder,
Symbol owner,
ParameterSyntax parameterSyntax,
SourceParameterSymbol parameter,
BoundExpression defaultExpression,
BoundExpression convertedExpression,
BindingDiagnosticBag diagnostics)
{
bool hasErrors = false;
// SPEC VIOLATION: The spec says that the conversion from the initializer to the
// parameter type is required to be either an identity or a nullable conversion, but
// that is not right:
//
// void M(short myShort = 10) {}
// * not an identity or nullable conversion but should be legal
//
// void M(object obj = (dynamic)null) {}
// * an identity conversion, but should be illegal
//
// void M(MyStruct? myStruct = default(MyStruct)) {}
// * a nullable conversion, but must be illegal because we cannot generate metadata for it
//
// Even if the expression is thoroughly illegal, we still want to bind it and
// stick it in the parameter because we want to be able to analyze it for
// IntelliSense purposes.
TypeSymbol parameterType = parameter.Type;
CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = binder.GetNewCompoundUseSiteInfo(diagnostics);
Conversion conversion = binder.Conversions.ClassifyImplicitConversionFromExpression(defaultExpression, parameterType, ref useSiteInfo);
diagnostics.Add(defaultExpression.Syntax, useSiteInfo);
var refKind = GetModifiers(parameterSyntax.Modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword);
// CONSIDER: We are inconsistent here regarding where the error is reported; is it
// CONSIDER: reported on the parameter name, or on the value of the initializer?
// CONSIDER: Consider making this consistent.
if (refKind == RefKind.Ref || refKind == RefKind.Out)
{
// error CS1741: A ref or out parameter cannot have a default value
diagnostics.Add(ErrorCode.ERR_RefOutDefaultValue, refnessKeyword.GetLocation());
hasErrors = true;
}
else if (paramsKeyword.Kind() == SyntaxKind.ParamsKeyword)
{
// error CS1751: Cannot specify a default value for a parameter array
diagnostics.Add(ErrorCode.ERR_DefaultValueForParamsParameter, paramsKeyword.GetLocation());
hasErrors = true;
}
else if (thisKeyword.Kind() == SyntaxKind.ThisKeyword)
{
// Only need to report CS1743 for the first parameter. The caller will
// have reported CS1100 if 'this' appeared on another parameter.
if (parameter.Ordinal == 0)
{
// error CS1743: Cannot specify a default value for the 'this' parameter
diagnostics.Add(ErrorCode.ERR_DefaultValueForExtensionParameter, thisKeyword.GetLocation());
hasErrors = true;
}
}
else if (!defaultExpression.HasAnyErrors && !IsValidDefaultValue(defaultExpression.IsImplicitObjectCreation() ? convertedExpression : defaultExpression))
{
// error CS1736: Default parameter value for '{0}' must be a compile-time constant
diagnostics.Add(ErrorCode.ERR_DefaultValueMustBeConstant, parameterSyntax.Default.Value.Location, parameterSyntax.Identifier.ValueText);
hasErrors = true;
}
else if (!conversion.Exists ||
conversion.IsUserDefined ||
conversion.IsIdentity && parameterType.SpecialType == SpecialType.System_Object && defaultExpression.Type.IsDynamic())
{
// If we had no implicit conversion, or a user-defined conversion, report an error.
//
// Even though "object x = (dynamic)null" is a legal identity conversion, we do not allow it.
// CONSIDER: We could. Doesn't hurt anything.
// error CS1750: A value of type '{0}' cannot be used as a default parameter because there are no standard conversions to type '{1}'
diagnostics.Add(ErrorCode.ERR_NoConversionForDefaultParam, parameterSyntax.Identifier.GetLocation(),
defaultExpression.Display, parameterType);
hasErrors = true;
}
else if (conversion.IsReference &&
(parameterType.SpecialType == SpecialType.System_Object || parameterType.Kind == SymbolKind.DynamicType) &&
(object)defaultExpression.Type != null &&
defaultExpression.Type.SpecialType == SpecialType.System_String ||
conversion.IsBoxing)
{
// We don't allow object x = "hello", object x = 123, dynamic x = "hello", etc.
// error CS1763: '{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null
diagnostics.Add(ErrorCode.ERR_NotNullRefDefaultParameter, parameterSyntax.Identifier.GetLocation(),
parameterSyntax.Identifier.ValueText, parameterType);
hasErrors = true;
}
else if (conversion.IsNullable && !defaultExpression.Type.IsNullableType() &&
!(parameterType.GetNullableUnderlyingType().IsEnumType() || parameterType.GetNullableUnderlyingType().IsIntrinsicType()))
{
// We can do:
// M(int? x = default(int))
// M(int? x = default(int?))
// M(MyEnum? e = default(enum))
// M(MyEnum? e = default(enum?))
// M(MyStruct? s = default(MyStruct?))
//
// but we cannot do:
//
// M(MyStruct? s = default(MyStruct))
// error CS1770:
// A value of type '{0}' cannot be used as default parameter for nullable parameter '{1}' because '{0}' is not a simple type
diagnostics.Add(ErrorCode.ERR_NoConversionForNubDefaultParam, parameterSyntax.Identifier.GetLocation(),
defaultExpression.Type, parameterSyntax.Identifier.ValueText);
hasErrors = true;
}
ConstantValueUtils.CheckLangVersionForConstantValue(convertedExpression, diagnostics);
// Certain contexts allow default parameter values syntactically but they are ignored during
// semantic analysis. They are:
// 1. Explicitly implemented interface methods; since the method will always be called
// via the interface, the defaults declared on the implementation will not
// be seen at the call site.
//
// UNDONE: 2. The "actual" side of a partial method; the default values are taken from the
// UNDONE: "declaring" side of the method.
//
// UNDONE: 3. An indexer with only one formal parameter; it is illegal to omit every argument
// UNDONE: to an indexer.
//
// 4. A user-defined operator; it is syntactically impossible to omit the argument.
if (owner.IsExplicitInterfaceImplementation() ||
owner.IsPartialImplementation() ||
owner.IsOperator())
{
// CS1066: The default value specified for parameter '{0}' will have no effect because it applies to a
// member that is used in contexts that do not allow optional arguments
diagnostics.Add(ErrorCode.WRN_DefaultValueForUnconsumedLocation,
parameterSyntax.Identifier.GetLocation(),
parameterSyntax.Identifier.ValueText);
}
return hasErrors;
}
private static bool IsValidDefaultValue(BoundExpression expression)
{
// SPEC VIOLATION:
// By the spec an optional parameter initializer is required to be either:
// * a constant,
// * new S() where S is a value type
// * default(S) where S is a value type.
//
// The native compiler considers default(T) to be a valid
// initializer regardless of whether T is a value type
// reference type, type parameter type, and so on.
// We should consider simply allowing this in the spec.
//
// Also when valuetype S has a parameterless constructor,
// new S() is clearly not a constant expression and should produce an error
if (expression.ConstantValue != null)
{
return true;
}
while (true)
{
switch (expression.Kind)
{
case BoundKind.DefaultLiteral:
case BoundKind.DefaultExpression:
return true;
case BoundKind.ObjectCreationExpression:
return IsValidDefaultValue((BoundObjectCreationExpression)expression);
default:
return false;
}
}
}
private static bool IsValidDefaultValue(BoundObjectCreationExpression expression)
{
return expression.Constructor.IsDefaultValueTypeConstructor(requireZeroInit: true) && expression.InitializerExpressionOpt == null;
}
internal static MethodSymbol FindContainingGenericMethod(Symbol symbol)
{
for (Symbol current = symbol; (object)current != null; current = current.ContainingSymbol)
{
if (current.Kind == SymbolKind.Method)
{
MethodSymbol method = (MethodSymbol)current;
if (method.MethodKind != MethodKind.AnonymousFunction)
{
return method.IsGenericMethod ? method : null;
}
}
}
return null;
}
private static RefKind GetModifiers(SyntaxTokenList modifiers, out SyntaxToken refnessKeyword, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword)
{
var refKind = RefKind.None;
refnessKeyword = default(SyntaxToken);
paramsKeyword = default(SyntaxToken);
thisKeyword = default(SyntaxToken);
foreach (var modifier in modifiers)
{
switch (modifier.Kind())
{
case SyntaxKind.OutKeyword:
if (refKind == RefKind.None)
{
refnessKeyword = modifier;
refKind = RefKind.Out;
}
break;
case SyntaxKind.RefKeyword:
if (refKind == RefKind.None)
{
refnessKeyword = modifier;
refKind = RefKind.Ref;
}
break;
case SyntaxKind.InKeyword:
if (refKind == RefKind.None)
{
refnessKeyword = modifier;
refKind = RefKind.In;
}
break;
case SyntaxKind.ParamsKeyword:
paramsKeyword = modifier;
break;
case SyntaxKind.ThisKeyword:
thisKeyword = modifier;
break;
}
}
return refKind;
}
internal static ImmutableArray<CustomModifier> ConditionallyCreateInModifiers(RefKind refKind, bool addRefReadOnlyModifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
if (addRefReadOnlyModifier && refKind == RefKind.In)
{
return CreateInModifiers(binder, diagnostics, syntax);
}
else
{
return ImmutableArray<CustomModifier>.Empty;
}
}
internal static ImmutableArray<CustomModifier> CreateInModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
return CreateModifiers(WellKnownType.System_Runtime_InteropServices_InAttribute, binder, diagnostics, syntax);
}
internal static ImmutableArray<CustomModifier> CreateOutModifiers(Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
return CreateModifiers(WellKnownType.System_Runtime_InteropServices_OutAttribute, binder, diagnostics, syntax);
}
private static ImmutableArray<CustomModifier> CreateModifiers(WellKnownType modifier, Binder binder, BindingDiagnosticBag diagnostics, SyntaxNode syntax)
{
var modifierType = binder.GetWellKnownType(modifier, diagnostics, syntax);
return ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType));
}
}
}
| 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/Test/Emit/Attributes/AttributeTests_NativeInteger.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_NativeInteger : CSharpTestBase
{
private static readonly SymbolDisplayFormat FormatWithSpecialTypes = SymbolDisplayFormat.TestFormat.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
[Fact]
public void EmptyProject()
{
var source = @"";
var comp = CreateCompilation(source);
var expected =
@"";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void ExplicitAttribute_FromSource()
{
var source =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(new[] { NativeIntegerAttributeDefinition, source });
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger] System.UIntPtr[] F2
";
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute");
Assert.NotNull(attributeType);
AssertNativeIntegerAttributes(module, expected);
});
}
[Fact]
public void ExplicitAttribute_FromMetadata()
{
var comp = CreateCompilation(NativeIntegerAttributeDefinition);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
comp = CreateCompilation(source, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger] System.UIntPtr[] F2
";
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute");
Assert.Null(attributeType);
AssertNativeIntegerAttributes(module, expected);
});
}
[Fact]
public void ExplicitAttribute_MissingEmptyConstructor()
{
var source1 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NativeIntegerAttribute : Attribute
{
public NativeIntegerAttribute(bool[] flags) { }
}
}";
var source2 =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nint F1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F1").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(3, 17),
// (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nuint[] F2;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F2").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(4, 20));
}
[Fact]
public void ExplicitAttribute_MissingConstructor()
{
var source1 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NativeIntegerAttribute : Attribute
{
}
}";
var source2 =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nint F1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F1").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(3, 17),
// (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nuint[] F2;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F2").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(4, 20));
}
[Fact]
public void ExplicitAttribute_ReferencedInSource()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal class NativeIntegerAttribute : Attribute
{
internal NativeIntegerAttribute() { }
internal NativeIntegerAttribute(bool[] flags) { }
}
}";
var source =
@"#pragma warning disable 67
#pragma warning disable 169
using System;
using System.Runtime.CompilerServices;
[NativeInteger] class Program
{
[NativeInteger] IntPtr F;
[NativeInteger] event EventHandler E;
[NativeInteger] object P { get; }
[NativeInteger(new[] { false, true })] static UIntPtr[] M1() => throw null;
[return: NativeInteger(new[] { false, true })] static UIntPtr[] M2() => throw null;
static void M3([NativeInteger]object arg) { }
}";
var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular8);
verifyDiagnostics(comp);
comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular9);
verifyDiagnostics(comp);
static void verifyDiagnostics(CSharpCompilation comp)
{
comp.VerifyDiagnostics(
// (5,2): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] class Program
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 2),
// (7,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] IntPtr F;
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 6),
// (8,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] event EventHandler E;
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(8, 6),
// (9,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] object P { get; }
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(9, 6),
// (11,14): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [return: NativeInteger(new[] { false, true })] static UIntPtr[] M2() => throw null;
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger(new[] { false, true })").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(11, 14),
// (12,21): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// static void M3([NativeInteger]object arg) { }
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(12, 21));
}
}
[Fact]
public void MissingAttributeUsageAttribute()
{
var source =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
}
[Fact]
public void Metadata_ZeroElements()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0]
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0]
ret
}
.method public static void F1(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0]
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<System.IntPtr, System.UIntPtr>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F0(?, ?)' is not supported by the language
// B.F0(default, default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?, ?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(new A<System.IntPtr, System.UIntPtr>());
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(6, 11));
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F0(?, ?)' is not supported by the language
// B.F0(default, default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?, ?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(new A<System.IntPtr, System.UIntPtr>());
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(6, 11));
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0( x, y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1( a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(? x, ? y)
[NativeInteger({ })] ? x
[NativeInteger({ })] ? y
void F1(? a)
[NativeInteger({ })] ? a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_OneElementFalse()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F1(class A<int32, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F2(class A<native int, uint32> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<int, System.UIntPtr>());
B.F2(new A<System.IntPtr, uint>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0(System.IntPtr x, System.UIntPtr y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1(A<int, System.UIntPtr> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<System.IntPtr, uint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(System.IntPtr x, System.UIntPtr y)
[NativeInteger({ False })] System.IntPtr x
[NativeInteger({ False })] System.UIntPtr y
void F1(A<System.Int32, System.UIntPtr> a)
[NativeInteger({ False })] A<System.Int32, System.UIntPtr> a
void F2(A<System.IntPtr, System.UInt32> a)
[NativeInteger({ False })] A<System.IntPtr, System.UInt32> a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_OneElementTrue()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
ret
}
.method public static void F1(class A<int32, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
ret
}
.method public static void F2(class A<native int, uint32> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<int, nuint>());
B.F2(new A<nint, uint>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (6,25): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// B.F1(new A<int, nuint>());
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(6, 25),
// (7,20): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// B.F2(new A<nint, uint>());
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(7, 20));
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0(nint x, nuint y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1(A<int, nuint> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<nint, uint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(System.IntPtr x, System.UIntPtr y)
[NativeInteger({ True })] System.IntPtr x
[NativeInteger({ True })] System.UIntPtr y
void F1(A<System.Int32, System.UIntPtr> a)
[NativeInteger({ True })] A<System.Int32, System.UIntPtr> a
void F2(A<System.IntPtr, System.UInt32> a)
[NativeInteger({ True })] A<System.IntPtr, System.UInt32> a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_AllFalse()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F1(class A<int32, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F2(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 00 00 00 ) // new[] { false, false }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<int, System.UIntPtr>());
B.F2(new A<System.IntPtr, System.UIntPtr>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0(System.IntPtr x, System.UIntPtr y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1(A<int, System.UIntPtr> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<System.IntPtr, System.UIntPtr> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(System.IntPtr x, System.UIntPtr y)
[NativeInteger({ False })] System.IntPtr x
[NativeInteger({ False })] System.UIntPtr y
void F1(A<System.Int32, System.UIntPtr> a)
[NativeInteger({ False })] A<System.Int32, System.UIntPtr> a
void F2(A<System.IntPtr, System.UIntPtr> a)
[NativeInteger({ False, False })] A<System.IntPtr, System.UIntPtr> a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_TooFewAndTooManyTransformFlags()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
}
.class public B
{
.method public static void F(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor() = ( 01 00 00 00 ) // no array, too few
ret
}
.method public static void F0(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0], too few
ret
}
.method public static void F1(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }, too few
ret
}
.method public static void F2(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }, valid
ret
}
.method public static void F3(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 01 01 00 00 ) // new[] { false, true, true }, too many
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F(A<nint, nuint> a)
{
B.F(a);
B.F0(a);
B.F1(a);
B.F2(a);
B.F3(a);
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (3,21): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// static void F(A<nint, nuint> a)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(3, 21),
// (3,27): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// static void F(A<nint, nuint> a)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(3, 27),
// (5,11): error CS0570: 'B.F(?)' is not supported by the language
// B.F(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F").WithArguments("B.F(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F0(?)' is not supported by the language
// B.F0(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(7, 11),
// (9,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(9, 11));
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F(?)' is not supported by the language
// B.F(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F").WithArguments("B.F(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F0(?)' is not supported by the language
// B.F0(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(7, 11),
// (9,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(9, 11));
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F( a)", type.GetMember("F").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F0( a)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1( a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<System.IntPtr, nuint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F3( a)", type.GetMember("F3").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F(? a)
[NativeInteger] ? a
void F0(? a)
[NativeInteger({ })] ? a
void F1(? a)
[NativeInteger({ True })] ? a
void F2(A<System.IntPtr, System.UIntPtr> a)
[NativeInteger({ False, True })] A<System.IntPtr, System.UIntPtr> a
void F3(? a)
[NativeInteger({ False, True, True })] ? a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_UnexpectedTarget()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class A<T>
{
}
.class public B
{
.method public static void F1(int32 w)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor() = ( 01 00 00 00 )
ret
}
.method public static void F2(object[] x)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }
ret
}
.method public static void F3(class A<class B> y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }
ret
}
.method public static void F4(native int[] z)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 01 01 00 00 ) // new[] { true, true }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F1(default);
B.F2(default);
B.F3(default);
B.F4(default);
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F2(?)' is not supported by the language
// B.F2(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("B.F2(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(7, 11),
// (8,11): error CS0570: 'B.F4(?)' is not supported by the language
// B.F4(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F4").WithArguments("B.F4(?)").WithLocation(8, 11)
);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F2(?)' is not supported by the language
// B.F2(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("B.F2(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(7, 11),
// (8,11): error CS0570: 'B.F4(?)' is not supported by the language
// B.F4(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F4").WithArguments("B.F4(?)").WithLocation(8, 11)
);
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F1( w)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2( x)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F3( y)", type.GetMember("F3").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F4( z)", type.GetMember("F4").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"
B
void F1(? w)
[NativeInteger] ? w
void F2(? x)
[NativeInteger({ False, True })] ? x
void F3(? y)
[NativeInteger({ False, True })] ? y
void F4(? z)
[NativeInteger({ True, True })] ? z
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
[Fact]
public void EmitAttribute_BaseClass()
{
var source =
@"public class A<T, U>
{
}
public class B : A<nint, nuint[]>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"[NativeInteger({ True, True })] B
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Interface()
{
var source =
@"public interface I<T>
{
}
public class A : I<(nint, nuint[])>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "A");
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])");
});
}
[Fact]
public void EmitAttribute_AllTypes()
{
var source =
@"public enum E { }
public class C<T>
{
public delegate void D<T>();
public enum F { }
public struct S<U> { }
public interface I<U> { }
public C<T>.S<nint> F1;
public C<nuint>.I<T> F2;
public C<E>.D<nint> F3;
public C<nuint>.D<dynamic> F4;
public C<C<nuint>.D<System.IntPtr>>.F F5;
public C<C<System.UIntPtr>.F>.D<nint> F6;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"C<T>
[NativeInteger] C<T>.S<System.IntPtr> F1
[NativeInteger] C<System.UIntPtr>.I<T> F2
[NativeInteger] C<E>.D<System.IntPtr> F3
[NativeInteger] C<System.UIntPtr>.D<dynamic> F4
[NativeInteger({ True, False })] C<C<System.UIntPtr>.D<System.IntPtr>>.F F5
[NativeInteger({ False, True })] C<C<System.UIntPtr>.F>.D<System.IntPtr> F6
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ErrorType()
{
var source1 =
@"public class A { }
public class B<T> { }";
var comp = CreateCompilation(source1, assemblyName: "95d36b13-f2e1-495d-9ab6-62e8cc63ac22");
var ref1 = comp.EmitToImageReference();
var source2 =
@"public class C<T, U> { }
public class D
{
public B<nint> F1;
public C<nint, A> F2;
}";
comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
var ref2 = comp.EmitToImageReference();
var source3 =
@"class Program
{
static void Main()
{
var d = new D();
_ = d.F1;
_ = d.F2;
}
}";
comp = CreateCompilation(source3, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,15): error CS0012: The type 'B<>' is defined in an assembly that is not referenced. You must add a reference to assembly '95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// _ = d.F1;
Diagnostic(ErrorCode.ERR_NoTypeDef, "F1").WithArguments("B<>", "95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 15),
// (7,15): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly '95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// _ = d.F2;
Diagnostic(ErrorCode.ERR_NoTypeDef, "F2").WithArguments("A", "95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 15));
}
[Fact]
public void EmitAttribute_Fields()
{
var source =
@"public class Program
{
public nint F1;
public (System.IntPtr, nuint[]) F2;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) F2
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_MethodReturnType()
{
var source =
@"public class Program
{
public (System.IntPtr, nuint[]) F() => default;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) F()
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_MethodParameters()
{
var source =
@"public class Program
{
public void F(nint x, nuint y) { }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
void F(System.IntPtr x, System.UIntPtr y)
[NativeInteger] System.IntPtr x
[NativeInteger] System.UIntPtr y
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_PropertyType()
{
var source =
@"public class Program
{
public (System.IntPtr, nuint[]) P => default;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) P { get; }
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) P.get
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_PropertyParameters()
{
var source =
@"public class Program
{
public object this[nint x, (nuint[], System.IntPtr) y] => null;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
System.Object this[System.IntPtr x, (System.UIntPtr[], System.IntPtr) y] { get; }
[NativeInteger] System.IntPtr x
[NativeInteger({ True, False })] (System.UIntPtr[], System.IntPtr) y
System.Object this[System.IntPtr x, (System.UIntPtr[], System.IntPtr) y].get
[NativeInteger] System.IntPtr x
[NativeInteger({ True, False })] (System.UIntPtr[], System.IntPtr) y
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_EventType()
{
var source =
@"using System;
public class Program
{
public event EventHandler<nuint[]> E;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
[NativeInteger] event System.EventHandler<System.UIntPtr[]> E
void E.add
[NativeInteger] System.EventHandler<System.UIntPtr[]> value
void E.remove
[NativeInteger] System.EventHandler<System.UIntPtr[]> value
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_OperatorReturnType()
{
var source =
@"public class C
{
public static nint operator+(C a, C b) => 0;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"C
[NativeInteger] System.IntPtr operator +(C a, C b)
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_OperatorParameters()
{
var source =
@"public class C
{
public static C operator+(C a, nuint[] b) => a;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"C
C operator +(C a, System.UIntPtr[] b)
[NativeInteger] System.UIntPtr[] b
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_DelegateReturnType()
{
var source =
@"public delegate nint D();";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"D
[NativeInteger] System.IntPtr Invoke()
[NativeInteger] System.IntPtr EndInvoke(System.IAsyncResult result)
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_DelegateParameters()
{
var source =
@"public delegate void D(nint x, nuint[] y);";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"D
void Invoke(System.IntPtr x, System.UIntPtr[] y)
[NativeInteger] System.IntPtr x
[NativeInteger] System.UIntPtr[] y
System.IAsyncResult BeginInvoke(System.IntPtr x, System.UIntPtr[] y, System.AsyncCallback callback, System.Object @object)
[NativeInteger] System.IntPtr x
[NativeInteger] System.UIntPtr[] y
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Constraint()
{
var source =
@"public class A<T>
{
}
public class B<T> where T : A<nint>
{
}
public class C<T> where T : A<nuint[]>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var type = comp.GetMember<NamedTypeSymbol>("B");
Assert.Equal("A<nint>", getConstraintType(type).ToDisplayString(FormatWithSpecialTypes));
type = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal("A<nuint[]>", getConstraintType(type).ToDisplayString(FormatWithSpecialTypes));
static TypeWithAnnotations getConstraintType(NamedTypeSymbol type) => type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0];
}
[Fact]
public void EmitAttribute_LambdaReturnType()
{
var source =
@"using System;
class Program
{
static object M()
{
Func<nint> f = () => (nint)2;
return f();
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
AssertNoNativeIntegerAttributes(comp);
}
[Fact]
public void EmitAttribute_LambdaParameters()
{
var source =
@"using System;
class Program
{
static void M()
{
Action<nuint[]> a = (nuint[] n) => { };
a(null);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
AssertNoNativeIntegerAttributes(comp);
}
[Fact]
public void EmitAttribute_LocalFunctionReturnType()
{
var source =
@"class Program
{
static object M()
{
nint L() => (nint)2;
return L();
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular9,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<M>g__L|0_0");
AssertNativeIntegerAttribute(method.GetReturnTypeAttributes());
AssertAttributes(method.GetAttributes(), "System.Runtime.CompilerServices.CompilerGeneratedAttribute");
});
}
[Fact]
public void EmitAttribute_LocalFunctionParameters()
{
var source =
@"class Program
{
static void M()
{
void L(nuint[] n) { }
L(null);
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular9,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<M>g__L|0_0");
AssertNativeIntegerAttribute(method.Parameters[0].GetAttributes());
});
}
[Fact]
public void EmitAttribute_LocalFunctionConstraints()
{
var source =
@"interface I<T>
{
}
class Program
{
static void M()
{
void L<T>() where T : I<nint> { }
L<I<nint>>();
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NativeIntegerAttribute"));
});
}
[Fact]
public void EmitAttribute_Nested()
{
var source =
@"public class A<T>
{
public class B<U> { }
}
unsafe public class Program
{
public nint F1;
public nuint[] F2;
public nint* F3;
public A<nint>.B<nuint> F4;
public (nint, nuint) F5;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger] System.UIntPtr[] F2
[NativeInteger] System.IntPtr* F3
[NativeInteger({ True, True })] A<System.IntPtr>.B<System.UIntPtr> F4
[NativeInteger({ True, True })] (System.IntPtr, System.UIntPtr) F5
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_LongTuples_01()
{
var source =
@"public class A<T>
{
}
unsafe public class B
{
public A<(object, (nint, nuint, nint[], nuint, nint, nuint*[], nint, System.UIntPtr))> F1;
public A<(nint, object, nuint[], object, nint, object, (System.IntPtr, nuint), object, nuint)> F2;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
var expected =
@"B
[NativeInteger({ True, True, True, True, True, True, True, False })] A<(System.Object, (System.IntPtr, System.UIntPtr, System.IntPtr[], System.UIntPtr, System.IntPtr, System.UIntPtr*[], System.IntPtr, System.UIntPtr))> F1
[NativeInteger({ True, True, True, False, True, True })] A<(System.IntPtr, System.Object, System.UIntPtr[], System.Object, System.IntPtr, System.Object, (System.IntPtr, System.UIntPtr), System.Object, System.UIntPtr)> F2
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_LongTuples_02()
{
var source1 =
@"public interface IA { }
public interface IB<T> { }
public class C : IA, IB<(nint, object, nuint[], object, nint, object, (System.IntPtr, nuint), object, nuint)>
{
}";
var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C");
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().ElementAt(1));
var customAttributes = interfaceImpl.GetCustomAttributes();
AssertAttributes(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])");
var customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])");
AssertEx.Equal(ImmutableArray.Create(true, true, true, false, true, true), reader.ReadBoolArray(customAttribute.Value));
});
var ref1 = comp.EmitToImageReference();
var source2 =
@"class Program
{
static void Main()
{
IA a = new C();
_ = a;
}
}";
comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(45519, "https://github.com/dotnet/roslyn/issues/45519")]
public void EmitAttribute_PartialMethods()
{
var source =
@"public partial class Program
{
static partial void F1(System.IntPtr x);
static partial void F2(System.UIntPtr x) { }
static partial void F1(nint x) { }
static partial void F2(nuint x);
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9);
var expected =
@"Program
void F2(System.UIntPtr x)
[NativeInteger] System.UIntPtr x
";
AssertNativeIntegerAttributes(comp, expected);
comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(6), parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (4,25): warning CS8826: Partial method declarations 'void Program.F2(nuint x)' and 'void Program.F2(UIntPtr x)' have signature differences.
// static partial void F2(System.UIntPtr x) { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F2").WithArguments("void Program.F2(nuint x)", "void Program.F2(UIntPtr x)").WithLocation(4, 25),
// (5,25): warning CS8826: Partial method declarations 'void Program.F1(IntPtr x)' and 'void Program.F1(nint x)' have signature differences.
// static partial void F1(nint x) { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F1").WithArguments("void Program.F1(IntPtr x)", "void Program.F1(nint x)").WithLocation(5, 25));
}
// Shouldn't depend on [NullablePublicOnly].
[Fact]
public void NoPublicMembers()
{
var source =
@"class A<T, U>
{
}
class B : A<System.UIntPtr, nint>
{
}";
var comp = CreateCompilation(
source,
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9.WithNullablePublicOnly());
var expected =
@"[NativeInteger({ False, True })] B
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void AttributeUsage()
{
var source =
@"public class Program
{
public nint F;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute");
AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo();
Assert.False(attributeUsage.Inherited);
Assert.False(attributeUsage.AllowMultiple);
Assert.True(attributeUsage.HasValidAttributeTargets);
var expectedTargets =
AttributeTargets.Class |
AttributeTargets.Event |
AttributeTargets.Field |
AttributeTargets.GenericParameter |
AttributeTargets.Parameter |
AttributeTargets.Property |
AttributeTargets.ReturnValue;
Assert.Equal(expectedTargets, attributeUsage.ValidTargets);
});
}
[Fact]
public void AttributeFieldExists()
{
var source =
@"public class Program
{
public nint F;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Program");
var member = type.GetMembers("F").Single();
var attributes = member.GetAttributes();
AssertNativeIntegerAttribute(attributes);
var attribute = GetNativeIntegerAttribute(attributes);
var field = attribute.AttributeClass.GetField("TransformFlags");
Assert.Equal("System.Boolean[]", field.TypeWithAnnotations.ToTestDisplayString());
});
}
[Fact]
public void NestedNativeIntegerWithPrecedingType()
{
var comp = CompileAndVerify(@"
class C<T, U, V>
{
public C<dynamic, T, nint> F0;
public C<dynamic, nint, System.IntPtr> F1;
public C<dynamic, nuint, System.UIntPtr> F2;
public C<T, nint, System.IntPtr> F3;
public C<T, nuint, System.UIntPtr> F4;
}
", options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator);
static void symbolValidator(ModuleSymbol module)
{
var expectedAttributes = @"
C<T, U, V>
[NativeInteger] C<dynamic, T, System.IntPtr> F0
[NativeInteger({ True, False })] C<dynamic, System.IntPtr, System.IntPtr> F1
[NativeInteger({ True, False })] C<dynamic, System.UIntPtr, System.UIntPtr> F2
[NativeInteger({ True, False })] C<T, System.IntPtr, System.IntPtr> F3
[NativeInteger({ True, False })] C<T, System.UIntPtr, System.UIntPtr> F4
";
AssertNativeIntegerAttributes(module, expectedAttributes);
var c = module.GlobalNamespace.GetTypeMember("C");
assert("C<dynamic, T, nint>", "F0");
assert("C<dynamic, nint, System.IntPtr>", "F1");
assert("C<dynamic, nuint, System.UIntPtr>", "F2");
assert("C<T, nint, System.IntPtr>", "F3");
assert("C<T, nuint, System.UIntPtr>", "F4");
void assert(string expectedType, string fieldName)
{
Assert.Equal(expectedType, c.GetField(fieldName).Type.ToTestDisplayString());
}
}
}
[Fact]
public void FunctionPointersWithNativeIntegerTypes()
{
var comp = CompileAndVerify(@"
unsafe class C
{
public delegate*<nint, object, object> F0;
public delegate*<nint, nint, nint> F1;
public delegate*<System.IntPtr, System.IntPtr, nint> F2;
public delegate*<nint, System.IntPtr, System.IntPtr> F3;
public delegate*<System.IntPtr, nint, System.IntPtr> F4;
public delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, nint> F5;
public delegate*<nint, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F6;
public delegate*<delegate*<System.IntPtr, System.IntPtr, nint>, System.IntPtr> F7;
public delegate*<System.IntPtr, delegate*<System.IntPtr, nint, System.IntPtr>> F8;
}
", options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator);
static void symbolValidator(ModuleSymbol module)
{
var expectedAttributes = @"
C
[NativeInteger] delegate*<System.IntPtr, System.Object, System.Object> F0
[NativeInteger({ True, True, True })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F1
[NativeInteger({ True, False, False })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F2
[NativeInteger({ False, True, False })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F3
[NativeInteger({ False, False, True })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F4
[NativeInteger({ True, False, False, False })] delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, System.IntPtr> F5
[NativeInteger({ False, False, False, True })] delegate*<System.IntPtr, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F6
[NativeInteger({ False, True, False, False })] delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, System.IntPtr> F7
[NativeInteger({ False, False, True, False })] delegate*<System.IntPtr, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F8
";
AssertNativeIntegerAttributes(module, expectedAttributes);
var c = module.GlobalNamespace.GetTypeMember("C");
assert("delegate*<nint, System.Object, System.Object>", "F0");
assert("delegate*<nint, nint, nint>", "F1");
assert("delegate*<System.IntPtr, System.IntPtr, nint>", "F2");
assert("delegate*<nint, System.IntPtr, System.IntPtr>", "F3");
assert("delegate*<System.IntPtr, nint, System.IntPtr>", "F4");
assert("delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, nint>", "F5");
assert("delegate*<nint, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>>", "F6");
assert("delegate*<delegate*<System.IntPtr, System.IntPtr, nint>, System.IntPtr>", "F7");
assert("delegate*<System.IntPtr, delegate*<System.IntPtr, nint, System.IntPtr>>", "F8");
void assert(string expectedType, string fieldName)
{
var field = c.GetField(fieldName);
FunctionPointerUtilities.CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)field.Type);
Assert.Equal(expectedType, c.GetField(fieldName).Type.ToTestDisplayString());
}
}
}
private static TypeDefinition GetTypeDefinitionByName(MetadataReader reader, string name)
{
return reader.GetTypeDefinition(reader.TypeDefinitions.Single(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name)));
}
private static string GetAttributeConstructorName(MetadataReader reader, CustomAttributeHandle handle)
{
return reader.Dump(reader.GetCustomAttribute(handle).Constructor);
}
private static CustomAttribute GetAttributeByConstructorName(MetadataReader reader, CustomAttributeHandleCollection handles, string name)
{
return reader.GetCustomAttribute(handles.FirstOrDefault(h => GetAttributeConstructorName(reader, h) == name));
}
private static void AssertAttributes(MetadataReader reader, CustomAttributeHandleCollection handles, params string[] expectedNames)
{
var actualNames = handles.Select(h => GetAttributeConstructorName(reader, h)).ToArray();
AssertEx.Equal(actualNames, expectedNames);
}
private static void AssertNoNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
AssertAttributes(attributes);
}
private static void AssertNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
AssertAttributes(attributes, "System.Runtime.CompilerServices.NativeIntegerAttribute");
}
private static void AssertAttributes(ImmutableArray<CSharpAttributeData> attributes, params string[] expectedNames)
{
var actualNames = attributes.Select(a => a.AttributeClass.ToTestDisplayString()).ToArray();
AssertEx.Equal(actualNames, expectedNames);
}
private static void AssertNoNativeIntegerAttributes(CSharpCompilation comp)
{
var image = comp.EmitToArray();
using (var reader = new PEReader(image))
{
var metadataReader = reader.GetMetadataReader();
var attributes = metadataReader.GetCustomAttributeRows().Select(metadataReader.GetCustomAttributeName).ToArray();
Assert.False(attributes.Contains("NativeIntegerAttribute"));
}
}
private void AssertNativeIntegerAttributes(CSharpCompilation comp, string expected)
{
CompileAndVerify(comp, symbolValidator: module => AssertNativeIntegerAttributes(module, expected));
}
private static void AssertNativeIntegerAttributes(ModuleSymbol module, string expected)
{
var actual = NativeIntegerAttributesVisitor.GetString((PEModuleSymbol)module);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual);
}
private static CSharpAttributeData GetNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
return attributes.Single(a => a.AttributeClass.ToTestDisplayString() == "System.Runtime.CompilerServices.NativeIntegerAttribute");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_NativeInteger : CSharpTestBase
{
private static readonly SymbolDisplayFormat FormatWithSpecialTypes = SymbolDisplayFormat.TestFormat.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
[Fact]
public void EmptyProject()
{
var source = @"";
var comp = CreateCompilation(source);
var expected =
@"";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void ExplicitAttribute_FromSource()
{
var source =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(new[] { NativeIntegerAttributeDefinition, source });
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger] System.UIntPtr[] F2
";
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute");
Assert.NotNull(attributeType);
AssertNativeIntegerAttributes(module, expected);
});
}
[Fact]
public void ExplicitAttribute_FromMetadata()
{
var comp = CreateCompilation(NativeIntegerAttributeDefinition);
comp.VerifyDiagnostics();
var ref0 = comp.EmitToImageReference();
var source =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
comp = CreateCompilation(source, references: new[] { ref0 }, parseOptions: TestOptions.Regular9);
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger] System.UIntPtr[] F2
";
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute");
Assert.Null(attributeType);
AssertNativeIntegerAttributes(module, expected);
});
}
[Fact]
public void ExplicitAttribute_MissingEmptyConstructor()
{
var source1 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NativeIntegerAttribute : Attribute
{
public NativeIntegerAttribute(bool[] flags) { }
}
}";
var source2 =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nint F1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F1").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(3, 17),
// (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nuint[] F2;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F2").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(4, 20));
}
[Fact]
public void ExplicitAttribute_MissingConstructor()
{
var source1 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NativeIntegerAttribute : Attribute
{
}
}";
var source2 =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(new[] { source1, source2 }, parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (3,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nint F1;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F1").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(3, 17),
// (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// public nuint[] F2;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F2").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(4, 20));
}
[Fact]
public void ExplicitAttribute_ReferencedInSource()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal class NativeIntegerAttribute : Attribute
{
internal NativeIntegerAttribute() { }
internal NativeIntegerAttribute(bool[] flags) { }
}
}";
var source =
@"#pragma warning disable 67
#pragma warning disable 169
using System;
using System.Runtime.CompilerServices;
[NativeInteger] class Program
{
[NativeInteger] IntPtr F;
[NativeInteger] event EventHandler E;
[NativeInteger] object P { get; }
[NativeInteger(new[] { false, true })] static UIntPtr[] M1() => throw null;
[return: NativeInteger(new[] { false, true })] static UIntPtr[] M2() => throw null;
static void M3([NativeInteger]object arg) { }
}";
var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular8);
verifyDiagnostics(comp);
comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular9);
verifyDiagnostics(comp);
static void verifyDiagnostics(CSharpCompilation comp)
{
comp.VerifyDiagnostics(
// (5,2): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] class Program
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 2),
// (7,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] IntPtr F;
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 6),
// (8,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] event EventHandler E;
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(8, 6),
// (9,6): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [NativeInteger] object P { get; }
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(9, 6),
// (11,14): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// [return: NativeInteger(new[] { false, true })] static UIntPtr[] M2() => throw null;
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger(new[] { false, true })").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(11, 14),
// (12,21): error CS8335: Do not use 'System.Runtime.CompilerServices.NativeIntegerAttribute'. This is reserved for compiler usage.
// static void M3([NativeInteger]object arg) { }
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NativeInteger").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(12, 21));
}
}
[Fact]
public void MissingAttributeUsageAttribute()
{
var source =
@"public class Program
{
public nint F1;
public nuint[] F2;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
}
[Fact]
public void Metadata_ZeroElements()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0]
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0]
ret
}
.method public static void F1(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0]
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<System.IntPtr, System.UIntPtr>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F0(?, ?)' is not supported by the language
// B.F0(default, default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?, ?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(new A<System.IntPtr, System.UIntPtr>());
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(6, 11));
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F0(?, ?)' is not supported by the language
// B.F0(default, default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?, ?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(new A<System.IntPtr, System.UIntPtr>());
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(6, 11));
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0( x, y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1( a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(? x, ? y)
[NativeInteger({ })] ? x
[NativeInteger({ })] ? y
void F1(? a)
[NativeInteger({ })] ? a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_OneElementFalse()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F1(class A<int32, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F2(class A<native int, uint32> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<int, System.UIntPtr>());
B.F2(new A<System.IntPtr, uint>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0(System.IntPtr x, System.UIntPtr y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1(A<int, System.UIntPtr> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<System.IntPtr, uint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(System.IntPtr x, System.UIntPtr y)
[NativeInteger({ False })] System.IntPtr x
[NativeInteger({ False })] System.UIntPtr y
void F1(A<System.Int32, System.UIntPtr> a)
[NativeInteger({ False })] A<System.Int32, System.UIntPtr> a
void F2(A<System.IntPtr, System.UInt32> a)
[NativeInteger({ False })] A<System.IntPtr, System.UInt32> a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_OneElementTrue()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
ret
}
.method public static void F1(class A<int32, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
ret
}
.method public static void F2(class A<native int, uint32> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<int, nuint>());
B.F2(new A<nint, uint>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (6,25): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// B.F1(new A<int, nuint>());
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(6, 25),
// (7,20): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// B.F2(new A<nint, uint>());
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(7, 20));
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0(nint x, nuint y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1(A<int, nuint> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<nint, uint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(System.IntPtr x, System.UIntPtr y)
[NativeInteger({ True })] System.IntPtr x
[NativeInteger({ True })] System.UIntPtr y
void F1(A<System.Int32, System.UIntPtr> a)
[NativeInteger({ True })] A<System.Int32, System.UIntPtr> a
void F2(A<System.IntPtr, System.UInt32> a)
[NativeInteger({ True })] A<System.IntPtr, System.UInt32> a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_AllFalse()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}
.class public B
{
.method public static void F0(native int x, native uint y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
.param [2]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F1(class A<int32, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 00 00 00 ) // new[] { false }
ret
}
.method public static void F2(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 00 00 00 ) // new[] { false, false }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F0(default, default);
B.F1(new A<int, System.UIntPtr>());
B.F2(new A<System.IntPtr, System.UIntPtr>());
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F0(System.IntPtr x, System.UIntPtr y)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1(A<int, System.UIntPtr> a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<System.IntPtr, System.UIntPtr> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F0(System.IntPtr x, System.UIntPtr y)
[NativeInteger({ False })] System.IntPtr x
[NativeInteger({ False })] System.UIntPtr y
void F1(A<System.Int32, System.UIntPtr> a)
[NativeInteger({ False })] A<System.Int32, System.UIntPtr> a
void F2(A<System.IntPtr, System.UIntPtr> a)
[NativeInteger({ False, False })] A<System.IntPtr, System.UIntPtr> a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_TooFewAndTooManyTransformFlags()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class public A<T, U>
{
}
.class public B
{
.method public static void F(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor() = ( 01 00 00 00 ) // no array, too few
ret
}
.method public static void F0(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 00 00 00 00 00 00 ) // new bool[0], too few
ret
}
.method public static void F1(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 01 00 00 00 01 00 00 ) // new[] { true }, too few
ret
}
.method public static void F2(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }, valid
ret
}
.method public static void F3(class A<native int, native uint> a)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 03 00 00 00 00 01 01 00 00 ) // new[] { false, true, true }, too many
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F(A<nint, nuint> a)
{
B.F(a);
B.F0(a);
B.F1(a);
B.F2(a);
B.F3(a);
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (3,21): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// static void F(A<nint, nuint> a)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nint").WithArguments("native-sized integers", "9.0").WithLocation(3, 21),
// (3,27): error CS8400: Feature 'native-sized integers' is not available in C# 8.0. Please use language version 9.0 or greater.
// static void F(A<nint, nuint> a)
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "nuint").WithArguments("native-sized integers", "9.0").WithLocation(3, 27),
// (5,11): error CS0570: 'B.F(?)' is not supported by the language
// B.F(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F").WithArguments("B.F(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F0(?)' is not supported by the language
// B.F0(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(7, 11),
// (9,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(9, 11));
verify(comp);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F(?)' is not supported by the language
// B.F(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F").WithArguments("B.F(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F0(?)' is not supported by the language
// B.F0(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F0").WithArguments("B.F0(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(7, 11),
// (9,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(a);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(9, 11));
verify(comp);
static void verify(CSharpCompilation comp)
{
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F( a)", type.GetMember("F").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F0( a)", type.GetMember("F0").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F1( a)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2(A<System.IntPtr, nuint> a)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F3( a)", type.GetMember("F3").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"B
void F(? a)
[NativeInteger] ? a
void F0(? a)
[NativeInteger({ })] ? a
void F1(? a)
[NativeInteger({ True })] ? a
void F2(A<System.IntPtr, System.UIntPtr> a)
[NativeInteger({ False, True })] A<System.IntPtr, System.UIntPtr> a
void F3(? a)
[NativeInteger({ False, True, True })] ? a
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
}
[Fact]
public void Metadata_UnexpectedTarget()
{
var source0 =
@".class private System.Runtime.CompilerServices.NativeIntegerAttribute extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
.method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret }
}
.class A<T>
{
}
.class public B
{
.method public static void F1(int32 w)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor() = ( 01 00 00 00 )
ret
}
.method public static void F2(object[] x)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }
ret
}
.method public static void F3(class A<class B> y)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) // new[] { false, true }
ret
}
.method public static void F4(native int[] z)
{
.param [1]
.custom instance void System.Runtime.CompilerServices.NativeIntegerAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 01 01 00 00 ) // new[] { true, true }
ret
}
}";
var ref0 = CompileIL(source0);
var source1 =
@"class Program
{
static void F()
{
B.F1(default);
B.F2(default);
B.F3(default);
B.F4(default);
}
}";
var comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F2(?)' is not supported by the language
// B.F2(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("B.F2(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(7, 11),
// (8,11): error CS0570: 'B.F4(?)' is not supported by the language
// B.F4(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F4").WithArguments("B.F4(?)").WithLocation(8, 11)
);
comp = CreateCompilation(source1, new[] { ref0 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (5,11): error CS0570: 'B.F1(?)' is not supported by the language
// B.F1(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F1").WithArguments("B.F1(?)").WithLocation(5, 11),
// (6,11): error CS0570: 'B.F2(?)' is not supported by the language
// B.F2(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F2").WithArguments("B.F2(?)").WithLocation(6, 11),
// (7,11): error CS0570: 'B.F3(?)' is not supported by the language
// B.F3(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F3").WithArguments("B.F3(?)").WithLocation(7, 11),
// (8,11): error CS0570: 'B.F4(?)' is not supported by the language
// B.F4(default);
Diagnostic(ErrorCode.ERR_BindToBogus, "F4").WithArguments("B.F4(?)").WithLocation(8, 11)
);
var type = comp.GetTypeByMetadataName("B");
Assert.Equal("void B.F1( w)", type.GetMember("F1").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F2( x)", type.GetMember("F2").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F3( y)", type.GetMember("F3").ToDisplayString(FormatWithSpecialTypes));
Assert.Equal("void B.F4( z)", type.GetMember("F4").ToDisplayString(FormatWithSpecialTypes));
var expected =
@"
B
void F1(? w)
[NativeInteger] ? w
void F2(? x)
[NativeInteger({ False, True })] ? x
void F3(? y)
[NativeInteger({ False, True })] ? y
void F4(? z)
[NativeInteger({ True, True })] ? z
";
AssertNativeIntegerAttributes(type.ContainingModule, expected);
}
[Fact]
public void EmitAttribute_BaseClass()
{
var source =
@"public class A<T, U>
{
}
public class B : A<nint, nuint[]>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"[NativeInteger({ True, True })] B
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Interface()
{
var source =
@"public interface I<T>
{
}
public class A : I<(nint, nuint[])>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "A");
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])");
});
}
[Fact]
public void EmitAttribute_AllTypes()
{
var source =
@"public enum E { }
public class C<T>
{
public delegate void D<T>();
public enum F { }
public struct S<U> { }
public interface I<U> { }
public C<T>.S<nint> F1;
public C<nuint>.I<T> F2;
public C<E>.D<nint> F3;
public C<nuint>.D<dynamic> F4;
public C<C<nuint>.D<System.IntPtr>>.F F5;
public C<C<System.UIntPtr>.F>.D<nint> F6;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"C<T>
[NativeInteger] C<T>.S<System.IntPtr> F1
[NativeInteger] C<System.UIntPtr>.I<T> F2
[NativeInteger] C<E>.D<System.IntPtr> F3
[NativeInteger] C<System.UIntPtr>.D<dynamic> F4
[NativeInteger({ True, False })] C<C<System.UIntPtr>.D<System.IntPtr>>.F F5
[NativeInteger({ False, True })] C<C<System.UIntPtr>.F>.D<System.IntPtr> F6
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ErrorType()
{
var source1 =
@"public class A { }
public class B<T> { }";
var comp = CreateCompilation(source1, assemblyName: "95d36b13-f2e1-495d-9ab6-62e8cc63ac22");
var ref1 = comp.EmitToImageReference();
var source2 =
@"public class C<T, U> { }
public class D
{
public B<nint> F1;
public C<nint, A> F2;
}";
comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
var ref2 = comp.EmitToImageReference();
var source3 =
@"class Program
{
static void Main()
{
var d = new D();
_ = d.F1;
_ = d.F2;
}
}";
comp = CreateCompilation(source3, references: new[] { ref2 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,15): error CS0012: The type 'B<>' is defined in an assembly that is not referenced. You must add a reference to assembly '95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// _ = d.F1;
Diagnostic(ErrorCode.ERR_NoTypeDef, "F1").WithArguments("B<>", "95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 15),
// (7,15): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly '95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// _ = d.F2;
Diagnostic(ErrorCode.ERR_NoTypeDef, "F2").WithArguments("A", "95d36b13-f2e1-495d-9ab6-62e8cc63ac22, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 15));
}
[Fact]
public void EmitAttribute_Fields()
{
var source =
@"public class Program
{
public nint F1;
public (System.IntPtr, nuint[]) F2;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) F2
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_MethodReturnType()
{
var source =
@"public class Program
{
public (System.IntPtr, nuint[]) F() => default;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) F()
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_MethodParameters()
{
var source =
@"public class Program
{
public void F(nint x, nuint y) { }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
void F(System.IntPtr x, System.UIntPtr y)
[NativeInteger] System.IntPtr x
[NativeInteger] System.UIntPtr y
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_PropertyType()
{
var source =
@"public class Program
{
public (System.IntPtr, nuint[]) P => default;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) P { get; }
[NativeInteger({ False, True })] (System.IntPtr, System.UIntPtr[]) P.get
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_PropertyParameters()
{
var source =
@"public class Program
{
public object this[nint x, (nuint[], System.IntPtr) y] => null;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
System.Object this[System.IntPtr x, (System.UIntPtr[], System.IntPtr) y] { get; }
[NativeInteger] System.IntPtr x
[NativeInteger({ True, False })] (System.UIntPtr[], System.IntPtr) y
System.Object this[System.IntPtr x, (System.UIntPtr[], System.IntPtr) y].get
[NativeInteger] System.IntPtr x
[NativeInteger({ True, False })] (System.UIntPtr[], System.IntPtr) y
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_EventType()
{
var source =
@"using System;
public class Program
{
public event EventHandler<nuint[]> E;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"Program
[NativeInteger] event System.EventHandler<System.UIntPtr[]> E
void E.add
[NativeInteger] System.EventHandler<System.UIntPtr[]> value
void E.remove
[NativeInteger] System.EventHandler<System.UIntPtr[]> value
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_OperatorReturnType()
{
var source =
@"public class C
{
public static nint operator+(C a, C b) => 0;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"C
[NativeInteger] System.IntPtr operator +(C a, C b)
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_OperatorParameters()
{
var source =
@"public class C
{
public static C operator+(C a, nuint[] b) => a;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"C
C operator +(C a, System.UIntPtr[] b)
[NativeInteger] System.UIntPtr[] b
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_DelegateReturnType()
{
var source =
@"public delegate nint D();";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"D
[NativeInteger] System.IntPtr Invoke()
[NativeInteger] System.IntPtr EndInvoke(System.IAsyncResult result)
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_DelegateParameters()
{
var source =
@"public delegate void D(nint x, nuint[] y);";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"D
void Invoke(System.IntPtr x, System.UIntPtr[] y)
[NativeInteger] System.IntPtr x
[NativeInteger] System.UIntPtr[] y
System.IAsyncResult BeginInvoke(System.IntPtr x, System.UIntPtr[] y, System.AsyncCallback callback, System.Object @object)
[NativeInteger] System.IntPtr x
[NativeInteger] System.UIntPtr[] y
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Constraint()
{
var source =
@"public class A<T>
{
}
public class B<T> where T : A<nint>
{
}
public class C<T> where T : A<nuint[]>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var type = comp.GetMember<NamedTypeSymbol>("B");
Assert.Equal("A<nint>", getConstraintType(type).ToDisplayString(FormatWithSpecialTypes));
type = comp.GetMember<NamedTypeSymbol>("C");
Assert.Equal("A<nuint[]>", getConstraintType(type).ToDisplayString(FormatWithSpecialTypes));
static TypeWithAnnotations getConstraintType(NamedTypeSymbol type) => type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0];
}
[Fact]
public void EmitAttribute_LambdaReturnType()
{
var source =
@"using System;
class Program
{
static object M()
{
Func<nint> f = () => (nint)2;
return f();
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular9,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program+<>c").GetMethod("<M>b__0_0");
AssertNativeIntegerAttribute(method.GetReturnTypeAttributes());
});
}
[Fact]
public void EmitAttribute_LambdaParameters()
{
var source =
@"using System;
class Program
{
static void M()
{
Action<nuint[]> a = (nuint[] n) => { };
a(null);
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular9,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program+<>c").GetMethod("<M>b__0_0");
AssertNativeIntegerAttribute(method.Parameters[0].GetAttributes());
});
}
[Fact]
public void EmitAttribute_LocalFunctionReturnType()
{
var source =
@"class Program
{
static object M()
{
nint L() => (nint)2;
return L();
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular9,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<M>g__L|0_0");
AssertNativeIntegerAttribute(method.GetReturnTypeAttributes());
AssertAttributes(method.GetAttributes(), "System.Runtime.CompilerServices.CompilerGeneratedAttribute");
});
}
[Fact]
public void EmitAttribute_LocalFunctionParameters()
{
var source =
@"class Program
{
static void M()
{
void L(nuint[] n) { }
L(null);
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular9,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<M>g__L|0_0");
AssertNativeIntegerAttribute(method.Parameters[0].GetAttributes());
});
}
[Fact]
public void EmitAttribute_Lambda_NetModule()
{
var source =
@"class Program
{
static void Main()
{
var a1 = (nint n) => { };
a1(1);
var a2 = nuint[] () => null;
a2();
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseModule);
comp.VerifyDiagnostics(
// (5,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported
// var a1 = (nint n) => { };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 19),
// (7,29): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported
// var a2 = nuint[] () => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "=>").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 29));
}
[Fact]
public void EmitAttribute_LocalFunction_NetModule()
{
var source =
@"class Program
{
static void Main()
{
void L1(nint n) { };
L1(1);
nuint[] L2() => null;
L2();
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseModule);
comp.VerifyDiagnostics(
// (5,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported
// void L1(nint n) { };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(5, 17),
// (7,9): error CS0518: Predefined type 'System.Runtime.CompilerServices.NativeIntegerAttribute' is not defined or imported
// nuint[] L2() => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "nuint[]").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute").WithLocation(7, 9));
}
[Fact]
public void EmitAttribute_Lambda_MissingAttributeConstructor()
{
var sourceA =
@"namespace System.Runtime.CompilerServices
{
public sealed class NativeIntegerAttribute : Attribute
{
private NativeIntegerAttribute() { }
}
}";
var sourceB =
@"class Program
{
static void Main()
{
var a1 = (nint n) => { };
a1(1);
var a2 = nuint[] () => null;
a2();
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB });
comp.VerifyDiagnostics(
// (5,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// var a1 = (nint n) => { };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(5, 19),
// (7,29): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// var a2 = nuint[] () => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=>").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(7, 29));
}
[Fact]
public void EmitAttribute_LocalFunction_MissingAttributeConstructor()
{
var sourceA =
@"namespace System.Runtime.CompilerServices
{
public sealed class NativeIntegerAttribute : Attribute
{
private NativeIntegerAttribute() { }
}
}";
var sourceB =
@"class Program
{
static void Main()
{
void L1(nint n) { };
L1(1);
nuint[] L2() => null;
L2();
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB });
comp.VerifyDiagnostics(
// (5,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// void L1(nint n) { };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "nint n").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(5, 17),
// (7,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NativeIntegerAttribute..ctor'
// nuint[] L2() => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "nuint[]").WithArguments("System.Runtime.CompilerServices.NativeIntegerAttribute", ".ctor").WithLocation(7, 9));
}
[Fact]
public void EmitAttribute_LocalFunctionConstraints()
{
var source =
@"interface I<T>
{
}
class Program
{
static void M()
{
void L<T>() where T : I<nint> { }
L<I<nint>>();
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NativeIntegerAttribute"));
});
}
[Fact]
public void EmitAttribute_Nested()
{
var source =
@"public class A<T>
{
public class B<U> { }
}
unsafe public class Program
{
public nint F1;
public nuint[] F2;
public nint* F3;
public A<nint>.B<nuint> F4;
public (nint, nuint) F5;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
var expected =
@"Program
[NativeInteger] System.IntPtr F1
[NativeInteger] System.UIntPtr[] F2
[NativeInteger] System.IntPtr* F3
[NativeInteger({ True, True })] A<System.IntPtr>.B<System.UIntPtr> F4
[NativeInteger({ True, True })] (System.IntPtr, System.UIntPtr) F5
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_LongTuples_01()
{
var source =
@"public class A<T>
{
}
unsafe public class B
{
public A<(object, (nint, nuint, nint[], nuint, nint, nuint*[], nint, System.UIntPtr))> F1;
public A<(nint, object, nuint[], object, nint, object, (System.IntPtr, nuint), object, nuint)> F2;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll);
var expected =
@"B
[NativeInteger({ True, True, True, True, True, True, True, False })] A<(System.Object, (System.IntPtr, System.UIntPtr, System.IntPtr[], System.UIntPtr, System.IntPtr, System.UIntPtr*[], System.IntPtr, System.UIntPtr))> F1
[NativeInteger({ True, True, True, False, True, True })] A<(System.IntPtr, System.Object, System.UIntPtr[], System.Object, System.IntPtr, System.Object, (System.IntPtr, System.UIntPtr), System.Object, System.UIntPtr)> F2
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_LongTuples_02()
{
var source1 =
@"public interface IA { }
public interface IB<T> { }
public class C : IA, IB<(nint, object, nuint[], object, nint, object, (System.IntPtr, nuint), object, nuint)>
{
}";
var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C");
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().ElementAt(1));
var customAttributes = interfaceImpl.GetCustomAttributes();
AssertAttributes(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])");
var customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NativeIntegerAttribute..ctor(Boolean[])");
AssertEx.Equal(ImmutableArray.Create(true, true, true, false, true, true), reader.ReadBoolArray(customAttribute.Value));
});
var ref1 = comp.EmitToImageReference();
var source2 =
@"class Program
{
static void Main()
{
IA a = new C();
_ = a;
}
}";
comp = CreateCompilation(source2, references: new[] { ref1 }, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics();
}
[Fact]
[WorkItem(45519, "https://github.com/dotnet/roslyn/issues/45519")]
public void EmitAttribute_PartialMethods()
{
var source =
@"public partial class Program
{
static partial void F1(System.IntPtr x);
static partial void F2(System.UIntPtr x) { }
static partial void F1(nint x) { }
static partial void F2(nuint x);
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: TestOptions.Regular9);
var expected =
@"Program
void F2(System.UIntPtr x)
[NativeInteger] System.UIntPtr x
";
AssertNativeIntegerAttributes(comp, expected);
comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(6), parseOptions: TestOptions.Regular9);
comp.VerifyEmitDiagnostics(
// (4,25): warning CS8826: Partial method declarations 'void Program.F2(nuint x)' and 'void Program.F2(UIntPtr x)' have signature differences.
// static partial void F2(System.UIntPtr x) { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F2").WithArguments("void Program.F2(nuint x)", "void Program.F2(UIntPtr x)").WithLocation(4, 25),
// (5,25): warning CS8826: Partial method declarations 'void Program.F1(IntPtr x)' and 'void Program.F1(nint x)' have signature differences.
// static partial void F1(nint x) { }
Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F1").WithArguments("void Program.F1(IntPtr x)", "void Program.F1(nint x)").WithLocation(5, 25));
}
// Shouldn't depend on [NullablePublicOnly].
[Fact]
public void NoPublicMembers()
{
var source =
@"class A<T, U>
{
}
class B : A<System.UIntPtr, nint>
{
}";
var comp = CreateCompilation(
source,
options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9.WithNullablePublicOnly());
var expected =
@"[NativeInteger({ False, True })] B
";
AssertNativeIntegerAttributes(comp, expected);
}
[Fact]
public void AttributeUsage()
{
var source =
@"public class Program
{
public nint F;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NativeIntegerAttribute");
AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo();
Assert.False(attributeUsage.Inherited);
Assert.False(attributeUsage.AllowMultiple);
Assert.True(attributeUsage.HasValidAttributeTargets);
var expectedTargets =
AttributeTargets.Class |
AttributeTargets.Event |
AttributeTargets.Field |
AttributeTargets.GenericParameter |
AttributeTargets.Parameter |
AttributeTargets.Property |
AttributeTargets.ReturnValue;
Assert.Equal(expectedTargets, attributeUsage.ValidTargets);
});
}
[Fact]
public void AttributeFieldExists()
{
var source =
@"public class Program
{
public nint F;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
CompileAndVerify(comp, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Program");
var member = type.GetMembers("F").Single();
var attributes = member.GetAttributes();
AssertNativeIntegerAttribute(attributes);
var attribute = GetNativeIntegerAttribute(attributes);
var field = attribute.AttributeClass.GetField("TransformFlags");
Assert.Equal("System.Boolean[]", field.TypeWithAnnotations.ToTestDisplayString());
});
}
[Fact]
public void NestedNativeIntegerWithPrecedingType()
{
var comp = CompileAndVerify(@"
class C<T, U, V>
{
public C<dynamic, T, nint> F0;
public C<dynamic, nint, System.IntPtr> F1;
public C<dynamic, nuint, System.UIntPtr> F2;
public C<T, nint, System.IntPtr> F3;
public C<T, nuint, System.UIntPtr> F4;
}
", options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator);
static void symbolValidator(ModuleSymbol module)
{
var expectedAttributes = @"
C<T, U, V>
[NativeInteger] C<dynamic, T, System.IntPtr> F0
[NativeInteger({ True, False })] C<dynamic, System.IntPtr, System.IntPtr> F1
[NativeInteger({ True, False })] C<dynamic, System.UIntPtr, System.UIntPtr> F2
[NativeInteger({ True, False })] C<T, System.IntPtr, System.IntPtr> F3
[NativeInteger({ True, False })] C<T, System.UIntPtr, System.UIntPtr> F4
";
AssertNativeIntegerAttributes(module, expectedAttributes);
var c = module.GlobalNamespace.GetTypeMember("C");
assert("C<dynamic, T, nint>", "F0");
assert("C<dynamic, nint, System.IntPtr>", "F1");
assert("C<dynamic, nuint, System.UIntPtr>", "F2");
assert("C<T, nint, System.IntPtr>", "F3");
assert("C<T, nuint, System.UIntPtr>", "F4");
void assert(string expectedType, string fieldName)
{
Assert.Equal(expectedType, c.GetField(fieldName).Type.ToTestDisplayString());
}
}
}
[Fact]
public void FunctionPointersWithNativeIntegerTypes()
{
var comp = CompileAndVerify(@"
unsafe class C
{
public delegate*<nint, object, object> F0;
public delegate*<nint, nint, nint> F1;
public delegate*<System.IntPtr, System.IntPtr, nint> F2;
public delegate*<nint, System.IntPtr, System.IntPtr> F3;
public delegate*<System.IntPtr, nint, System.IntPtr> F4;
public delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, nint> F5;
public delegate*<nint, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F6;
public delegate*<delegate*<System.IntPtr, System.IntPtr, nint>, System.IntPtr> F7;
public delegate*<System.IntPtr, delegate*<System.IntPtr, nint, System.IntPtr>> F8;
}
", options: TestOptions.UnsafeReleaseDll, parseOptions: TestOptions.Regular9, symbolValidator: symbolValidator);
static void symbolValidator(ModuleSymbol module)
{
var expectedAttributes = @"
C
[NativeInteger] delegate*<System.IntPtr, System.Object, System.Object> F0
[NativeInteger({ True, True, True })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F1
[NativeInteger({ True, False, False })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F2
[NativeInteger({ False, True, False })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F3
[NativeInteger({ False, False, True })] delegate*<System.IntPtr, System.IntPtr, System.IntPtr> F4
[NativeInteger({ True, False, False, False })] delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, System.IntPtr> F5
[NativeInteger({ False, False, False, True })] delegate*<System.IntPtr, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F6
[NativeInteger({ False, True, False, False })] delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, System.IntPtr> F7
[NativeInteger({ False, False, True, False })] delegate*<System.IntPtr, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>> F8
";
AssertNativeIntegerAttributes(module, expectedAttributes);
var c = module.GlobalNamespace.GetTypeMember("C");
assert("delegate*<nint, System.Object, System.Object>", "F0");
assert("delegate*<nint, nint, nint>", "F1");
assert("delegate*<System.IntPtr, System.IntPtr, nint>", "F2");
assert("delegate*<nint, System.IntPtr, System.IntPtr>", "F3");
assert("delegate*<System.IntPtr, nint, System.IntPtr>", "F4");
assert("delegate*<delegate*<System.IntPtr, System.IntPtr, System.IntPtr>, nint>", "F5");
assert("delegate*<nint, delegate*<System.IntPtr, System.IntPtr, System.IntPtr>>", "F6");
assert("delegate*<delegate*<System.IntPtr, System.IntPtr, nint>, System.IntPtr>", "F7");
assert("delegate*<System.IntPtr, delegate*<System.IntPtr, nint, System.IntPtr>>", "F8");
void assert(string expectedType, string fieldName)
{
var field = c.GetField(fieldName);
FunctionPointerUtilities.CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)field.Type);
Assert.Equal(expectedType, c.GetField(fieldName).Type.ToTestDisplayString());
}
}
}
private static TypeDefinition GetTypeDefinitionByName(MetadataReader reader, string name)
{
return reader.GetTypeDefinition(reader.TypeDefinitions.Single(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name)));
}
private static string GetAttributeConstructorName(MetadataReader reader, CustomAttributeHandle handle)
{
return reader.Dump(reader.GetCustomAttribute(handle).Constructor);
}
private static CustomAttribute GetAttributeByConstructorName(MetadataReader reader, CustomAttributeHandleCollection handles, string name)
{
return reader.GetCustomAttribute(handles.FirstOrDefault(h => GetAttributeConstructorName(reader, h) == name));
}
private static void AssertAttributes(MetadataReader reader, CustomAttributeHandleCollection handles, params string[] expectedNames)
{
var actualNames = handles.Select(h => GetAttributeConstructorName(reader, h)).ToArray();
AssertEx.Equal(expectedNames, actualNames);
}
private static void AssertNoNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
AssertAttributes(attributes);
}
private static void AssertNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
AssertAttributes(attributes, "System.Runtime.CompilerServices.NativeIntegerAttribute");
}
private static void AssertAttributes(ImmutableArray<CSharpAttributeData> attributes, params string[] expectedNames)
{
var actualNames = attributes.Select(a => a.AttributeClass.ToTestDisplayString()).ToArray();
AssertEx.Equal(expectedNames, actualNames);
}
private static void AssertNoNativeIntegerAttributes(CSharpCompilation comp)
{
var image = comp.EmitToArray();
using (var reader = new PEReader(image))
{
var metadataReader = reader.GetMetadataReader();
var attributes = metadataReader.GetCustomAttributeRows().Select(metadataReader.GetCustomAttributeName).ToArray();
Assert.False(attributes.Contains("NativeIntegerAttribute"));
}
}
private void AssertNativeIntegerAttributes(CSharpCompilation comp, string expected)
{
CompileAndVerify(comp, symbolValidator: module => AssertNativeIntegerAttributes(module, expected));
}
private static void AssertNativeIntegerAttributes(ModuleSymbol module, string expected)
{
var actual = NativeIntegerAttributesVisitor.GetString((PEModuleSymbol)module);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual);
}
private static CSharpAttributeData GetNativeIntegerAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
return attributes.Single(a => a.AttributeClass.ToTestDisplayString() == "System.Runtime.CompilerServices.NativeIntegerAttribute");
}
}
}
| 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/Test/Emit/Attributes/AttributeTests_Nullable.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_Nullable : CSharpTestBase
{
// An empty project should not require System.Attribute.
[Fact]
public void EmptyProject_MissingAttribute()
{
var source = "";
var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1)
);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")]
public void SynthesizeNullableAttributeBasedOnInterfacesToEmit(bool useImageReferences)
{
Func<CSharpCompilation, MetadataReference> getReference = c => useImageReferences ? c.EmitToImageReference() : c.ToMetadataReference();
var lib1_source = @"
using System.Threading.Tasks;
#nullable enable
public interface I2<T, TResult>
{
Task<TResult> ExecuteAsync(T parameter);
}
public interface I1<T> : I2<T, object>
{
}
";
var lib1_comp = CreateCompilation(lib1_source);
lib1_comp.VerifyDiagnostics();
var lib2_source = @"
#nullable disable
public interface I0 : I1<string>
{
}";
var lib2_comp = CreateCompilation(lib2_source, references: new[] { getReference(lib1_comp) });
lib2_comp.VerifyDiagnostics();
var imc1 = (TypeSymbol)lib2_comp.GlobalNamespace.GetMember("I0");
AssertEx.SetEqual(
new[] { "I1<System.String>" },
imc1.InterfacesNoUseSiteDiagnostics().Select(i => i.ToTestDisplayString(includeNonNullable: true)));
AssertEx.SetEqual(
new[] { "I1<System.String>", "I2<System.String, System.Object!>" },
imc1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString(includeNonNullable: true)));
var client_source = @"
public class C
{
public void M(I0 imc)
{
imc.ExecuteAsync("""");
}
}";
var client_comp = CreateCompilation(client_source, references: new[] { getReference(lib1_comp), getReference(lib2_comp) });
client_comp.VerifyDiagnostics();
var imc2 = (TypeSymbol)client_comp.GlobalNamespace.GetMember("I0");
// Note: it is expected that the symbol shows different Interfaces in PE vs. compilation reference
AssertEx.SetEqual(
useImageReferences
? new[] { "I1<System.String>", "I2<System.String, System.Object!>" }
: new[] { "I1<System.String>" },
imc2.InterfacesNoUseSiteDiagnostics().Select(i => i.ToTestDisplayString(includeNonNullable: true)));
AssertEx.SetEqual(
new[] { "I1<System.String>", "I2<System.String, System.Object!>" },
imc2.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString(includeNonNullable: true)));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")]
public void SynthesizeNullableAttributeBasedOnInterfacesToEmit_NotOnAllInterfaces(bool useImageReferences)
{
Func<CSharpCompilation, MetadataReference> getReference = c => useImageReferences ? c.EmitToImageReference() : c.ToMetadataReference();
var lib1_source = @"
#nullable enable
public interface I2<T, TResult>
{
}
public interface I1<T> : I2<T, object>
{
}
";
var lib1_comp = CreateCompilation(lib1_source);
lib1_comp.VerifyDiagnostics();
var lib2_source = @"
#nullable disable
public class C0 : I1<string>
{
}";
var lib2_comp = CreateCompilation(lib2_source, references: new[] { getReference(lib1_comp) });
lib2_comp.VerifyDiagnostics();
var lib2_c0 = (TypeSymbol)lib2_comp.GlobalNamespace.GetMember("C0");
AssertEx.SetEqual(
new[] { "I1<System.String>" },
lib2_c0.InterfacesNoUseSiteDiagnostics().Select(i => i.ToTestDisplayString(includeNonNullable: true)));
AssertEx.SetEqual(
new[] { "I1<System.String>", "I2<System.String, System.Object!>" },
lib2_c0.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString(includeNonNullable: true)));
CompileAndVerify(lib2_comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C0");
var interfaceHandles = typeDef.GetInterfaceImplementations();
var interfaceImpl1 = reader.GetInterfaceImplementation(interfaceHandles.First());
Assert.Equal("TypeSpecification:I1`1{String}", reader.Dump(interfaceImpl1.Interface));
AssertAttributes(reader, interfaceImpl1.GetCustomAttributes());
var interfaceImpl2 = reader.GetInterfaceImplementation(interfaceHandles.Last());
Assert.Equal("TypeSpecification:I2`2{String, Object}", reader.Dump(interfaceImpl2.Interface));
AssertAttributes(reader, interfaceImpl2.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
assertType(reader, exists: true, "NullableAttribute");
});
var lib3_source = @"
#nullable disable
public class C1 : C0
{
}";
var lib3_comp = CreateCompilation(lib3_source, references: new[] { getReference(lib1_comp), getReference(lib2_comp) });
lib3_comp.VerifyDiagnostics();
var lib3_c0 = (TypeSymbol)lib2_comp.GlobalNamespace.GetMember("C0");
AssertEx.SetEqual(
new[] { "I1<System.String>" },
lib3_c0.InterfacesNoUseSiteDiagnostics().Select(i => i.ToTestDisplayString(includeNonNullable: true)));
AssertEx.SetEqual(
new[] { "I1<System.String>", "I2<System.String, System.Object!>" },
lib3_c0.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString(includeNonNullable: true)));
CompileAndVerify(lib3_comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C1");
var interfaceHandles = typeDef.GetInterfaceImplementations();
Assert.True(interfaceHandles.IsEmpty());
assertType(reader, exists: false, "NullableAttribute");
});
void assertType(MetadataReader reader, bool exists, string name)
{
if (exists)
{
_ = reader.TypeDefinitions.Single(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name));
}
else
{
Assert.False(reader.TypeDefinitions.Any(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name)));
}
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")]
public void SynthesizeTupleElementNamesAttributeBasedOnInterfacesToEmit_IndirectInterfaces(bool useImageReferences)
{
Func<CSharpCompilation, MetadataReference> getReference = c => useImageReferences ? c.EmitToImageReference() : c.ToMetadataReference();
var valueTuple_source = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
public override string ToString()
{
return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}';
}
}
}";
var valueTuple_comp = CreateCompilationWithMscorlib40(valueTuple_source);
valueTuple_comp.VerifyDiagnostics();
var tupleElementNamesAttribute_source = @"
namespace System.Runtime.CompilerServices
{
public class TupleElementNamesAttribute : Attribute
{
public TupleElementNamesAttribute(string[] transformNames) { }
}
}";
var tupleElementNamesAttribute_comp = CreateCompilationWithMscorlib40(tupleElementNamesAttribute_source);
tupleElementNamesAttribute_comp.VerifyDiagnostics();
var lib1_source = @"
using System.Threading.Tasks;
public interface I2<T, TResult>
{
Task<TResult> ExecuteAsync(T parameter);
}
public interface I1<T> : I2<T, (object a, object b)>
{
}
";
var lib1_comp = CreateCompilationWithMscorlib40(lib1_source, references: new[] { getReference(valueTuple_comp), getReference(tupleElementNamesAttribute_comp) });
lib1_comp.VerifyDiagnostics();
var lib2_source = @"
public interface I0 : I1<string>
{
}";
var lib2_comp = CreateCompilationWithMscorlib40(lib2_source, references: new[] { getReference(lib1_comp), getReference(valueTuple_comp) }); // missing TupleElementNamesAttribute
lib2_comp.VerifyDiagnostics(
// (2,18): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
// public interface I0 : I1<string>
Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "I0").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(2, 18)
);
lib2_comp.VerifyEmitDiagnostics(
// (2,18): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
// public interface I0 : I1<string>
Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "I0").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(2, 18)
);
var imc1 = (TypeSymbol)lib2_comp.GlobalNamespace.GetMember("I0");
AssertEx.SetEqual(
new[] { "I1<System.String>" },
imc1.InterfacesNoUseSiteDiagnostics().Select(i => i.ToTestDisplayString(includeNonNullable: true)));
AssertEx.SetEqual(
new[] { "I1<System.String>", "I2<System.String, (System.Object a, System.Object b)>" },
imc1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString(includeNonNullable: true)));
}
[Fact, WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")]
public void SynthesizeTupleElementNamesAttributeBasedOnInterfacesToEmit_BaseAndDirectInterface()
{
var source = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
public override string ToString()
{
return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}';
}
}
}
namespace System.Runtime.CompilerServices
{
public class TupleElementNamesAttribute : Attribute
{
public TupleElementNamesAttribute() { } // Note: bad signature
}
}
public interface I<T> { }
public class Base<T> { }
public class C1 : I<(object a, object b)> { }
public class C2 : Base<(object a, object b)> { }
";
var comp = CreateCompilationWithMscorlib40(source);
comp.VerifyEmitDiagnostics(
// (34,14): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
// public class C1 : I<(object a, object b)> { }
Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "C1").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(34, 14),
// (34,21): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
// public class C1 : I<(object a, object b)> { }
Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(object a, object b)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(34, 21),
// (36,24): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
// public class C2 : Base<(object a, object b)> { }
Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(object a, object b)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(36, 24)
);
}
[Fact]
public void ExplicitAttributeFromSource()
{
var source =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute
{
public NullableAttribute(byte a) { }
public NullableAttribute(byte[] b) { }
}
}
class C
{
static void F(object? x, object?[] y) { }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ExplicitAttributeFromMetadata()
{
var source0 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute
{
public NullableAttribute(byte a) { }
public NullableAttribute(byte[] b) { }
}
}";
var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7);
var ref0 = comp0.EmitToImageReference();
var source =
@"class C
{
static void F(object? x, object?[] y) { }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ExplicitAttribute_MissingSingleByteConstructor()
{
var source =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute
{
public NullableAttribute(byte[] b) { }
}
}
class C
{
static void F(object? x, object?[] y) { }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (5,34): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// public NullableAttribute(byte[] b) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "byte[] b").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(5, 34),
// (10,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 19),
// (10,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?[] y").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 30));
}
[Fact]
public void ExplicitAttribute_MissingConstructor()
{
var source =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute
{
public NullableAttribute() { }
}
}
class C
{
static void F(object? x, object?[] y) { }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (10,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 19),
// (10,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?[] y").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 30));
}
[Fact]
public void ExplicitAttribute_MissingBothNeededConstructors()
{
var source =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute
{
public NullableAttribute(string[] b) { }
}
}
class C
{
static void F(object? x, object?[] y) { }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (5,34): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// public NullableAttribute(string[] b) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "string[] b").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(5, 34),
// (10,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 19),
// (10,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?[] y").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 30));
}
[Fact]
public void ExplicitAttribute_ReferencedInSource()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal class NullableAttribute : System.Attribute
{
internal NullableAttribute(byte b) { }
}
}";
var source =
@"#pragma warning disable 169
using System.Runtime.CompilerServices;
[assembly: Nullable(0)]
[module: Nullable(0)]
[Nullable(0)]
class Program
{
[Nullable(0)]object F;
[Nullable(0)]static object M1() => throw null;
[return: Nullable(0)]static object M2() => throw null;
static void M3([Nullable(0)]object arg) { }
}";
// C#7
var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular7);
verifyDiagnostics(comp);
// C#8
comp = CreateCompilation(new[] { sourceAttribute, source });
verifyDiagnostics(comp);
static void verifyDiagnostics(CSharpCompilation comp)
{
comp.VerifyDiagnostics(
// (5,2): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed.
// [Nullable(0)]
Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(5, 2),
// (8,6): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed.
// [Nullable(0)]object F;
Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(8, 6),
// (10,14): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed.
// [return: Nullable(0)]static object M2() => throw null;
Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(10, 14),
// (11,21): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed.
// static void M3([Nullable(0)]object arg) { }
Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(11, 21));
}
}
[Fact]
public void AttributeFromInternalsVisibleTo_01()
{
var sourceA =
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""B"")]
#nullable enable
class A
{
object? F = null;
}";
var options = TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All);
var comp = CreateCompilation(sourceA, assemblyName: "A", options: options);
CompileAndVerify(comp, symbolValidator: m => CheckAttribute(m.GlobalNamespace.GetMember("A.F").GetAttributes().Single(), "A"));
var refA = comp.EmitToImageReference();
var sourceB =
@"#nullable enable
class B
{
object? G = new A();
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, assemblyName: "B", options: options);
CompileAndVerify(comp, symbolValidator: m => CheckAttribute(m.GlobalNamespace.GetMember("B.G").GetAttributes().Single(), "B"));
}
[Fact]
public void AttributeFromInternalsVisibleTo_02()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal sealed class NullableAttribute : Attribute
{
public NullableAttribute(byte b) { }
public NullableAttribute(byte[] b) { }
}
}";
var sourceA =
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""B"")]
#nullable enable
class A
{
object? F = null;
}";
var options = TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All);
var comp = CreateCompilation(new[] { sourceAttribute, sourceA }, assemblyName: "A", options: options);
CompileAndVerify(comp, symbolValidator: m => CheckAttribute(m.GlobalNamespace.GetMember("A.F").GetAttributes().Single(), "A"));
var refA = comp.EmitToImageReference();
var sourceB =
@"#nullable enable
class B
{
object? G = new A();
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, assemblyName: "B", options: options);
CompileAndVerify(comp, symbolValidator: m => CheckAttribute(m.GlobalNamespace.GetMember("B.G").GetAttributes().Single(), "A"));
}
private static void CheckAttribute(CSharpAttributeData attribute, string assemblyName)
{
var attributeType = attribute.AttributeClass;
Assert.Equal("System.Runtime.CompilerServices", attributeType.ContainingNamespace.QualifiedName);
Assert.Equal("NullableAttribute", attributeType.Name);
Assert.Equal(assemblyName, attributeType.ContainingAssembly.Name);
}
[Fact]
public void NullableAttribute_MissingByte()
{
var source0 =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public class Attribute
{
}
}";
var comp0 = CreateEmptyCompilation(source0, parseOptions: TestOptions.Regular7);
var ref0 = comp0.EmitToImageReference();
var source =
@"class C
{
object? F() => null;
}";
var comp = CreateEmptyCompilation(
source,
references: new[] { ref0 },
parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (3,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// object? F() => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 11),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Int32' is not defined or imported
//
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "").WithArguments("System.Int32").WithLocation(1, 1));
}
[Fact]
public void NullableAttribute_MissingAttribute()
{
var source0 =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Byte { }
}";
var comp0 = CreateEmptyCompilation(source0, parseOptions: TestOptions.Regular7);
var ref0 = comp0.EmitToImageReference();
var source =
@"class C
{
object? F() => null;
}";
var comp = CreateEmptyCompilation(
source,
references: new[] { ref0 },
parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (3,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// object? F() => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 11),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
}
[Fact]
public void NullableAttribute_StaticAttributeConstructorOnly()
{
var source0 =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Byte { }
public class Attribute
{
static Attribute() { }
public Attribute(object o) { }
}
}";
var comp0 = CreateEmptyCompilation(source0, parseOptions: TestOptions.Regular7);
var ref0 = comp0.EmitToImageReference();
var source =
@"class C
{
object? F() => null;
}";
var comp = CreateEmptyCompilation(
source,
references: new[] { ref0 },
parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (3,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// object? F() => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 11),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments
Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1),
// error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments
Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1),
// error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments
Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1),
// error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments
Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1));
}
[Fact]
public void MissingAttributeUsageAttribute()
{
var source =
@"#nullable enable
class Program
{
object? F() => null;
}";
var comp = CreateCompilation(source);
comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
comp = CreateCompilation(source);
comp.MakeMemberMissing(WellKnownMember.System_AttributeUsageAttribute__ctor);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1));
comp = CreateCompilation(source);
comp.MakeMemberMissing(WellKnownMember.System_AttributeUsageAttribute__AllowMultiple);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1));
comp = CreateCompilation(source);
comp.MakeMemberMissing(WellKnownMember.System_AttributeUsageAttribute__Inherited);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
}
[Fact]
public void EmitAttribute_NoNullable()
{
var source =
@"public class C
{
public object F = new object();
}";
// C# 7.0: No NullableAttribute.
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
var type = assembly.GetTypeByMetadataName("C");
var field = (FieldSymbol)type.GetMembers("F").Single();
AssertNoNullableAttribute(field.GetAttributes());
AssertNoNullableAttribute(module.GetAttributes());
AssertAttributes(assembly.GetAttributes(),
"System.Runtime.CompilerServices.CompilationRelaxationsAttribute",
"System.Runtime.CompilerServices.RuntimeCompatibilityAttribute",
"System.Diagnostics.DebuggableAttribute");
});
// C# 8.0: NullableAttribute not included if no ? annotation.
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
var type = assembly.GetTypeByMetadataName("C");
var field = (FieldSymbol)type.GetMembers("F").Single();
AssertNoNullableAttribute(field.GetAttributes());
AssertNoNullableAttribute(module.GetAttributes());
AssertAttributes(assembly.GetAttributes(),
"System.Runtime.CompilerServices.CompilationRelaxationsAttribute",
"System.Runtime.CompilerServices.RuntimeCompatibilityAttribute",
"System.Diagnostics.DebuggableAttribute");
});
}
[Fact]
public void EmitAttribute_LocalFunctionConstraints()
{
var source = @"
class C
{
#nullable enable
void M1()
{
local(new C());
void local<T>(T t) where T : C?
{
}
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_OnlyAnnotationsEnabled_LocalFunctionConstraints()
{
var source = @"
class C
{
#nullable enable annotations
void M1()
{
local(new C());
void local<T>(T t) where T : C?
{
}
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_NullableEnabledInProject_LocalFunctionConstraints()
{
var source = @"
class C
{
void M1()
{
local(new C());
void local<T>(T t) where T : C?
{
}
}
}";
var comp = CreateCompilation(new[] { source }, options: WithNullable(NullableContextOptions.Enable), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_OnlyAnnotationsEnabledInProject_LocalFunctionConstraints()
{
var source = @"
class C
{
void M1()
{
local(new C());
void local<T>(T t) where T : C?
{
}
}
}";
var comp = CreateCompilation(new[] { source }, options: WithNullable(NullableContextOptions.Annotations), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_LocalFunctionConstraints_Nested()
{
var source = @"
interface I<T> { }
class C
{
#nullable enable
void M1()
{
void local<T>(T t) where T : I<C?>
{
}
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_LocalFunctionConstraints_NoAnnotation()
{
var source = @"
class C
{
#nullable enable
void M1()
{
local(new C());
void local<T>(T t) where T : C
{
}
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_Module()
{
var source =
@"public class C
{
public object? F = new object();
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
var type = assembly.GetTypeByMetadataName("C");
var field = (FieldSymbol)type.GetMembers("F").Single();
AssertNullableAttribute(field.GetAttributes());
AssertNoNullableAttribute(module.GetAttributes());
AssertAttributes(assembly.GetAttributes(),
"System.Runtime.CompilerServices.CompilationRelaxationsAttribute",
"System.Runtime.CompilerServices.RuntimeCompatibilityAttribute",
"System.Diagnostics.DebuggableAttribute");
});
}
[Fact]
public void EmitAttribute_NetModule()
{
var source =
@"public class C
{
public object? F = new object();
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public object? F = new object();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "F").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 20));
}
[Fact]
public void EmitAttribute_NetModuleNoDeclarations()
{
var source = "";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseModule);
CompileAndVerify(comp, verify: Verification.Skipped, symbolValidator: module =>
{
AssertAttributes(module.GetAttributes());
});
}
[Fact]
public void EmitAttribute_01()
{
var source =
@"public class Program
{
public object? F;
public object?[]? G;
}";
var comp = CreateCompilation(source, options: WithNullableEnable());
var expected =
@"[NullableContext(2)] [Nullable(0)] Program
System.Object? F
System.Object?[]? G
Program()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_02()
{
var source =
@"public class Program
{
public object? F(object?[]? args) => null;
public object G(object[] args) => null!;
}";
var comp = CreateCompilation(source, options: WithNullableEnable());
var expected =
@"Program
[NullableContext(2)] System.Object? F(System.Object?[]? args)
System.Object?[]? args
[NullableContext(1)] System.Object! G(System.Object![]! args)
System.Object![]! args
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_03()
{
var source =
@"public class Program
{
public static void F(string x, string y, string z) { }
}";
var comp = CreateCompilation(source, options: WithNullableEnable());
var expected =
@"Program
[NullableContext(1)] void F(System.String! x, System.String! y, System.String! z)
System.String! x
System.String! y
System.String! z
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_BaseClass()
{
var source =
@"public class A<T>
{
}
public class B1 : A<object>
{
}
public class B2 : A<object?>
{
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
var expected =
@"A<T>
[Nullable(2)] T
[Nullable({ 0, 1 })] B1
[Nullable({ 0, 2 })] B2
";
AssertNullableAttributes(comp, expected);
var source2 =
@"class C
{
static void F(A<object> x, A<object?> y)
{
}
static void G(B1 x, B2 y)
{
F(x, x);
F(y, y);
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (8,14): warning CS8620: Argument of type 'B1' cannot be used as an input of type 'A<object?>' for parameter 'y' in 'void C.F(A<object> x, A<object?> y)' due to differences in the nullability of reference types.
// F(x, x);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B1", "A<object?>", "y", "void C.F(A<object> x, A<object?> y)").WithLocation(8, 14),
// (9,11): warning CS8620: Argument of type 'B2' cannot be used as an input of type 'A<object>' for parameter 'x' in 'void C.F(A<object> x, A<object?> y)' due to differences in the nullability of reference types.
// F(y, y);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B2", "A<object>", "x", "void C.F(A<object> x, A<object?> y)").WithLocation(9, 11));
}
[Fact]
public void EmitAttribute_Interface_01()
{
var source =
@"public interface I<T>
{
}
public class A : I<object>
{
}
#nullable disable
public class AOblivious : I<object> { }
#nullable enable
public class B : I<object?>
{
}
";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "A");
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
typeDef = GetTypeDefinitionByName(reader, "B");
interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
});
var source2 =
@"class C
{
static void F(I<object> x, I<object?> y) { }
#nullable disable
static void FOblivious(I<object> x) { }
#nullable enable
static void G(A x, B y, AOblivious z)
{
F(x, x);
F(y, y);
F(z, z);
FOblivious(x);
FOblivious(y);
FOblivious(z);
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (9,14): warning CS8620: Argument of type 'A' cannot be used as an input of type 'I<object?>' for parameter 'y' in 'void C.F(I<object> x, I<object?> y)' due to differences in the nullability of reference types.
// F(x, x);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("A", "I<object?>", "y", "void C.F(I<object> x, I<object?> y)").WithLocation(9, 14),
// (10,11): warning CS8620: Argument of type 'B' cannot be used as an input of type 'I<object>' for parameter 'x' in 'void C.F(I<object> x, I<object?> y)' due to differences in the nullability of reference types.
// F(y, y);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B", "I<object>", "x", "void C.F(I<object> x, I<object?> y)").WithLocation(10, 11));
}
[Fact]
public void EmitAttribute_Interface_02()
{
var source =
@"public interface I<T>
{
}
public class A : I<(object X, object Y)>
{
}
public class B : I<(object X, object? Y)>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "A");
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(),
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])");
typeDef = GetTypeDefinitionByName(reader, "B");
interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(),
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])",
"MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
});
var source2 =
@"class C
{
static void F(I<(object, object)> a, I<(object, object?)> b)
{
}
static void G(A a, B b)
{
F(a, a);
F(b, b);
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (9,11): warning CS8620: Argument of type 'B' cannot be used as an input of type 'I<(object, object)>' for parameter 'a' in 'void C.F(I<(object, object)> a, I<(object, object?)> b)' due to differences in the nullability of reference types.
// F(b, b);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b").WithArguments("B", "I<(object, object)>", "a", "void C.F(I<(object, object)> a, I<(object, object?)> b)").WithLocation(9, 11));
var type = comp2.GetMember<NamedTypeSymbol>("A");
Assert.Equal("I<(System.Object X, System.Object Y)>", type.Interfaces()[0].ToTestDisplayString());
type = comp2.GetMember<NamedTypeSymbol>("B");
Assert.Equal("I<(System.Object X, System.Object? Y)>", type.Interfaces()[0].ToTestDisplayString());
}
[Fact]
public void EmitAttribute_ImplementedInterfaces_01()
{
var source =
@"#nullable enable
public interface I<T> { }
public class A :
I<object>,
I<string?>
{
public object FA1;
public object FA2;
}
public class B :
#nullable disable
I<object>,
#nullable enable
I<int>
{
public object FB1;
public object FB2;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(2)] I<T>
T
[NullableContext(1)] [Nullable(0)] A
System.Object! FA1
System.Object! FA2
A()
B
[Nullable(1)] System.Object! FB1
[Nullable(1)] System.Object! FB2
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ImplementedInterfaces_02()
{
var source =
@"#nullable enable
public interface IA { }
public interface IB<T> : IA { }
public interface IC<T> : IB<
#nullable disable
object
#nullable enable
>
{
}
public class C : IC<
#nullable disable
string
#nullable enable
>
{
public object F1;
public object F2;
public object F3;
}";
var comp = CreateCompilation(source);
var expected =
@"IB<T>
[Nullable(2)] T
IC<T>
[Nullable(2)] T
C
[Nullable(1)] System.Object! F1
[Nullable(1)] System.Object! F2
[Nullable(1)] System.Object! F3
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_TypeParameters()
{
var source =
@"#nullable enable
public interface I<T, U, V>
where U : class
where V : struct
{
T F1();
U F2();
U? F3();
V F4();
V? F5();
#nullable disable
T F6();
U F7();
U? F8();
V F9();
V? F10();
}";
var comp = CreateCompilation(source);
var expected =
@"I<T, U, V> where U : class! where V : struct
[Nullable(2)] T
[Nullable(1)] U
[NullableContext(1)] T F1()
[NullableContext(1)] U! F2()
[NullableContext(2)] U? F3()
[NullableContext(2)] U? F8()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Constraint_Nullable()
{
var source =
@"public class A
{
}
public class C<T> where T : A?
{
}
public class D<T> where T : A
{
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C`1");
var typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
var constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte)");
typeDef = GetTypeDefinitionByName(reader, "D`1");
typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte)");
});
var source2 =
@"class B : A { }
class Program
{
static void Main()
{
new C<A?>();
new C<A>();
new C<B?>();
new C<B>();
new D<A?>(); // warning
new D<A>();
new D<B?>(); // warning
new D<B>();
}
}";
var comp2 = CreateCompilation(new[] { source, source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp2.VerifyEmitDiagnostics(
// (10,15): warning CS8627: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'.
// new D<A?>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A?").WithArguments("D<T>", "A", "T", "A?").WithLocation(10, 15),
// (12,15): warning CS8627: The type 'B?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'B?' doesn't match constraint type 'A'.
// new D<B?>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "B?").WithArguments("D<T>", "A", "T", "B?").WithLocation(12, 15));
comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyEmitDiagnostics(
// (10,15): warning CS8627: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'.
// new D<A?>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A?").WithArguments("D<T>", "A", "T", "A?").WithLocation(10, 15),
// (12,15): warning CS8627: The type 'B?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'B?' doesn't match constraint type 'A'.
// new D<B?>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "B?").WithArguments("D<T>", "A", "T", "B?").WithLocation(12, 15));
var type = comp2.GetMember<NamedTypeSymbol>("C");
Assert.Equal("A?", type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
type = comp2.GetMember<NamedTypeSymbol>("D");
Assert.Equal("A!", type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
}
// https://github.com/dotnet/roslyn/issues/29976: Test with [NonNullTypes].
[Fact]
public void EmitAttribute_Constraint_Oblivious()
{
var source =
@"public class A<T>
{
}
public class C<T> where T : A<object>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C`1");
var typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
var constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes());
});
var source2 =
@"class B1 : A<object?> { }
class B2 : A<object> { }
class Program
{
static void Main()
{
new C<A<object?>>();
new C<A<object>>();
new C<A<object?>?>();
new C<A<object>?>();
new C<B1>();
new C<B2>();
new C<B1?>();
new C<B2?>();
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics();
var type = comp2.GetMember<NamedTypeSymbol>("C");
Assert.Equal("A<System.Object>", type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
}
[WorkItem(27742, "https://github.com/dotnet/roslyn/issues/27742")]
[Fact]
public void EmitAttribute_Constraint_Nested()
{
var source =
@"public class A<T>
{
}
public class B<T> where T : A<object?>
{
}
public class C<T> where T : A<object>
{
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "B`1");
var typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
var constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
typeDef = GetTypeDefinitionByName(reader, "C`1");
typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte)");
});
var source2 =
@"class Program
{
static void Main()
{
new B<A<object?>>();
new B<A<object>>(); // warning
new C<A<object?>>(); // warning
new C<A<object>>();
}
}";
var comp2 = CreateCompilation(new[] { source, source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp2.VerifyEmitDiagnostics(
// (6,15): warning CS8627: The type 'A<object>' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. Nullability of type argument 'A<object>' doesn't match constraint type 'A<object?>'.
// new B<A<object>>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<object>").WithArguments("B<T>", "A<object?>", "T", "A<object>").WithLocation(6, 15),
// (7,15): warning CS8627: The type 'A<object?>' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'A<object?>' doesn't match constraint type 'A<object>'.
// new C<A<object?>>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<object?>").WithArguments("C<T>", "A<object>", "T", "A<object?>").WithLocation(7, 15));
comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (6,15): warning CS8627: The type 'A<object>' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. Nullability of type argument 'A<object>' doesn't match constraint type 'A<object?>'.
// new B<A<object>>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<object>").WithArguments("B<T>", "A<object?>", "T", "A<object>").WithLocation(6, 15),
// (7,15): warning CS8627: The type 'A<object?>' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'A<object?>' doesn't match constraint type 'A<object>'.
// new C<A<object?>>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<object?>").WithArguments("C<T>", "A<object>", "T", "A<object?>").WithLocation(7, 15));
var type = comp2.GetMember<NamedTypeSymbol>("B");
Assert.Equal("A<System.Object?>!", type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
type = comp2.GetMember<NamedTypeSymbol>("C");
Assert.Equal("A<System.Object!>!", type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
}
[Fact]
public void EmitAttribute_Constraint_TypeParameter()
{
var source =
@"public class C<T, U>
where T : class
where U : T?
{
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C`2");
var typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[1]);
var constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte)");
});
var source2 =
@"class Program
{
static void Main()
{
new C<object?, string?>();
new C<object?, string>();
new C<object, string?>();
new C<object, string>();
}
}";
var comp2 = CreateCompilation(new[] { source, source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
var expected = new[] {
// (5,15): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T, U>'. Nullability of type argument 'object?' doesn't match 'class' constraint.
// new C<object?, string?>();
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T, U>", "T", "object?").WithLocation(5, 15),
// (6,15): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T, U>'. Nullability of type argument 'object?' doesn't match 'class' constraint.
// new C<object?, string>();
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T, U>", "T", "object?").WithLocation(6, 15)
};
comp2.VerifyEmitDiagnostics(expected);
comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyEmitDiagnostics(expected);
var type = comp2.GetMember<NamedTypeSymbol>("C");
Assert.Equal("T?", type.TypeParameters[1].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
}
[Fact]
public void EmitAttribute_Constraints()
{
var source =
@"#nullable enable
public abstract class Program
{
#nullable disable
public abstract void M0<T1, T2, T3, T4>()
where T1 : class
where T2 : class
where T3 : class
#nullable enable
where T4 : class?;
public abstract void M1<T1, T2, T3, T4>()
where T1 : class
where T2 : class
where T3 : class
#nullable disable
where T4 : class;
#nullable enable
public abstract void M2<T1, T2, T3, T4>()
where T1 : class?
where T2 : class?
where T3 : class?
where T4 : class;
private object _f1;
private object _f2;
private object _f3;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
[NullableContext(0)] void M0<T1, T2, T3, T4>() where T1 : class where T2 : class where T3 : class where T4 : class?
T1
T2
T3
[Nullable(2)] T4
void M1<T1, T2, T3, T4>() where T1 : class! where T2 : class! where T3 : class! where T4 : class
T1
T2
T3
[Nullable(0)] T4
[NullableContext(2)] void M2<T1, T2, T3, T4>() where T1 : class? where T2 : class? where T3 : class? where T4 : class!
T1
T2
T3
[Nullable(1)] T4
Program()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ClassConstraint_SameAsContext()
{
var source =
@"#nullable enable
public class Program
{
public class C0<T0>
#nullable disable
where T0 : class
#nullable enable
{
#nullable disable
public object F01;
public object F02;
#nullable enable
}
public class C1<T1>
where T1 : class
{
public object F11;
public object F12;
}
public class C2<T2>
where T2 : class?
{
public object? F21;
public object? F22;
}
public object F31;
public object F32;
public object F33;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
System.Object! F31
System.Object! F32
System.Object! F33
Program()
[NullableContext(0)] Program.C0<T0> where T0 : class
T0
System.Object F01
System.Object F02
C0()
[Nullable(0)] Program.C1<T1> where T1 : class!
T1
System.Object! F11
System.Object! F12
C1()
[NullableContext(2)] [Nullable(0)] Program.C2<T2> where T2 : class?
T2
System.Object? F21
System.Object? F22
C2()
";
CompileAndVerify(comp, symbolValidator: module =>
{
AssertNullableAttributes(module, expected);
verifyTypeParameterConstraint("Program.C0", null);
verifyTypeParameterConstraint("Program.C1", false);
verifyTypeParameterConstraint("Program.C2", true);
void verifyTypeParameterConstraint(string typeName, bool? expectedConstraintIsNullable)
{
var typeParameter = module.GlobalNamespace.GetMember<NamedTypeSymbol>(typeName).TypeParameters.Single();
Assert.True(typeParameter.HasReferenceTypeConstraint);
Assert.Equal(expectedConstraintIsNullable, typeParameter.ReferenceTypeConstraintIsNullable);
}
});
}
[Fact]
public void EmitAttribute_ClassConstraint_DifferentFromContext()
{
var source =
@"#nullable enable
public class Program
{
#nullable enable
public class C0<T0>
#nullable disable
where T0 : class
#nullable enable
{
public object F01;
public object F02;
}
public class C1<T1>
where T1 : class
{
public object? F11;
public object? F12;
}
public class C2<T2>
where T2 : class?
{
public object F21;
public object F22;
}
public object F31;
public object F32;
public object F33;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
System.Object! F31
System.Object! F32
System.Object! F33
Program()
[NullableContext(0)] Program.C0<T0> where T0 : class
T0
[Nullable(1)] System.Object! F01
[Nullable(1)] System.Object! F02
C0()
[NullableContext(2)] [Nullable(0)] Program.C1<T1> where T1 : class!
[Nullable(1)] T1
System.Object? F11
System.Object? F12
C1()
[Nullable(0)] Program.C2<T2> where T2 : class?
[Nullable(2)] T2
System.Object! F21
System.Object! F22
C2()
";
CompileAndVerify(comp, symbolValidator: module =>
{
AssertNullableAttributes(module, expected);
verifyTypeParameterConstraint("Program.C0", null);
verifyTypeParameterConstraint("Program.C1", false);
verifyTypeParameterConstraint("Program.C2", true);
void verifyTypeParameterConstraint(string typeName, bool? expectedConstraintIsNullable)
{
var typeParameter = module.GlobalNamespace.GetMember<NamedTypeSymbol>(typeName).TypeParameters.Single();
Assert.True(typeParameter.HasReferenceTypeConstraint);
Assert.Equal(expectedConstraintIsNullable, typeParameter.ReferenceTypeConstraintIsNullable);
}
});
}
[Fact]
public void EmitAttribute_NotNullConstraint()
{
var source =
@"#nullable enable
public class C0<T0>
where T0 : notnull
{
#nullable disable
public object F01;
public object F02;
#nullable enable
}
public class C1<T1>
where T1 : notnull
{
public object F11;
public object F12;
}
public class C2<T2>
where T2 : notnull
{
public object? F21;
public object? F22;
}";
var comp = CreateCompilation(source);
var expected =
@"C0<T0> where T0 : notnull
[Nullable(1)] T0
[NullableContext(1)] [Nullable(0)] C1<T1> where T1 : notnull
T1
System.Object! F11
System.Object! F12
C1()
[NullableContext(2)] [Nullable(0)] C2<T2> where T2 : notnull
[Nullable(1)] T2
System.Object? F21
System.Object? F22
C2()
";
CompileAndVerify(comp, symbolValidator: module =>
{
AssertNullableAttributes(module, expected);
verifyTypeParameterConstraint("C0");
verifyTypeParameterConstraint("C1");
verifyTypeParameterConstraint("C2");
void verifyTypeParameterConstraint(string typeName)
{
var typeParameter = module.GlobalNamespace.GetMember<NamedTypeSymbol>(typeName).TypeParameters.Single();
Assert.True(typeParameter.HasNotNullConstraint);
}
});
}
[Fact]
public void EmitAttribute_ConstraintTypes_01()
{
var source =
@"#nullable enable
public interface IA { }
public interface IB<T> { }
public interface I0<T>
#nullable disable
where T : IA, IB<int>
#nullable enable
{
object F01();
object F02();
}
public interface I1<T>
where T : IA, IB<int>
{
object? F11();
object? F12();
}
public interface I2<T>
where T : IA?, IB<object?>?
{
object F21();
object F22();
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(2)] IB<T>
T
I0<T> where T : IA, IB<System.Int32>
[NullableContext(1)] System.Object! F01()
[NullableContext(1)] System.Object! F02()
[NullableContext(1)] I1<T> where T : IA!, IB<System.Int32>!
[Nullable(0)] T
[NullableContext(2)] System.Object? F11()
[NullableContext(2)] System.Object? F12()
[NullableContext(1)] I2<T> where T : IA?, IB<System.Object?>?
[Nullable(0)] T
System.Object! F21()
System.Object! F22()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ConstraintTypes_02()
{
var source =
@"#nullable enable
public interface IA { }
public interface IB<T> { }
public class Program
{
public static void M0<T>(object x, object y)
#nullable disable
where T : IA, IB<int>
#nullable enable
{
}
public static void M1<T>(object? x, object? y)
where T : IA, IB<int>
{
}
public static void M2<T>(object x, object y)
where T : IA?, IB<object?>?
{
}
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(2)] IB<T>
T
Program
void M0<T>(System.Object! x, System.Object! y) where T : IA, IB<System.Int32>
[Nullable(1)] System.Object! x
[Nullable(1)] System.Object! y
[NullableContext(1)] void M1<T>(System.Object? x, System.Object? y) where T : IA!, IB<System.Int32>!
[Nullable(0)] T
[Nullable(2)] System.Object? x
[Nullable(2)] System.Object? y
[NullableContext(1)] void M2<T>(System.Object! x, System.Object! y) where T : IA?, IB<System.Object?>?
[Nullable(0)] T
System.Object! x
System.Object! y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_MethodReturnType()
{
var source =
@"public class C
{
public object? F() => null;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"C
[NullableContext(2)] System.Object? F()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_MethodParameters()
{
var source =
@"public class A
{
public void F(object?[] c) { }
}
#nullable enable
public class B
{
public void F(object x, object y) { }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"A
void F(System.Object?[] c)
[Nullable({ 0, 2 })] System.Object?[] c
B
[NullableContext(1)] void F(System.Object! x, System.Object! y)
System.Object! x
System.Object! y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ConstructorParameters()
{
var source =
@"public class C
{
public C(object?[] c) { }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"C
C(System.Object?[] c)
[Nullable({ 0, 2 })] System.Object?[] c
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_PropertyType()
{
var source =
@"public class C
{
public object? P => null;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"[NullableContext(2)] [Nullable(0)] C
C()
System.Object? P { get; }
System.Object? P.get
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_PropertyParameters()
{
var source =
@"public class A
{
public object this[object x, object? y] => throw new System.NotImplementedException();
}
#nullable enable
public class B
{
public object this[object x, object y] => throw new System.NotImplementedException();
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"A
System.Object this[System.Object x, System.Object? y] { get; }
[Nullable(2)] System.Object? y
System.Object this[System.Object x, System.Object? y].get
[Nullable(2)] System.Object? y
[NullableContext(1)] [Nullable(0)] B
B()
System.Object! this[System.Object! x, System.Object! y] { get; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Indexers()
{
var source =
@"#nullable enable
public class Program
{
public object this[object? x, object? y] => throw new System.NotImplementedException();
public object this[object? z] { set { } }
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
Program()
System.Object! this[System.Object? x, System.Object? y] { get; }
System.Object? x
System.Object? y
[NullableContext(2)] [Nullable(1)] System.Object! this[System.Object? x, System.Object? y].get
System.Object? x
System.Object? y
System.Object! this[System.Object? z] { set; }
[Nullable(2)] System.Object? z
void this[System.Object? z].set
[Nullable(2)] System.Object? z
System.Object! value
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_OperatorReturnType()
{
var source =
@"public class C
{
public static object? operator+(C a, C b) => null;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"C
[Nullable(2)] System.Object? operator +(C a, C b)
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_OperatorParameters()
{
var source =
@"public class C
{
public static object operator+(C a, object?[] b) => a;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"C
System.Object operator +(C a, System.Object?[] b)
[Nullable({ 0, 2 })] System.Object?[] b
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_DelegateReturnType()
{
var source =
@"public delegate object? D();";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"D
[NullableContext(2)] System.Object? Invoke()
[Nullable(2)] System.Object? EndInvoke(System.IAsyncResult result)
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_DelegateParameters()
{
var source =
@"public delegate void D(object?[] o);";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"D
void Invoke(System.Object?[] o)
[Nullable({ 0, 2 })] System.Object?[] o
System.IAsyncResult BeginInvoke(System.Object?[] o, System.AsyncCallback callback, System.Object @object)
[Nullable({ 0, 2 })] System.Object?[] o
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_NestedEnum()
{
var source =
@"#nullable enable
public class Program
{
public enum E
{
A,
B
}
public object F1;
public object F2;
public object F3;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
System.Object! F1
System.Object! F2
System.Object! F3
Program()
[NullableContext(0)] Program.E
A
B
E()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_LambdaReturnType()
{
var source =
@"delegate T D<T>();
class C
{
static void F<T>(D<T> d)
{
}
static void G(object o)
{
F(() =>
{
if (o != new object()) return o;
return null;
});
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
AssertNoNullableAttributes(comp);
}
[Fact]
public void EmitAttribute_LambdaParameters()
{
var source =
@"delegate void D<T>(T t);
class C
{
static void F<T>(D<T> d)
{
}
static void G()
{
F((object? o) => { });
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
AssertNoNullableAttributes(comp);
}
// See https://github.com/dotnet/roslyn/issues/28862.
[Fact]
public void EmitAttribute_QueryClauseParameters()
{
var source0 =
@"public class A
{
public static object?[] F(object[] x) => x;
}";
var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular8);
var ref0 = comp0.EmitToImageReference();
var source =
@"using System.Linq;
class B
{
static void M(object[] c)
{
var z = from x in A.F(c)
let y = x
where y != null
select y;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { ref0 });
AssertNoNullableAttributes(comp);
}
[Fact]
public void EmitAttribute_LocalFunctionReturnType()
{
var source =
@"class C
{
static void M()
{
object?[] L() => throw new System.NotImplementedException();
L();
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("C").GetMethod("<M>g__L|0_0");
AssertNullableAttribute(method.GetReturnTypeAttributes());
AssertAttributes(method.GetAttributes(), "System.Runtime.CompilerServices.CompilerGeneratedAttribute");
});
}
[Fact]
public void EmitAttribute_LocalFunctionParameters()
{
var source =
@"class C
{
static void M()
{
void L(object? x, object y) { }
L(null, 2);
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("C").GetMethod("<M>g__L|0_0");
AssertNullableAttribute(method.Parameters[0].GetAttributes());
AssertNoNullableAttribute(method.Parameters[1].GetAttributes());
});
}
[Fact]
public void EmitAttribute_ExplicitImplementationForwardingMethod()
{
var source0 =
@"public class A
{
public object? F() => null;
}";
var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular8);
var ref0 = comp0.EmitToImageReference();
var source =
@"interface I
{
object? F();
}
class B : A, I
{
}";
CompileAndVerify(
source,
references: new[] { ref0 },
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("B").GetMethod("I.F");
AssertNullableAttribute(method.GetReturnTypeAttributes());
AssertNoNullableAttribute(method.GetAttributes());
});
}
[Fact]
[WorkItem(30010, "https://github.com/dotnet/roslyn/issues/30010")]
public void EmitAttribute_Iterator_01()
{
var source =
@"using System.Collections.Generic;
class C
{
static IEnumerable<object?> F()
{
yield break;
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var property = module.ContainingAssembly.GetTypeByMetadataName("C").GetTypeMember("<F>d__0").GetProperty("System.Collections.Generic.IEnumerator<System.Object>.Current");
AssertNoNullableAttribute(property.GetAttributes());
var method = property.GetMethod;
AssertNullableAttribute(method.GetReturnTypeAttributes());
AssertAttributes(method.GetAttributes(), "System.Diagnostics.DebuggerHiddenAttribute");
});
}
[Fact]
public void EmitAttribute_Iterator_02()
{
var source =
@"using System.Collections.Generic;
class C
{
static IEnumerable<object?[]> F()
{
yield break;
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var property = module.ContainingAssembly.GetTypeByMetadataName("C").GetTypeMember("<F>d__0").GetProperty("System.Collections.Generic.IEnumerator<System.Object[]>.Current");
AssertNoNullableAttribute(property.GetAttributes());
var method = property.GetMethod;
AssertNullableAttribute(method.GetReturnTypeAttributes());
AssertAttributes(method.GetAttributes(), "System.Diagnostics.DebuggerHiddenAttribute");
});
}
[Fact]
public void EmitAttribute_UnconstrainedTypeParameter()
{
var source =
@"#nullable enable
public class Program
{
public T F1<T>() => default!;
public T? F2<T>() => default;
public T F3<T>() where T : class => default!;
public T? F4<T>() where T : class => default;
public T F5<T>() where T : class? => default!;
public T F6<T>() where T : struct => default;
public T? F7<T>() where T : struct => default;
public T F8<T>() where T : notnull => default;
public T? F9<T>() where T : notnull => default!;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
T F1<T>()
[Nullable(2)] T
[NullableContext(2)] T? F2<T>()
T
T! F3<T>() where T : class!
T
[Nullable(2)] T? F4<T>() where T : class!
T
T F5<T>() where T : class?
[Nullable(2)] T
[NullableContext(0)] T F6<T>() where T : struct
T
[NullableContext(0)] T? F7<T>() where T : struct
T
T F8<T>() where T : notnull
T
[Nullable(2)] T? F9<T>() where T : notnull
T
Program()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Byte0()
{
var source =
@"#nullable enable
public class Program
{
#nullable disable
public object
#nullable enable
F1(object x, object y) => null;
#nullable disable
public object
#nullable enable
F2(object? x, object? y) => null;
}";
var comp = CreateCompilation(source);
var expected =
@"Program
[NullableContext(1)] [Nullable(0)] System.Object F1(System.Object! x, System.Object! y)
System.Object! x
System.Object! y
[NullableContext(2)] [Nullable(0)] System.Object F2(System.Object? x, System.Object? y)
System.Object? x
System.Object? y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitPrivateMetadata_BaseTypes()
{
var source =
@"public class Base<T, U> { }
namespace Namespace
{
public class Public : Base<object, string?> { }
internal class Internal : Base<object, string?> { }
}
public class PublicTypes
{
public class Public : Base<object, string?> { }
internal class Internal : Base<object, string?> { }
protected class Protected : Base<object, string?> { }
protected internal class ProtectedInternal : Base<object, string?> { }
private protected class PrivateProtected : Base<object, string?> { }
private class Private : Base<object, string?> { }
}
internal class InternalTypes
{
public class Public : Base<object, string?> { }
internal class Internal : Base<object, string?> { }
protected class Protected : Base<object, string?> { }
protected internal class ProtectedInternal : Base<object, string?> { }
private protected class PrivateProtected : Base<object, string?> { }
private class Private : Base<object, string?> { }
}";
var expectedPublicOnly = @"
[NullableContext(2)] [Nullable(0)] Base<T, U>
T
U
Base()
PublicTypes
[Nullable({ 0, 1, 2 })] PublicTypes.Public
[Nullable({ 0, 1, 2 })] PublicTypes.Protected
[Nullable({ 0, 1, 2 })] PublicTypes.ProtectedInternal
[Nullable({ 0, 1, 2 })] Namespace.Public
";
var expectedPublicAndInternal = @"
[NullableContext(2)] [Nullable(0)] Base<T, U>
T
U
Base()
PublicTypes
[Nullable({ 0, 1, 2 })] PublicTypes.Public
[Nullable({ 0, 1, 2 })] PublicTypes.Internal
[Nullable({ 0, 1, 2 })] PublicTypes.Protected
[Nullable({ 0, 1, 2 })] PublicTypes.ProtectedInternal
[Nullable({ 0, 1, 2 })] PublicTypes.PrivateProtected
InternalTypes
[Nullable({ 0, 1, 2 })] InternalTypes.Public
[Nullable({ 0, 1, 2 })] InternalTypes.Internal
[Nullable({ 0, 1, 2 })] InternalTypes.Protected
[Nullable({ 0, 1, 2 })] InternalTypes.ProtectedInternal
[Nullable({ 0, 1, 2 })] InternalTypes.PrivateProtected
[Nullable({ 0, 1, 2 })] Namespace.Public
[Nullable({ 0, 1, 2 })] Namespace.Internal
";
var expectedAll = @"
[NullableContext(2)] [Nullable(0)] Base<T, U>
T
U
Base()
PublicTypes
[Nullable({ 0, 1, 2 })] PublicTypes.Public
[Nullable({ 0, 1, 2 })] PublicTypes.Internal
[Nullable({ 0, 1, 2 })] PublicTypes.Protected
[Nullable({ 0, 1, 2 })] PublicTypes.ProtectedInternal
[Nullable({ 0, 1, 2 })] PublicTypes.PrivateProtected
[Nullable({ 0, 1, 2 })] PublicTypes.Private
InternalTypes
[Nullable({ 0, 1, 2 })] InternalTypes.Public
[Nullable({ 0, 1, 2 })] InternalTypes.Internal
[Nullable({ 0, 1, 2 })] InternalTypes.Protected
[Nullable({ 0, 1, 2 })] InternalTypes.ProtectedInternal
[Nullable({ 0, 1, 2 })] InternalTypes.PrivateProtected
[Nullable({ 0, 1, 2 })] InternalTypes.Private
[Nullable({ 0, 1, 2 })] Namespace.Public
[Nullable({ 0, 1, 2 })] Namespace.Internal
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Delegates()
{
var source =
@"public class Program
{
protected delegate object ProtectedDelegate(object? arg);
internal delegate object InternalDelegate(object? arg);
private delegate object PrivateDelegate(object? arg);
}";
var expectedPublicOnly = @"
Program
Program.ProtectedDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
";
var expectedPublicAndInternal = @"
Program
Program.ProtectedDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
Program.InternalDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
";
var expectedAll = @"
Program
Program.ProtectedDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
Program.InternalDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
Program.PrivateDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Events()
{
var source =
@"#nullable disable
public delegate void D<T>(T t);
#nullable enable
public class Program
{
public event D<object?>? PublicEvent { add { } remove { } }
internal event D<object> InternalEvent { add { } remove { } }
protected event D<object?> ProtectedEvent { add { } remove { } }
protected internal event D<object?> ProtectedInternalEvent { add { } remove { } }
private protected event D<object>? PrivateProtectedEvent { add { } remove { } }
private event D<object?>? PrivateEvent { add { } remove { } }
}";
var expectedPublicOnly = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
event D<System.Object?>? PublicEvent
void PublicEvent.add
D<System.Object?>? value
void PublicEvent.remove
D<System.Object?>? value
[Nullable(1)] event D<System.Object!>! InternalEvent
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedEvent
void ProtectedEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedInternalEvent
void ProtectedInternalEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedInternalEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 2, 1 })] event D<System.Object!>? PrivateProtectedEvent
";
var expectedPublicAndInternal = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
event D<System.Object?>? PublicEvent
void PublicEvent.add
D<System.Object?>? value
void PublicEvent.remove
D<System.Object?>? value
[Nullable(1)] event D<System.Object!>! InternalEvent
[NullableContext(1)] void InternalEvent.add
D<System.Object!>! value
[NullableContext(1)] void InternalEvent.remove
D<System.Object!>! value
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedEvent
void ProtectedEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedInternalEvent
void ProtectedInternalEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedInternalEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 2, 1 })] event D<System.Object!>? PrivateProtectedEvent
void PrivateProtectedEvent.add
[Nullable({ 2, 1 })] D<System.Object!>? value
void PrivateProtectedEvent.remove
[Nullable({ 2, 1 })] D<System.Object!>? value
";
var expectedAll = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
event D<System.Object?>? PublicEvent
void PublicEvent.add
D<System.Object?>? value
void PublicEvent.remove
D<System.Object?>? value
[Nullable(1)] event D<System.Object!>! InternalEvent
[NullableContext(1)] void InternalEvent.add
D<System.Object!>! value
[NullableContext(1)] void InternalEvent.remove
D<System.Object!>! value
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedEvent
void ProtectedEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedInternalEvent
void ProtectedInternalEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedInternalEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 2, 1 })] event D<System.Object!>? PrivateProtectedEvent
void PrivateProtectedEvent.add
[Nullable({ 2, 1 })] D<System.Object!>? value
void PrivateProtectedEvent.remove
[Nullable({ 2, 1 })] D<System.Object!>? value
event D<System.Object?>? PrivateEvent
void PrivateEvent.add
D<System.Object?>? value
void PrivateEvent.remove
D<System.Object?>? value
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Fields()
{
var source =
@"public class Program
{
public object PublicField;
internal object? InternalField;
protected object ProtectedField;
protected internal object? ProtectedInternalField;
private protected object? PrivateProtectedField;
private object? PrivateField;
}";
var expectedPublicOnly = @"
[NullableContext(1)] [Nullable(0)] Program
System.Object! PublicField
System.Object! ProtectedField
[Nullable(2)] System.Object? ProtectedInternalField
Program()
";
var expectedPublicAndInternal = @"
[NullableContext(2)] [Nullable(0)] Program
[Nullable(1)] System.Object! PublicField
System.Object? InternalField
[Nullable(1)] System.Object! ProtectedField
System.Object? ProtectedInternalField
System.Object? PrivateProtectedField
Program()
";
var expectedAll = @"
[NullableContext(2)] [Nullable(0)] Program
[Nullable(1)] System.Object! PublicField
System.Object? InternalField
[Nullable(1)] System.Object! ProtectedField
System.Object? ProtectedInternalField
System.Object? PrivateProtectedField
System.Object? PrivateField
Program()
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Methods()
{
var source =
@"public class Program
{
public void PublicMethod(object arg) { }
internal object? InternalMethod(object? arg) => null;
protected object ProtectedMethod(object? arg) => null;
protected internal object? ProtectedInternalMethod(object? arg) => null;
private protected void PrivateProtectedMethod(object? arg) { }
private object? PrivateMethod(object? arg) => null;
}";
var expectedPublicOnly = @"
[NullableContext(1)] [Nullable(0)] Program
void PublicMethod(System.Object! arg)
System.Object! arg
System.Object! ProtectedMethod(System.Object? arg)
[Nullable(2)] System.Object? arg
[NullableContext(2)] System.Object? ProtectedInternalMethod(System.Object? arg)
System.Object? arg
Program()
";
var expectedPublicAndInternal = @"
[NullableContext(2)] [Nullable(0)] Program
[NullableContext(1)] void PublicMethod(System.Object! arg)
System.Object! arg
System.Object? InternalMethod(System.Object? arg)
System.Object? arg
[NullableContext(1)] System.Object! ProtectedMethod(System.Object? arg)
[Nullable(2)] System.Object? arg
System.Object? ProtectedInternalMethod(System.Object? arg)
System.Object? arg
void PrivateProtectedMethod(System.Object? arg)
System.Object? arg
Program()
";
var expectedAll = @"
[NullableContext(2)] [Nullable(0)] Program
[NullableContext(1)] void PublicMethod(System.Object! arg)
System.Object! arg
System.Object? InternalMethod(System.Object? arg)
System.Object? arg
[NullableContext(1)] System.Object! ProtectedMethod(System.Object? arg)
[Nullable(2)] System.Object? arg
System.Object? ProtectedInternalMethod(System.Object? arg)
System.Object? arg
void PrivateProtectedMethod(System.Object? arg)
System.Object? arg
System.Object? PrivateMethod(System.Object? arg)
System.Object? arg
Program()
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Properties()
{
var source =
@"public class Program
{
public object PublicProperty => null;
internal object? InternalProperty => null;
protected object ProtectedProperty => null;
protected internal object? ProtectedInternalProperty => null;
private protected object? PrivateProtectedProperty => null;
private object? PrivateProperty => null;
}";
var expectedPublicOnly = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
[Nullable(1)] System.Object! PublicProperty { get; }
[NullableContext(1)] System.Object! PublicProperty.get
[Nullable(1)] System.Object! ProtectedProperty { get; }
[NullableContext(1)] System.Object! ProtectedProperty.get
System.Object? ProtectedInternalProperty { get; }
System.Object? ProtectedInternalProperty.get
";
var expectedPublicAndInternal = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
[Nullable(1)] System.Object! PublicProperty { get; }
[NullableContext(1)] System.Object! PublicProperty.get
System.Object? InternalProperty { get; }
System.Object? InternalProperty.get
[Nullable(1)] System.Object! ProtectedProperty { get; }
[NullableContext(1)] System.Object! ProtectedProperty.get
System.Object? ProtectedInternalProperty { get; }
System.Object? ProtectedInternalProperty.get
System.Object? PrivateProtectedProperty { get; }
System.Object? PrivateProtectedProperty.get
";
var expectedAll = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
[Nullable(1)] System.Object! PublicProperty { get; }
[NullableContext(1)] System.Object! PublicProperty.get
System.Object? InternalProperty { get; }
System.Object? InternalProperty.get
[Nullable(1)] System.Object! ProtectedProperty { get; }
[NullableContext(1)] System.Object! ProtectedProperty.get
System.Object? ProtectedInternalProperty { get; }
System.Object? ProtectedInternalProperty.get
System.Object? PrivateProtectedProperty { get; }
System.Object? PrivateProtectedProperty.get
System.Object? PrivateProperty { get; }
System.Object? PrivateProperty.get
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Indexers()
{
var source =
@"public class Program
{
public class PublicType
{
public object? this[object? x, object y] => null;
}
internal class InternalType
{
public object this[object x, object y] { get => null; set { } }
}
protected class ProtectedType
{
public object? this[object x, object? y] { get => null; set { } }
}
protected internal class ProtectedInternalType
{
public object this[object x, object y] { set { } }
}
private protected class PrivateProtectedType
{
public object this[object x, object y] => null;
}
private class PrivateType
{
public object this[object x, object y] => null;
}
}";
var expectedPublicOnly = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
[Nullable(0)] Program.PublicType
PublicType()
System.Object? this[System.Object? x, System.Object! y] { get; }
System.Object? x
[Nullable(1)] System.Object! y
System.Object? this[System.Object? x, System.Object! y].get
System.Object? x
[Nullable(1)] System.Object! y
[Nullable(0)] Program.ProtectedType
ProtectedType()
System.Object? this[System.Object! x, System.Object? y] { get; set; }
[Nullable(1)] System.Object! x
System.Object? y
System.Object? this[System.Object! x, System.Object? y].get
[Nullable(1)] System.Object! x
System.Object? y
void this[System.Object! x, System.Object? y].set
[Nullable(1)] System.Object! x
System.Object? y
System.Object? value
[NullableContext(1)] [Nullable(0)] Program.ProtectedInternalType
ProtectedInternalType()
System.Object! this[System.Object! x, System.Object! y] { set; }
System.Object! x
System.Object! y
void this[System.Object! x, System.Object! y].set
System.Object! x
System.Object! y
System.Object! value
";
var expectedPublicAndInternal = @"
[NullableContext(1)] [Nullable(0)] Program
Program()
[NullableContext(2)] [Nullable(0)] Program.PublicType
PublicType()
System.Object? this[System.Object? x, System.Object! y] { get; }
System.Object? x
[Nullable(1)] System.Object! y
System.Object? this[System.Object? x, System.Object! y].get
System.Object? x
[Nullable(1)] System.Object! y
[Nullable(0)] Program.InternalType
InternalType()
System.Object! this[System.Object! x, System.Object! y] { get; set; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
void this[System.Object! x, System.Object! y].set
System.Object! x
System.Object! y
System.Object! value
[NullableContext(2)] [Nullable(0)] Program.ProtectedType
ProtectedType()
System.Object? this[System.Object! x, System.Object? y] { get; set; }
[Nullable(1)] System.Object! x
System.Object? y
System.Object? this[System.Object! x, System.Object? y].get
[Nullable(1)] System.Object! x
System.Object? y
void this[System.Object! x, System.Object? y].set
[Nullable(1)] System.Object! x
System.Object? y
System.Object? value
[Nullable(0)] Program.ProtectedInternalType
ProtectedInternalType()
System.Object! this[System.Object! x, System.Object! y] { set; }
System.Object! x
System.Object! y
void this[System.Object! x, System.Object! y].set
System.Object! x
System.Object! y
System.Object! value
[Nullable(0)] Program.PrivateProtectedType
PrivateProtectedType()
System.Object! this[System.Object! x, System.Object! y] { get; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
";
var expectedAll = @"
[NullableContext(1)] [Nullable(0)] Program
Program()
[NullableContext(2)] [Nullable(0)] Program.PublicType
PublicType()
System.Object? this[System.Object? x, System.Object! y] { get; }
System.Object? x
[Nullable(1)] System.Object! y
System.Object? this[System.Object? x, System.Object! y].get
System.Object? x
[Nullable(1)] System.Object! y
[Nullable(0)] Program.InternalType
InternalType()
System.Object! this[System.Object! x, System.Object! y] { get; set; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
void this[System.Object! x, System.Object! y].set
System.Object! x
System.Object! y
System.Object! value
[NullableContext(2)] [Nullable(0)] Program.ProtectedType
ProtectedType()
System.Object? this[System.Object! x, System.Object? y] { get; set; }
[Nullable(1)] System.Object! x
System.Object? y
System.Object? this[System.Object! x, System.Object? y].get
[Nullable(1)] System.Object! x
System.Object? y
void this[System.Object! x, System.Object? y].set
[Nullable(1)] System.Object! x
System.Object? y
System.Object? value
[Nullable(0)] Program.ProtectedInternalType
ProtectedInternalType()
System.Object! this[System.Object! x, System.Object! y] { set; }
System.Object! x
System.Object! y
void this[System.Object! x, System.Object! y].set
System.Object! x
System.Object! y
System.Object! value
[Nullable(0)] Program.PrivateProtectedType
PrivateProtectedType()
System.Object! this[System.Object! x, System.Object! y] { get; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
[Nullable(0)] Program.PrivateType
PrivateType()
System.Object! this[System.Object! x, System.Object! y] { get; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_TypeParameters()
{
var source =
@"public class Base { }
public class Program
{
protected static void ProtectedMethod<T, U>()
where T : notnull
where U : class
{
}
internal static void InternalMethod<T, U>()
where T : notnull
where U : class
{
}
private static void PrivateMethod<T, U>()
where T : notnull
where U : class
{
}
}";
var expectedPublicOnly = @"
Program
[NullableContext(1)] void ProtectedMethod<T, U>() where T : notnull where U : class!
T
U
";
var expectedPublicAndInternal = @"
[NullableContext(1)] [Nullable(0)] Program
void ProtectedMethod<T, U>() where T : notnull where U : class!
T
U
void InternalMethod<T, U>() where T : notnull where U : class!
T
U
Program()
";
var expectedAll = @"
[NullableContext(1)] [Nullable(0)] Program
void ProtectedMethod<T, U>() where T : notnull where U : class!
T
U
void InternalMethod<T, U>() where T : notnull where U : class!
T
U
void PrivateMethod<T, U>() where T : notnull where U : class!
T
U
Program()
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
[WorkItem(37161, "https://github.com/dotnet/roslyn/issues/37161")]
public void EmitPrivateMetadata_ExplicitImplementation()
{
var source =
@"public interface I<T>
{
T M(T[] args);
T P { get; set; }
T[] this[T index] { get; }
}
public class C : I<object?>
{
object? I<object?>.M(object?[] args) => throw null!;
object? I<object?>.P { get; set; }
object?[] I<object?>.this[object? index] => throw null!;
}";
// Attributes emitted for explicitly-implemented property and indexer, but not for accessors.
var expectedPublicOnly = @"
[NullableContext(1)] I<T>
[Nullable(2)] T
T M(T[]! args)
T[]! args
T P { get; set; }
T P.get
void P.set
T value
T[]! this[T index] { get; }
T index
T[]! this[T index].get
T index
C
[Nullable(2)] System.Object? I<System.Object>.P { get; set; }
[Nullable({ 1, 2 })] System.Object?[]! I<System.Object>.Item[System.Object index] { get; }
";
// Attributes emitted for explicitly-implemented property and indexer, but not for accessors.
var expectedPublicAndInternal = @"
[NullableContext(1)] I<T>
[Nullable(2)] T
T M(T[]! args)
T[]! args
T P { get; set; }
T P.get
void P.set
T value
T[]! this[T index] { get; }
T index
T[]! this[T index].get
T index
C
[Nullable(2)] System.Object? I<System.Object>.P { get; set; }
[Nullable({ 1, 2 })] System.Object?[]! I<System.Object>.Item[System.Object index] { get; }
";
var expectedAll = @"
[NullableContext(1)] I<T>
[Nullable(2)] T
T M(T[]! args)
T[]! args
T P { get; set; }
T P.get
void P.set
T value
T[]! this[T index] { get; }
T index
T[]! this[T index].get
T index
[NullableContext(2)] [Nullable(0)] C
System.Object? <I<System.Object>.P>k__BackingField
System.Object? I<System.Object>.M(System.Object?[]! args)
[Nullable({ 1, 2 })] System.Object?[]! args
[Nullable({ 1, 2 })] System.Object?[]! I<System.Object>.get_Item(System.Object? index)
System.Object? index
C()
System.Object? I<System.Object>.P { get; set; }
System.Object? I<System.Object>.P.get
void I<System.Object>.P.set
System.Object? value
[Nullable({ 1, 2 })] System.Object?[]! I<System.Object>.Item[System.Object? index] { get; }
System.Object? index
[Nullable({ 1, 2 })] System.Object?[]! I<System.Object>.get_Item(System.Object? index)
System.Object? index
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_SynthesizedFields()
{
var source =
@"public struct S<T> { }
public class Public
{
public static void PublicMethod()
{
S<object?> s;
System.Action a = () => { s.ToString(); };
}
}";
var expectedPublicOnly = @"
S<T>
[Nullable(2)] T
";
var expectedPublicAndInternal = @"
S<T>
[Nullable(2)] T
";
var expectedAll = @"
S<T>
[Nullable(2)] T
Public
Public.<>c__DisplayClass0_0
[Nullable({ 0, 2 })] S<System.Object?> s
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_SynthesizedParameters()
{
var source =
@"public class Public
{
private static void PrivateMethod(string x)
{
_ = new System.Action<string?>((string y) => { });
}
}";
var expectedPublicOnly = @"";
var expectedPublicAndInternal = @"";
var expectedAll = @"
Public
[NullableContext(1)] void PrivateMethod(System.String! x)
System.String! x
Public.<>c
[Nullable({ 0, 2 })] System.Action<System.String?> <>9__0_0
[NullableContext(1)] void <PrivateMethod>b__0_0(System.String! y)
System.String! y
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_AnonymousType()
{
var source =
@"public class Program
{
public static void Main()
{
_ = new { A = new object(), B = (string?)null };
}
}";
var expectedPublicOnly = @"";
var expectedPublicAndInternal = @"";
var expectedAll = @"";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Iterator()
{
var source =
@"using System.Collections.Generic;
public class Program
{
public static IEnumerable<object?> F()
{
yield break;
}
}";
var expectedPublicOnly = @"
Program
[Nullable({ 1, 2 })] System.Collections.Generic.IEnumerable<System.Object?>! F()
";
var expectedPublicAndInternal = @"
Program
[Nullable({ 1, 2 })] System.Collections.Generic.IEnumerable<System.Object?>! F()
";
var expectedAll = @"
Program
[Nullable({ 1, 2 })] System.Collections.Generic.IEnumerable<System.Object?>! F()
Program.<F>d__0
[Nullable(2)] System.Object? <>2__current
System.Object System.Collections.Generic.IEnumerator<System.Object>.Current { get; }
[Nullable(2)] System.Object? System.Collections.Generic.IEnumerator<System.Object>.Current.get
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
private void EmitPrivateMetadata(string source, string expectedPublicOnly, string expectedPublicAndInternal, string expectedAll)
{
var sourceIVTs =
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""Other"")]";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
AssertNullableAttributes(CreateCompilation(source, options: options, parseOptions: parseOptions), expectedAll);
AssertNullableAttributes(CreateCompilation(source, options: options, parseOptions: parseOptions.WithFeature("nullablePublicOnly")), expectedPublicOnly);
AssertNullableAttributes(CreateCompilation(new[] { source, sourceIVTs }, options: options, parseOptions: parseOptions), expectedAll);
AssertNullableAttributes(CreateCompilation(new[] { source, sourceIVTs }, options: options, parseOptions: parseOptions.WithFeature("nullablePublicOnly")), expectedPublicAndInternal);
}
/// <summary>
/// Should only require NullableAttribute constructor if nullable annotations are emitted.
/// </summary>
[Fact]
public void EmitPrivateMetadata_MissingAttributeConstructor()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute { }
}";
var source =
@"#pragma warning disable 0067
#pragma warning disable 0169
#pragma warning disable 8321
public class A
{
private object? F;
private static object? M(object arg) => null;
private object? P => null;
private object? this[object x, object? y] => null;
private event D<object?> E;
public static void M()
{
object? f(object arg) => arg;
object? l(object arg) { return arg; }
D<object> d = () => new object();
}
}
internal delegate T D<T>();
internal interface I<T> { }
internal class B : I<object>
{
public static object operator!(B b) => b;
public event D<object?> E;
private (object, object?) F;
}";
var options = WithNullableEnable();
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(new[] { sourceAttribute, source }, options: options, parseOptions: parseOptions);
comp.VerifyEmitDiagnostics(
// (6,21): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? F;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(6, 21),
// (7,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private static object? M(object arg) => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(7, 20),
// (7,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private static object? M(object arg) => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object arg").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(7, 30),
// (8,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? P => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(8, 13),
// (9,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 13),
// (9,26): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 26),
// (9,36): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? y").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 36),
// (10,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private event D<object?> E;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "E").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 30),
// (10,30): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable.
// private event D<object?> E;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(10, 30),
// (13,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// object? f(object arg) => arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(13, 9),
// (13,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// object? f(object arg) => arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object arg").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(13, 19),
// (14,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// object? l(object arg) { return arg; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(14, 9),
// (14,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// object? l(object arg) { return arg; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object arg").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(14, 19),
// (15,26): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// D<object> d = () => new object();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=>").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(15, 26),
// (18,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// internal delegate T D<T>();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(18, 19),
// (18,23): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// internal delegate T D<T>();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(18, 23),
// (19,22): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// internal interface I<T> { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(19, 22),
// (20,16): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// internal class B : I<object>
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "B").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(20, 16),
// (22,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// public static object operator!(B b) => b;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(22, 19),
// (22,36): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// public static object operator!(B b) => b;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "B b").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(22, 36),
// (23,29): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// public event D<object?> E;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "E").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(23, 29),
// (23,29): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable.
// public event D<object?> E;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(23, 29),
// (24,31): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private (object, object?) F;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(24, 31));
comp = CreateCompilation(new[] { sourceAttribute, source }, options: options, parseOptions: parseOptions.WithFeature("nullablePublicOnly"));
comp.VerifyEmitDiagnostics(
// (8,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? P => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(8, 13),
// (9,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 13),
// (9,26): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 26),
// (9,36): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? y").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 36),
// (10,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private event D<object?> E;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "E").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 30),
// (10,30): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable.
// private event D<object?> E;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(10, 30),
// (23,29): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable.
// public event D<object?> E;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(23, 29)
);
}
[Fact]
public void EmitPrivateMetadata_MissingAttributeConstructor_NullableDisabled()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute { }
}";
var source =
@"#pragma warning disable 414
public class Program
{
private object? F = null;
private object? P => null;
}";
var options = TestOptions.ReleaseDll;
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(new[] { sourceAttribute, source }, options: options, parseOptions: parseOptions);
comp.VerifyEmitDiagnostics(
// (4,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// private object? F = null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 19),
// (4,21): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? F = null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(4, 21),
// (5,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? P => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(5, 13),
// (5,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// private object? P => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 19));
comp = CreateCompilation(new[] { sourceAttribute, source }, options: options, parseOptions: parseOptions.WithFeature("nullablePublicOnly"));
comp.VerifyEmitDiagnostics(
// (4,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// private object? F = null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 19),
// (5,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? P => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(5, 13),
// (5,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// private object? P => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 19));
}
[Fact]
public void EmitAttribute_ValueTypes_01()
{
var source =
@"#nullable enable
struct S1<T> { }
struct S2<T, U> { }
class C1<T> { }
class C2<T, U> { }
class Program
{
static void F() { }
int F11;
int? F12;
#nullable disable
object F21;
#nullable enable
object F22;
S1<int> F31;
S1<int?>? F32;
S1<
#nullable disable
object
#nullable enable
> F33;
S1<object?> F34;
S2<int, int> F41;
S2<int,
#nullable disable
object
#nullable enable
> F42;
S2<
#nullable disable
object,
#nullable enable
int> F43;
S2<
#nullable disable
object, object
#nullable enable
> F44;
S2<int, object> F45;
S2<object?, int> F46;
S2<
#nullable disable
object,
#nullable enable
object> F47;
S2<object?,
#nullable disable
object
#nullable enable
> F48;
S2<object, object?> F49;
C1<int
#nullable disable
> F51;
#nullable enable
C1<int?
#nullable disable
> F52;
#nullable enable
C1<int> F53;
C1<int?> F54;
C1<
#nullable disable
object> F55;
#nullable enable
C1<object
#nullable disable
> F56;
#nullable enable
C1<
#nullable disable
object
#nullable enable
>? F57;
C1<object>? F58;
C2<int,
#nullable disable
object> F60;
#nullable enable
C2<int, object
#nullable disable
> F61;
#nullable enable
C2<object?, int
#nullable disable
> F62;
#nullable enable
C2<int, object> F63;
C2<object?, int>? F64;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<MethodSymbol>("Program.F").ReturnTypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "void");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F11").TypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "int");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F12").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { }, "int?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F21").TypeWithAnnotations, new byte[] { 0 }, new byte[] { 0 }, "object");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F22").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "object!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F31").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "S1<int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F32").TypeWithAnnotations, new byte[] { 0, 0, 0, 0 }, new byte[] { 0 }, "S1<int?>?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F33").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "S1<object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F34").TypeWithAnnotations, new byte[] { 0, 2 }, new byte[] { 0, 2 }, "S1<object?>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F41").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0 }, "S2<int, int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F42").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "S2<int, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F43").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "S2<object, int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F44").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0, 0 }, "S2<object, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F45").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 1 }, "S2<int, object!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F46").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2 }, "S2<object?, int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F47").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 1 }, "S2<object, object!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F48").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2, 0 }, "S2<object?, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F49").TypeWithAnnotations, new byte[] { 0, 1, 2 }, new byte[] { 0, 1, 2 }, "S2<object!, object?>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F51").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "C1<int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F52").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0 }, "C1<int?>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F53").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "C1<int>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F54").TypeWithAnnotations, new byte[] { 1, 0, 0 }, new byte[] { 1 }, "C1<int?>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F55").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "C1<object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F56").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "C1<object!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F57").TypeWithAnnotations, new byte[] { 2, 0 }, new byte[] { 2, 0 }, "C1<object>?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F58").TypeWithAnnotations, new byte[] { 2, 1 }, new byte[] { 2, 1 }, "C1<object!>?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F60").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "C2<int, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F61").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 1 }, "C2<int, object!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F62").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2 }, "C2<object?, int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F63").TypeWithAnnotations, new byte[] { 1, 0, 1 }, new byte[] { 1, 1 }, "C2<int, object!>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F64").TypeWithAnnotations, new byte[] { 2, 2, 0 }, new byte[] { 2, 2 }, "C2<object?, int>?");
}
}
[Fact]
public void EmitAttribute_ValueTypes_02()
{
var source =
@"#nullable enable
struct S<T> { }
class Program
{
int
#nullable disable
[] F1;
#nullable enable
int[] F2;
int?[]? F3;
int
#nullable disable
[]
#nullable enable
[] F4;
int?[]
#nullable disable
[] F5;
#nullable enable
S<int
#nullable disable
[]
#nullable enable
> F6;
S<int?[]?>? F7;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "int[]");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "int[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 2, 0, 0 }, new byte[] { 2 }, "int?[]?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 1, 0 }, new byte[] { 0, 1 }, "int[]![]");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0 }, "int?[][]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "S<int[]>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F7").TypeWithAnnotations, new byte[] { 0, 0, 2, 0, 0 }, new byte[] { 0, 2 }, "S<int?[]?>?");
}
}
[Fact]
public void EmitAttribute_ValueTypes_03()
{
var source =
@"#nullable enable
class Program
{
System.ValueTuple F0;
(int, int) F1;
(int?, int?)? F2;
#nullable disable
(int, object) F3;
(object, int) F4;
#nullable enable
(int, object?) F5;
(object, int) F6;
((int, int), ((int, int), int)) F7;
((int, int), ((int, object), int)) F8;
#nullable disable
(int _1, int _2, int _3, int _4, int _5, int _6, int _7, object _8) F9;
#nullable enable
(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9) F10;
(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, object _9) F11;
(int _1, int _2, int _3, int _4, int _5, int _6, int _7, object _8, int _9) F12;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F0").TypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "System.ValueTuple");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0 }, "(int, int)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0 }, new byte[] { 0 }, "(int?, int?)?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "(int, object)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "(object, int)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0, 2 }, new byte[] { 0, 2 }, "(int, object?)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 0, 1, 0 }, new byte[] { 0, 1 }, "(object!, int)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F7").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new byte[] { 0, 0, 0, 0 }, "((int, int), ((int, int), int))");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F8").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 1, 0 }, new byte[] { 0, 0, 0, 0, 1 }, "((int, int), ((int, object!), int))");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F9").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new byte[] { 0, 0, 0 }, "(int _1, int _2, int _3, int _4, int _5, int _6, int _7, object _8)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F10").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new byte[] { 0, 0 }, "(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F11").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, new byte[] { 0, 0, 1 }, "(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, object! _9)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F12").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 }, new byte[] { 0, 0, 1 }, "(int _1, int _2, int _3, int _4, int _5, int _6, int _7, object! _8, int _9)");
}
}
[Fact]
public void EmitAttribute_ValueTypes_04()
{
var source =
@"#nullable enable
struct S0
{
internal struct S { }
internal class C { }
}
struct S1<T>
{
internal struct S { }
internal class C { }
}
class C0
{
internal struct S { }
internal class C { }
}
class C1<T>
{
internal struct S { }
internal class C { }
}
class Program
{
S0.S F11;
#nullable disable
S0.C F12;
#nullable enable
S0.C F13;
S1<int>.S F21;
#nullable disable
S1<int>.C F22;
#nullable enable
S1<int>.C F23;
#nullable disable
S1<object>.S F24;
#nullable enable
S1<object>.S F25;
S1<
#nullable disable
object
#nullable enable
>.C F26;
S1<object
#nullable disable
>.C F27;
#nullable enable
S1<int>.S[] F28;
S1<C1<object>.S> F29;
C0.S F31;
#nullable disable
C0.C F32;
#nullable enable
C0.C F33;
C1<int>.S F41;
#nullable disable
C1<int>.C F42;
#nullable enable
C1<int>.C F43;
#nullable disable
C1<object>.S F44;
#nullable enable
C1<object>.S F45;
C1<
#nullable disable
object
#nullable enable
>.C F46;
C1<object
#nullable disable
>.C F47;
#nullable enable
C1<int>.S[] F48;
C1<S1<object>.S> F49;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F11").TypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "S0.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F12").TypeWithAnnotations, new byte[] { 0 }, new byte[] { 0 }, "S0.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F13").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "S0.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F21").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "S1<int>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F22").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "S1<int>.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F23").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "S1<int>.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F24").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "S1<object>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F25").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "S1<object!>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F26").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1, 0 }, "S1<object>.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F27").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "S1<object!>.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F28").TypeWithAnnotations, new byte[] { 1, 0, 0 }, new byte[] { 1, 0 }, "S1<int>.S[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F29").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 1 }, "S1<C1<object!>.S>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F31").TypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "C0.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F32").TypeWithAnnotations, new byte[] { 0 }, new byte[] { 0 }, "C0.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F33").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "C0.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F41").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "C1<int>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F42").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "C1<int>.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F43").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "C1<int>.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F44").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "C1<object>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F45").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "C1<object!>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F46").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1, 0 }, "C1<object>.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F47").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "C1<object!>.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F48").TypeWithAnnotations, new byte[] { 1, 0, 0 }, new byte[] { 1, 0 }, "C1<int>.S[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F49").TypeWithAnnotations, new byte[] { 1, 0, 1 }, new byte[] { 1, 0, 1 }, "C1<S1<object!>.S>!");
}
}
[Fact]
public void EmitAttribute_ValueTypes_05()
{
var source =
@"#nullable enable
interface I0
{
internal delegate void D();
internal enum E { }
internal interface I { }
}
interface I1<T>
{
internal delegate void D();
internal enum E { }
internal interface I { }
}
class Program
{
I0.D F1;
I0.E F2;
I0.I F3;
I1<int>.D F4;
I1<int>.E F5;
I1<int>.I F6;
#nullable disable
I1<object>.D F7;
I1<object>.E F8;
I1<object>.I F9;
#nullable enable
I1<object>.E F10;
I1<int>.E[] F11;
I1<I0.E> F12;
I1<I1<object>.E>.E F13;
I1<I1<int>.D>.I F14;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "I0.D!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "I0.E");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "I0.I!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "I1<int>.D!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "I1<int>.E");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "I1<int>.I!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F7").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "I1<object>.D");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F8").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "I1<object>.E");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F9").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "I1<object>.I");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F10").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "I1<object!>.E");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F11").TypeWithAnnotations, new byte[] { 1, 0, 0 }, new byte[] { 1, 0 }, "I1<int>.E[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F12").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "I1<I0.E>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F13").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 1 }, "I1<I1<object!>.E>.E");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F14").TypeWithAnnotations, new byte[] { 1, 1, 0 }, new byte[] { 1, 1 }, "I1<I1<int>.D!>.I!");
}
}
[Fact]
public void EmitAttribute_ValueTypes_06()
{
var source =
@"#nullable enable
struct S<T> { }
class C<T> { }
unsafe class Program
{
int* F1;
int?* F2;
S<int*> F3;
S<int>* F4;
#nullable disable
C<int*> F5;
#nullable enable
C<int*> F6;
}";
var comp = CreateCompilation(source);
var globalNamespace = comp.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "int*");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0 }, "int?*");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "S<int*>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "S<int>*");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "C<int*>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 1, 0, 0 }, new byte[] { 1, 0 }, "C<int*>!");
}
[Fact]
public void EmitAttribute_ValueTypes_07()
{
var source =
@"#nullable enable
class C<T> { }
struct S<T> { }
class Program<T, U, V>
where U : class
where V : struct
{
T F11;
T[] F12;
C<T> F13;
S<T> F14;
#nullable disable
U F21;
#nullable enable
U? F22;
U[] F23;
C<U> F24;
S<U> F25;
V F31;
V? F32;
V[] F33;
C<V> F34;
S<V> F35;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F11").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "T");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F12").TypeWithAnnotations, new byte[] { 1, 1 }, new byte[] { 1, 1 }, "T[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F13").TypeWithAnnotations, new byte[] { 1, 1 }, new byte[] { 1, 1 }, "C<T>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F14").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "S<T>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F21").TypeWithAnnotations, new byte[] { 0 }, new byte[] { 0 }, "U");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F22").TypeWithAnnotations, new byte[] { 2 }, new byte[] { 2 }, "U?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F23").TypeWithAnnotations, new byte[] { 1, 1 }, new byte[] { 1, 1 }, "U![]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F24").TypeWithAnnotations, new byte[] { 1, 1 }, new byte[] { 1, 1 }, "C<U!>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F25").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "S<U!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F31").TypeWithAnnotations, new byte[] { 0 }, new byte[] { 0 }, "V");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F32").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "V?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F33").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1, 0 }, "V[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F34").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1, 0 }, "C<V>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F35").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "S<V>");
}
}
[Fact]
public void EmitAttribute_ValueTypes_08()
{
var source0 =
@"public struct S0 { }
public struct S2<T, U> { }";
var comp = CreateCompilation(source0);
var ref0 = comp.EmitToImageReference();
var source1 =
@"#nullable enable
public class C2<T, U> { }
public class Program
{
public C2<S0, object?> F1;
public C2<object, S0>? F2;
public S2<S0, object> F3;
public S2<object?, S0> F4;
public (S0, object) F5;
public (object?, S0) F6;
}";
// With reference assembly.
comp = CreateCompilation(source1, references: new[] { ref0 });
var ref1 = comp.EmitToImageReference();
var globalNamespace = comp.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 1, 0, 2 }, new byte[] { 1, 2 }, "C2<S0, object?>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 2, 1, 0 }, new byte[] { 2, 1 }, "C2<object!, S0>?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 1 }, "S2<S0, object!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2 }, "S2<object?, S0>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 1 }, "(S0, object!)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2 }, "(object?, S0)");
// Without reference assembly.
comp = CreateCompilation(source1);
globalNamespace = comp.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 1, 0, 2 }, new byte[] { 1, 1, 2 }, "C2<S0!, object?>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 2, 1, 0 }, new byte[] { 2, 1, 1 }, "C2<object!, S0!>?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 1, 1, 1 }, "S2<S0!, object!>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 1, 2, 1 }, "S2<object?, S0!>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 1, 1 }, "(S0!, object!)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2, 1 }, "(object?, S0!)");
var source2 =
@"";
// Without reference assembly.
comp = CreateCompilation(source2, references: new[] { ref1 });
globalNamespace = comp.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 1, 0, 2 }, new byte[] { 0, 0, 0 }, "C2<S0, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 2, 1, 0 }, new byte[] { 0, 0, 0 }, "C2<object, S0>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 0 }, "S2<S0, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 0, 0 }, "S2<object, S0>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 0 }, "(S0, object)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 0, 0 }, "(object, S0)");
}
private static readonly SymbolDisplayFormat _displayFormat = SymbolDisplayFormat.TestFormat.
WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.UseSpecialTypes).
WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None);
private static void VerifyBytes(TypeWithAnnotations type, byte[] expectedPreviously, byte[] expectedNow, string expectedDisplay)
{
var builder = ArrayBuilder<byte>.GetInstance();
type.AddNullableTransforms(builder);
var actualBytes = builder.ToImmutableAndFree();
Assert.Equal(expectedNow, actualBytes);
Assert.Equal(expectedDisplay, type.ToDisplayString(_displayFormat));
var underlyingType = type.SetUnknownNullabilityForReferenceTypes();
// Verify re-applying the same bytes gives the same result.
TypeWithAnnotations updated;
int position = 0;
Assert.True(underlyingType.ApplyNullableTransforms(0, actualBytes, ref position, out updated));
Assert.True(updated.Equals(type, TypeCompareKind.ConsiderEverything));
// If the expected byte[] is shorter than earlier builds, verify that
// applying the previous byte[] does not consume all bytes.
if (!expectedPreviously.SequenceEqual(expectedNow))
{
position = 0;
underlyingType.ApplyNullableTransforms(0, ImmutableArray.Create(expectedPreviously), ref position, out _);
Assert.Equal(position, expectedNow.Length);
}
}
[Fact]
public void EmitAttribute_ValueTypes_09()
{
var source1 =
@"#nullable enable
public interface I
{
void M1(int x);
void M2(int[]? x);
void M3(int x, object? y);
}";
var comp = CreateCompilation(source1);
var expected1 =
@"[NullableContext(2)] I
void M1(System.Int32 x)
System.Int32 x
void M2(System.Int32[]? x)
System.Int32[]? x
void M3(System.Int32 x, System.Object? y)
System.Int32 x
System.Object? y
";
AssertNullableAttributes(comp, expected1);
var ref0 = comp.EmitToImageReference();
var source2 =
@"#nullable enable
class C : I
{
public void M1(int x) { }
public void M2(int[]? x) { }
public void M3(int x, object? y) { }
}";
comp = CreateCompilation(source2, references: new[] { ref0 });
comp.VerifyDiagnostics();
}
[Fact]
public void EmitAttribute_ValueTypes_10()
{
var source1 =
@"#nullable enable
public class C<T> { }
public interface I1
{
void M(int x, object? y, object? z);
}
public interface I2
{
void M(C<int>? x, object? y, object? z);
}";
var comp = CreateCompilation(source1);
var expected1 =
@"C<T>
[Nullable(2)] T
[NullableContext(2)] I1
void M(System.Int32 x, System.Object? y, System.Object? z)
System.Int32 x
System.Object? y
System.Object? z
[NullableContext(2)] I2
void M(C<System.Int32>? x, System.Object? y, System.Object? z)
C<System.Int32>? x
System.Object? y
System.Object? z
";
AssertNullableAttributes(comp, expected1);
var ref0 = comp.EmitToImageReference();
var source2 =
@"#nullable enable
class C1 : I1
{
public void M(int x, object? y, object? z) { }
}
class C2 : I2
{
public void M(C<int>? x, object? y, object? z) { }
}";
comp = CreateCompilation(source2, references: new[] { ref0 });
comp.VerifyDiagnostics();
}
[Fact]
public void EmitAttribute_ValueTypes_11()
{
var source1 =
@"#nullable enable
public interface I1<T>
{
void M(T x, object? y, object? z);
}
public interface I2<T> where T : class
{
void M(T? x, object? y, object? z);
}
public interface I3<T> where T : struct
{
void M(T x, object? y, object? z);
}";
var comp = CreateCompilation(source1);
var expected1 =
@"[NullableContext(2)] I1<T>
T
void M(T x, System.Object? y, System.Object? z)
[Nullable(1)] T x
System.Object? y
System.Object? z
[NullableContext(1)] I2<T> where T : class!
T
[NullableContext(2)] void M(T? x, System.Object? y, System.Object? z)
T? x
System.Object? y
System.Object? z
I3<T> where T : struct
[NullableContext(2)] void M(T x, System.Object? y, System.Object? z)
[Nullable(0)] T x
System.Object? y
System.Object? z
";
AssertNullableAttributes(comp, expected1);
var ref0 = comp.EmitToImageReference();
var source2 =
@"#nullable enable
class C1A<T> : I1<T> where T : struct
{
public void M(T x, object? y, object? z) { }
}
class C1B : I1<int>
{
public void M(int x, object? y, object? z) { }
}
class C2A<T> : I2<T> where T : class
{
public void M(T? x, object? y, object? z) { }
}
class C2B : I2<string>
{
public void M(string? x, object? y, object? z) { }
}
class C3A<T> : I3<T> where T : struct
{
public void M(T x, object? y, object? z) { }
}
class C3B : I3<int>
{
public void M(int x, object? y, object? z) { }
}";
comp = CreateCompilation(source2, references: new[] { ref0 });
comp.VerifyDiagnostics();
}
[Fact]
public void UseSiteError_LambdaReturnType()
{
var source0 =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct IntPtr { }
public class MulticastDelegate { }
}";
var comp0 = CreateEmptyCompilation(source0);
var ref0 = comp0.EmitToImageReference();
var source =
@"delegate T D<T>();
class C
{
static void F<T>(D<T> d)
{
}
static void G(object o)
{
F(() =>
{
if (o != new object()) return o;
return null;
});
}
}";
var comp = CreateEmptyCompilation(
source,
references: new[] { ref0 },
parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ModuleMissingAttribute_BaseClass()
{
var source =
@"class A<T>
{
}
class B : A<object?>
{
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,9): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// class A<T>
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 9),
// (4,7): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// class B : A<object?>
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(4, 7));
}
[Fact]
public void ModuleMissingAttribute_Interface()
{
var source =
@"interface I<T>
{
}
class C : I<(object X, object? Y)>
{
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,11): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// interface I<T>
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "I").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(1, 11),
// (1,13): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// interface I<T>
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 13),
// (4,7): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// class C : I<(object X, object? Y)>
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(4, 7));
}
[Fact]
public void ModuleMissingAttribute_MethodReturnType()
{
var source =
@"class C
{
object? F() => null;
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,5): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object? F() => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 5),
// (3,13): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// object? F() => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "F").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(3, 13));
}
[Fact]
public void ModuleMissingAttribute_MethodParameters()
{
var source =
@"class C
{
void F(object?[] c) { }
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,12): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// void F(object?[] c) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?[] c").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 12));
}
[Fact]
public void ModuleMissingAttribute_ConstructorParameters()
{
var source =
@"class C
{
C(object?[] c) { }
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,7): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// C(object?[] c) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?[] c").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 7));
}
[Fact]
public void ModuleMissingAttribute_PropertyType()
{
var source =
@"class C
{
object? P => null;
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,7): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// class C
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(1, 7),
// (3,5): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object? P => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 5));
}
[Fact]
public void ModuleMissingAttribute_PropertyParameters()
{
var source =
@"class C
{
object this[object x, object? y] => throw new System.NotImplementedException();
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,7): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// class C
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(1, 7),
// (3,5): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object this[object x, object? y] => throw new System.NotImplementedException();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 5),
// (3,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object this[object x, object? y] => throw new System.NotImplementedException();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object x").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 17),
// (3,27): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object this[object x, object? y] => throw new System.NotImplementedException();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object? y").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 27));
}
[Fact]
public void ModuleMissingAttribute_OperatorReturnType()
{
var source =
@"class C
{
public static object? operator+(C a, C b) => null;
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object? operator+(C a, C b) => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 19),
// (3,35): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// public static object? operator+(C a, C b) => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "+").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(3, 35),
// (3,37): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object? operator+(C a, C b) => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C a").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 37),
// (3,42): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object? operator+(C a, C b) => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C b").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 42)
);
}
[Fact]
public void ModuleMissingAttribute_OperatorParameters()
{
var source =
@"class C
{
public static object operator+(C a, object?[] b) => a;
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object operator+(C a, object?[] b) => a;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 19),
// (3,34): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// public static object operator+(C a, object?[] b) => a;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "+").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(3, 34),
// (3,36): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object operator+(C a, object?[] b) => a;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C a").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 36),
// (3,41): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object operator+(C a, object?[] b) => a;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?[] b").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 41));
}
[Fact]
public void ModuleMissingAttribute_DelegateReturnType()
{
var source =
@"delegate object? D();";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,10): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// delegate object? D();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 10),
// (1,18): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// delegate object? D();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "D").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(1, 18));
}
[Fact]
public void ModuleMissingAttribute_DelegateParameters()
{
var source =
@"delegate void D(object?[] o);";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// delegate void D(object?[] o);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?[] o").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 17));
}
[Fact]
public void ModuleMissingAttribute_LambdaReturnType()
{
var source =
@"delegate T D<T>();
class C
{
static void F<T>(D<T> d)
{
}
static void G(object o)
{
F(() =>
{
if (o != new object()) return o;
return null;
});
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseModule);
// The lambda signature is emitted without a [Nullable] attribute because
// the return type is inferred from flow analysis, not from initial binding.
// As a result, there is no missing attribute warning.
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ModuleMissingAttribute_LambdaParameters()
{
var source =
@"delegate void D<T>(T t);
class C
{
static void F<T>(D<T> d)
{
}
static void G()
{
F((object? o) => { });
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,15): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// delegate void D<T>(T t);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "D").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(1, 15),
// (1,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// delegate void D<T>(T t);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 17),
// (1,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// delegate void D<T>(T t);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T t").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 20),
// (4,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// static void F<T>(D<T> d)
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "F").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(4, 17),
// (4,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// static void F<T>(D<T> d)
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(4, 19),
// (4,22): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// static void F<T>(D<T> d)
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "D<T> d").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(4, 22),
// (9,12): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// F((object? o) => { });
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object? o").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(9, 12));
}
[Fact]
public void ModuleMissingAttribute_LocalFunctionReturnType()
{
var source =
@"class C
{
static void M()
{
object?[] L() => throw new System.NotImplementedException();
L();
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (5,9): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object?[] L() => throw new System.NotImplementedException();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?[]").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(5, 9));
}
[Fact]
public void ModuleMissingAttribute_LocalFunctionParameters()
{
var source =
@"class C
{
static void M()
{
void L(object? x, object y) { }
L(null, 2);
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (5,16): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// void L(object? x, object y) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object? x").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(5, 16),
// (5,27): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// void L(object? x, object y) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object y").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(5, 27));
}
[Fact]
public void Tuples()
{
var source =
@"public class A
{
public static ((object?, object) _1, object? _2, object _3, ((object?[], object), object?) _4) Nested;
public static (object? _1, object _2, object? _3, object _4, object? _5, object _6, object? _7, object _8, object? _9) Long;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "A");
var fieldDefs = typeDef.GetFields().Select(f => reader.GetFieldDefinition(f)).ToArray();
// Nested tuple
var field = fieldDefs.Single(f => reader.StringComparer.Equals(f.Name, "Nested"));
var customAttributes = field.GetCustomAttributes();
AssertAttributes(reader, customAttributes,
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])",
"MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
var customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
AssertEx.Equal(ImmutableArray.Create<byte>(0, 0, 2, 0, 2, 0, 0, 0, 0, 2, 0, 2), reader.ReadByteArray(customAttribute.Value));
// Long tuple
field = fieldDefs.Single(f => reader.StringComparer.Equals(f.Name, "Long"));
customAttributes = field.GetCustomAttributes();
AssertAttributes(reader, customAttributes,
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])",
"MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
AssertEx.Equal(ImmutableArray.Create<byte>(0, 2, 0, 2, 0, 2, 0, 2, 0, 0, 2), reader.ReadByteArray(customAttribute.Value));
});
var source2 =
@"class B
{
static void Main()
{
A.Nested._1.Item1.ToString(); // 1
A.Nested._1.Item2.ToString();
A.Nested._2.ToString(); // 2
A.Nested._3.ToString();
A.Nested._4.Item1.Item1.ToString();
A.Nested._4.Item1.Item1[0].ToString(); // 3
A.Nested._4.Item1.Item2.ToString();
A.Nested._4.Item2.ToString(); // 4
A.Long._1.ToString(); // 5
A.Long._2.ToString();
A.Long._3.ToString(); // 6
A.Long._4.ToString();
A.Long._5.ToString(); // 7
A.Long._6.ToString();
A.Long._7.ToString(); // 8
A.Long._8.ToString();
A.Long._9.ToString(); // 9
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (5,9): warning CS8602: Dereference of a possibly null reference.
// A.Nested._1.Item1.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Nested._1.Item1").WithLocation(5, 9),
// (7,9): warning CS8602: Dereference of a possibly null reference.
// A.Nested._2.ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Nested._2").WithLocation(7, 9),
// (10,9): warning CS8602: Dereference of a possibly null reference.
// A.Nested._4.Item1.Item1[0].ToString(); // 3
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Nested._4.Item1.Item1[0]").WithLocation(10, 9),
// (12,9): warning CS8602: Dereference of a possibly null reference.
// A.Nested._4.Item2.ToString(); // 4
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Nested._4.Item2").WithLocation(12, 9),
// (13,9): warning CS8602: Dereference of a possibly null reference.
// A.Long._1.ToString(); // 5
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Long._1").WithLocation(13, 9),
// (15,9): warning CS8602: Dereference of a possibly null reference.
// A.Long._3.ToString(); // 6
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Long._3").WithLocation(15, 9),
// (17,9): warning CS8602: Dereference of a possibly null reference.
// A.Long._5.ToString(); // 7
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Long._5").WithLocation(17, 9),
// (19,9): warning CS8602: Dereference of a possibly null reference.
// A.Long._7.ToString(); // 8
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Long._7").WithLocation(19, 9),
// (21,9): warning CS8602: Dereference of a possibly null reference.
// A.Long._9.ToString(); // 9
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Long._9").WithLocation(21, 9));
var type = comp2.GetMember<NamedTypeSymbol>("A");
Assert.Equal(
"((System.Object?, System.Object) _1, System.Object? _2, System.Object _3, ((System.Object?[], System.Object), System.Object?) _4)",
type.GetMember<FieldSymbol>("Nested").TypeWithAnnotations.ToTestDisplayString());
Assert.Equal(
"(System.Object? _1, System.Object _2, System.Object? _3, System.Object _4, System.Object? _5, System.Object _6, System.Object? _7, System.Object _8, System.Object? _9)",
type.GetMember<FieldSymbol>("Long").TypeWithAnnotations.ToTestDisplayString());
}
// DynamicAttribute and NullableAttribute formats should be aligned.
[Fact]
public void TuplesDynamic()
{
var source =
@"#pragma warning disable 0067
using System;
public interface I<T> { }
public class A<T> { }
public class B<T> :
A<(object? _1, (object _2, object? _3), object _4, object? _5, object _6, object? _7, object _8, object? _9)>,
I<(object? _1, (object _2, object? _3), object _4, object? _5, object _6, object? _7, object _8, object? _9)>
where T : A<(object? _1, (object _2, object? _3), object _4, object? _5, object _6, object? _7, object _8, object? _9)>
{
public (dynamic? _1, (object _2, dynamic? _3), object _4, dynamic? _5, object _6, dynamic? _7, object _8, dynamic? _9) Field;
public event EventHandler<(dynamic? _1, (object _2, dynamic? _3), object _4, dynamic? _5, object _6, dynamic? _7, object _8, dynamic? _9)> Event;
public (dynamic? _1, (object _2, dynamic? _3), object _4, dynamic? _5, object _6, dynamic? _7, object _8, dynamic? _9) Method(
(dynamic? _1, (object _2, dynamic? _3), object _4, dynamic? _5, object _6, dynamic? _7, object _8, dynamic? _9) arg) => arg;
public (dynamic? _1, (object _2, dynamic? _3), object _4, dynamic? _5, object _6, dynamic? _7, object _8, dynamic? _9) Property { get; set; }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "B`1");
// Base type
checkAttributesNoDynamic(typeDef.GetCustomAttributes(), addOne: 0); // add one for A<T>
// Interface implementation
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
checkAttributesNoDynamic(interfaceImpl.GetCustomAttributes(), addOne: 0); // add one for I<T>
// Type parameter constraint type
var typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
var constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
checkAttributesNoDynamic(constraint.GetCustomAttributes(), addOne: 1); // add one for A<T>
// Field type
var field = typeDef.GetFields().Select(f => reader.GetFieldDefinition(f)).Single(f => reader.StringComparer.Equals(f.Name, "Field"));
checkAttributes(field.GetCustomAttributes());
// Event type
var @event = typeDef.GetEvents().Select(e => reader.GetEventDefinition(e)).Single(e => reader.StringComparer.Equals(e.Name, "Event"));
checkAttributes(@event.GetCustomAttributes(), addOne: 1); // add one for EventHandler<T>
// Method return type and parameter type
var method = typeDef.GetMethods().Select(m => reader.GetMethodDefinition(m)).Single(m => reader.StringComparer.Equals(m.Name, "Method"));
var parameters = method.GetParameters().Select(p => reader.GetParameter(p)).ToArray();
checkAttributes(parameters[0].GetCustomAttributes()); // return type
checkAttributes(parameters[1].GetCustomAttributes()); // parameter
// Property type
var property = typeDef.GetProperties().Select(p => reader.GetPropertyDefinition(p)).Single(p => reader.StringComparer.Equals(p.Name, "Property"));
checkAttributes(property.GetCustomAttributes());
void checkAttributes(CustomAttributeHandleCollection customAttributes, byte? addOne = null)
{
AssertAttributes(reader, customAttributes,
"MemberReference:Void System.Runtime.CompilerServices.DynamicAttribute..ctor(Boolean[])",
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])",
"MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
checkNullableAttribute(customAttributes, addOne);
}
void checkAttributesNoDynamic(CustomAttributeHandleCollection customAttributes, byte? addOne = null)
{
AssertAttributes(reader, customAttributes,
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])",
"MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
checkNullableAttribute(customAttributes, addOne);
}
void checkNullableAttribute(CustomAttributeHandleCollection customAttributes, byte? addOne)
{
var customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
var expectedBits = ImmutableArray.Create<byte>(0, 2, 0, 1, 2, 1, 2, 1, 2, 1, 0, 2);
if (addOne.HasValue)
{
expectedBits = ImmutableArray.Create(addOne.GetValueOrDefault()).Concat(expectedBits);
}
AssertEx.Equal(expectedBits, reader.ReadByteArray(customAttribute.Value));
}
});
var source2 =
@"class C
{
static void F(B<A<(object?, (object, object?), object, object?, object, object?, object, object?)>> b)
{
b.Field._8.ToString();
b.Field._9.ToString(); // 1
b.Method(default)._8.ToString();
b.Method(default)._9.ToString(); // 2
b.Property._8.ToString();
b.Property._9.ToString(); // 3
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (6,9): warning CS8602: Dereference of a possibly null reference.
// b.Field._9.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Field._9").WithLocation(6, 9),
// (8,9): warning CS8602: Dereference of a possibly null reference.
// b.Method(default)._9.ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Method(default)._9").WithLocation(8, 9),
// (10,9): warning CS8602: Dereference of a possibly null reference.
// b.Property._9.ToString(); // 3
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Property._9").WithLocation(10, 9));
var type = comp2.GetMember<NamedTypeSymbol>("B");
Assert.Equal(
"A<(System.Object? _1, (System.Object _2, System.Object? _3), System.Object _4, System.Object? _5, System.Object _6, System.Object? _7, System.Object _8, System.Object? _9)>",
type.BaseTypeNoUseSiteDiagnostics.ToTestDisplayString());
Assert.Equal(
"I<(System.Object? _1, (System.Object _2, System.Object? _3), System.Object _4, System.Object? _5, System.Object _6, System.Object? _7, System.Object _8, System.Object? _9)>",
type.Interfaces()[0].ToTestDisplayString());
Assert.Equal(
"A<(System.Object? _1, (System.Object _2, System.Object? _3), System.Object _4, System.Object? _5, System.Object _6, System.Object? _7, System.Object _8, System.Object? _9)>",
type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString());
Assert.Equal(
"(dynamic? _1, (System.Object _2, dynamic? _3), System.Object _4, dynamic? _5, System.Object _6, dynamic? _7, System.Object _8, dynamic? _9)",
type.GetMember<FieldSymbol>("Field").TypeWithAnnotations.ToTestDisplayString());
Assert.Equal(
"System.EventHandler<(dynamic? _1, (System.Object _2, dynamic? _3), System.Object _4, dynamic? _5, System.Object _6, dynamic? _7, System.Object _8, dynamic? _9)>",
type.GetMember<EventSymbol>("Event").TypeWithAnnotations.ToTestDisplayString());
Assert.Equal(
"(dynamic? _1, (System.Object _2, dynamic? _3), System.Object _4, dynamic? _5, System.Object _6, dynamic? _7, System.Object _8, dynamic? _9) B<T>.Method((dynamic? _1, (System.Object _2, dynamic? _3), System.Object _4, dynamic? _5, System.Object _6, dynamic? _7, System.Object _8, dynamic? _9) arg)",
type.GetMember<MethodSymbol>("Method").ToTestDisplayString());
Assert.Equal(
"(dynamic? _1, (System.Object _2, dynamic? _3), System.Object _4, dynamic? _5, System.Object _6, dynamic? _7, System.Object _8, dynamic? _9) B<T>.Property { get; set; }",
type.GetMember<PropertySymbol>("Property").ToTestDisplayString());
}
[Fact]
[WorkItem(36934, "https://github.com/dotnet/roslyn/issues/36934")]
public void AttributeUsage()
{
var source =
@"#nullable enable
public class Program
{
public object? F;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NullableAttribute");
AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo();
Assert.False(attributeUsage.Inherited);
Assert.False(attributeUsage.AllowMultiple);
Assert.True(attributeUsage.HasValidAttributeTargets);
var expectedTargets = AttributeTargets.Class | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.GenericParameter | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue;
Assert.Equal(expectedTargets, attributeUsage.ValidTargets);
});
}
[Fact]
public void NullableFlags_Field_Exists()
{
var source =
@"public class C
{
public void F(object? x, object y, object z) { }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
var method = (MethodSymbol)type.GetMembers("F").Single();
var attributes = method.Parameters[0].GetAttributes();
AssertNullableAttribute(attributes);
var nullable = GetNullableAttribute(attributes);
var field = nullable.AttributeClass.GetField("NullableFlags");
Assert.NotNull(field);
Assert.Equal("System.Byte[]", field.TypeWithAnnotations.ToTestDisplayString());
});
}
[Fact]
public void NullableFlags_Field_Contains_ConstructorArguments_SingleByteConstructor()
{
var source =
@"
#nullable enable
using System;
using System.Linq;
public class C
{
public void F(object? x, object y, object z) { }
public static void Main()
{
var attribute = typeof(C).GetMethod(""F"").GetParameters()[0].GetCustomAttributes(true).Single(a => a.GetType().Name == ""NullableAttribute"");
var field = attribute.GetType().GetField(""NullableFlags"");
byte[] flags = (byte[])field.GetValue(attribute);
Console.Write($""{{ {string.Join("","", flags)} }}"");
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "{ 2 }", symbolValidator: module =>
{
var expected =
@"C
[NullableContext(1)] void F(System.Object? x, System.Object! y, System.Object! z)
[Nullable(2)] System.Object? x
System.Object! y
System.Object! z
";
AssertNullableAttributes(module, expected);
});
}
[Fact]
public void NullableFlags_Field_Contains_ConstructorArguments_ByteArrayConstructor()
{
var source =
@"
#nullable enable
using System;
using System.Linq;
public class C
{
public void F(Action<object?, Action<object, object?>?> c) { }
public static void Main()
{
var attribute = typeof(C).GetMethod(""F"").GetParameters()[0].GetCustomAttributes(true).Single(a => a.GetType().Name == ""NullableAttribute"");
var field = attribute.GetType().GetField(""NullableFlags"");
byte[] flags = (byte[])field.GetValue(attribute);
System.Console.Write($""{{ {string.Join("","", flags)} }}"");
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "{ 1,2,2,1,2 }", symbolValidator: module =>
{
var expected =
@"C
void F(System.Action<System.Object?, System.Action<System.Object!, System.Object?>?>! c)
[Nullable({ 1, 2, 2, 1, 2 })] System.Action<System.Object?, System.Action<System.Object!, System.Object?>?>! c
";
AssertNullableAttributes(module, expected);
});
}
[Fact]
[WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")]
public void PropertyAccessorWithNullableContextAttribute_01()
{
var source =
@"#nullable enable
public class A
{
public object? this[object x, object? y] => null;
public static A F(object x) => new A();
public static A F(object x, object? y) => new A();
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] A
A! F(System.Object! x)
System.Object! x
A! F(System.Object! x, System.Object? y)
System.Object! x
[Nullable(2)] System.Object? y
A()
[Nullable(2)] System.Object? this[System.Object! x, System.Object? y] { get; }
[Nullable(1)] System.Object! x
System.Object? y
[NullableContext(2)] System.Object? this[System.Object! x, System.Object? y].get
[Nullable(1)] System.Object! x
System.Object? y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
[WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")]
public void PropertyAccessorWithNullableContextAttribute_02()
{
var source =
@"#nullable enable
public class A
{
public object? this[object x, object? y] { set { } }
public static A F(object x) => new A();
public static A F(object x, object? y) => new A();
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] A
A! F(System.Object! x)
System.Object! x
A! F(System.Object! x, System.Object? y)
System.Object! x
[Nullable(2)] System.Object? y
A()
[Nullable(2)] System.Object? this[System.Object! x, System.Object? y] { set; }
[Nullable(1)] System.Object! x
System.Object? y
[NullableContext(2)] void this[System.Object! x, System.Object? y].set
[Nullable(1)] System.Object! x
System.Object? y
System.Object? value
";
AssertNullableAttributes(comp, expected);
}
[Fact]
[WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")]
public void PropertyAccessorWithNullableContextAttribute_03()
{
var source =
@"#nullable enable
public class A
{
public object this[object? x, object y] => null;
public static A? F0;
public static A? F1;
public static A? F2;
public static A? F3;
public static A? F4;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(2)] [Nullable(0)] A
A? F0
A? F1
A? F2
A? F3
A? F4
A()
[Nullable(1)] System.Object! this[System.Object? x, System.Object! y] { get; }
[Nullable(2)] System.Object? x
System.Object! y
[NullableContext(1)] System.Object! this[System.Object? x, System.Object! y].get
[Nullable(2)] System.Object? x
System.Object! y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
[WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")]
public void PropertyAccessorWithNullableContextAttribute_04()
{
var source =
@"#nullable enable
public class A
{
public object this[object? x, object y] { set { } }
public static A? F0;
public static A? F1;
public static A? F2;
public static A? F3;
public static A? F4;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(2)] [Nullable(0)] A
A? F0
A? F1
A? F2
A? F3
A? F4
A()
[Nullable(1)] System.Object! this[System.Object? x, System.Object! y] { set; }
[Nullable(2)] System.Object? x
System.Object! y
[NullableContext(1)] void this[System.Object? x, System.Object! y].set
[Nullable(2)] System.Object? x
System.Object! y
System.Object! value
";
AssertNullableAttributes(comp, expected);
}
private static void AssertNoNullableAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
AssertAttributes(attributes);
}
private static void AssertNullableAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
AssertAttributes(attributes, "System.Runtime.CompilerServices.NullableAttribute");
}
private static void AssertAttributes(ImmutableArray<CSharpAttributeData> attributes, params string[] expectedNames)
{
var actualNames = attributes.Select(a => a.AttributeClass.ToTestDisplayString()).ToArray();
AssertEx.SetEqual(actualNames, expectedNames);
}
private static void AssertNoNullableAttributes(CSharpCompilation comp)
{
var image = comp.EmitToArray();
using (var reader = new PEReader(image))
{
var metadataReader = reader.GetMetadataReader();
var attributes = metadataReader.GetCustomAttributeRows().Select(metadataReader.GetCustomAttributeName).ToArray();
Assert.False(attributes.Contains("NullableContextAttribute"));
Assert.False(attributes.Contains("NullableAttribute"));
}
}
private static CSharpAttributeData GetNullableAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
return attributes.Single(a => a.AttributeClass.ToTestDisplayString() == "System.Runtime.CompilerServices.NullableAttribute");
}
private static TypeDefinition GetTypeDefinitionByName(MetadataReader reader, string name)
{
return reader.GetTypeDefinition(reader.TypeDefinitions.Single(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name)));
}
private static string GetAttributeConstructorName(MetadataReader reader, CustomAttributeHandle handle)
{
return reader.Dump(reader.GetCustomAttribute(handle).Constructor);
}
private static CustomAttribute GetAttributeByConstructorName(MetadataReader reader, CustomAttributeHandleCollection handles, string name)
{
return reader.GetCustomAttribute(handles.FirstOrDefault(h => GetAttributeConstructorName(reader, h) == name));
}
private static void AssertAttributes(MetadataReader reader, CustomAttributeHandleCollection handles, params string[] expectedNames)
{
var actualNames = handles.Select(h => GetAttributeConstructorName(reader, h)).ToArray();
AssertEx.SetEqual(actualNames, expectedNames);
}
private void AssertNullableAttributes(CSharpCompilation comp, string expected)
{
CompileAndVerify(comp, symbolValidator: module => AssertNullableAttributes(module, expected));
}
private static void AssertNullableAttributes(ModuleSymbol module, string expected)
{
var actual = NullableAttributesVisitor.GetString((PEModuleSymbol)module);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_Nullable : CSharpTestBase
{
// An empty project should not require System.Attribute.
[Fact]
public void EmptyProject_MissingAttribute()
{
var source = "";
var comp = CreateEmptyCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options.
Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1)
);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")]
public void SynthesizeNullableAttributeBasedOnInterfacesToEmit(bool useImageReferences)
{
Func<CSharpCompilation, MetadataReference> getReference = c => useImageReferences ? c.EmitToImageReference() : c.ToMetadataReference();
var lib1_source = @"
using System.Threading.Tasks;
#nullable enable
public interface I2<T, TResult>
{
Task<TResult> ExecuteAsync(T parameter);
}
public interface I1<T> : I2<T, object>
{
}
";
var lib1_comp = CreateCompilation(lib1_source);
lib1_comp.VerifyDiagnostics();
var lib2_source = @"
#nullable disable
public interface I0 : I1<string>
{
}";
var lib2_comp = CreateCompilation(lib2_source, references: new[] { getReference(lib1_comp) });
lib2_comp.VerifyDiagnostics();
var imc1 = (TypeSymbol)lib2_comp.GlobalNamespace.GetMember("I0");
AssertEx.SetEqual(
new[] { "I1<System.String>" },
imc1.InterfacesNoUseSiteDiagnostics().Select(i => i.ToTestDisplayString(includeNonNullable: true)));
AssertEx.SetEqual(
new[] { "I1<System.String>", "I2<System.String, System.Object!>" },
imc1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString(includeNonNullable: true)));
var client_source = @"
public class C
{
public void M(I0 imc)
{
imc.ExecuteAsync("""");
}
}";
var client_comp = CreateCompilation(client_source, references: new[] { getReference(lib1_comp), getReference(lib2_comp) });
client_comp.VerifyDiagnostics();
var imc2 = (TypeSymbol)client_comp.GlobalNamespace.GetMember("I0");
// Note: it is expected that the symbol shows different Interfaces in PE vs. compilation reference
AssertEx.SetEqual(
useImageReferences
? new[] { "I1<System.String>", "I2<System.String, System.Object!>" }
: new[] { "I1<System.String>" },
imc2.InterfacesNoUseSiteDiagnostics().Select(i => i.ToTestDisplayString(includeNonNullable: true)));
AssertEx.SetEqual(
new[] { "I1<System.String>", "I2<System.String, System.Object!>" },
imc2.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString(includeNonNullable: true)));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")]
public void SynthesizeNullableAttributeBasedOnInterfacesToEmit_NotOnAllInterfaces(bool useImageReferences)
{
Func<CSharpCompilation, MetadataReference> getReference = c => useImageReferences ? c.EmitToImageReference() : c.ToMetadataReference();
var lib1_source = @"
#nullable enable
public interface I2<T, TResult>
{
}
public interface I1<T> : I2<T, object>
{
}
";
var lib1_comp = CreateCompilation(lib1_source);
lib1_comp.VerifyDiagnostics();
var lib2_source = @"
#nullable disable
public class C0 : I1<string>
{
}";
var lib2_comp = CreateCompilation(lib2_source, references: new[] { getReference(lib1_comp) });
lib2_comp.VerifyDiagnostics();
var lib2_c0 = (TypeSymbol)lib2_comp.GlobalNamespace.GetMember("C0");
AssertEx.SetEqual(
new[] { "I1<System.String>" },
lib2_c0.InterfacesNoUseSiteDiagnostics().Select(i => i.ToTestDisplayString(includeNonNullable: true)));
AssertEx.SetEqual(
new[] { "I1<System.String>", "I2<System.String, System.Object!>" },
lib2_c0.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString(includeNonNullable: true)));
CompileAndVerify(lib2_comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C0");
var interfaceHandles = typeDef.GetInterfaceImplementations();
var interfaceImpl1 = reader.GetInterfaceImplementation(interfaceHandles.First());
Assert.Equal("TypeSpecification:I1`1{String}", reader.Dump(interfaceImpl1.Interface));
AssertAttributes(reader, interfaceImpl1.GetCustomAttributes());
var interfaceImpl2 = reader.GetInterfaceImplementation(interfaceHandles.Last());
Assert.Equal("TypeSpecification:I2`2{String, Object}", reader.Dump(interfaceImpl2.Interface));
AssertAttributes(reader, interfaceImpl2.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
assertType(reader, exists: true, "NullableAttribute");
});
var lib3_source = @"
#nullable disable
public class C1 : C0
{
}";
var lib3_comp = CreateCompilation(lib3_source, references: new[] { getReference(lib1_comp), getReference(lib2_comp) });
lib3_comp.VerifyDiagnostics();
var lib3_c0 = (TypeSymbol)lib2_comp.GlobalNamespace.GetMember("C0");
AssertEx.SetEqual(
new[] { "I1<System.String>" },
lib3_c0.InterfacesNoUseSiteDiagnostics().Select(i => i.ToTestDisplayString(includeNonNullable: true)));
AssertEx.SetEqual(
new[] { "I1<System.String>", "I2<System.String, System.Object!>" },
lib3_c0.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString(includeNonNullable: true)));
CompileAndVerify(lib3_comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C1");
var interfaceHandles = typeDef.GetInterfaceImplementations();
Assert.True(interfaceHandles.IsEmpty());
assertType(reader, exists: false, "NullableAttribute");
});
void assertType(MetadataReader reader, bool exists, string name)
{
if (exists)
{
_ = reader.TypeDefinitions.Single(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name));
}
else
{
Assert.False(reader.TypeDefinitions.Any(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name)));
}
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")]
public void SynthesizeTupleElementNamesAttributeBasedOnInterfacesToEmit_IndirectInterfaces(bool useImageReferences)
{
Func<CSharpCompilation, MetadataReference> getReference = c => useImageReferences ? c.EmitToImageReference() : c.ToMetadataReference();
var valueTuple_source = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
public override string ToString()
{
return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}';
}
}
}";
var valueTuple_comp = CreateCompilationWithMscorlib40(valueTuple_source);
valueTuple_comp.VerifyDiagnostics();
var tupleElementNamesAttribute_source = @"
namespace System.Runtime.CompilerServices
{
public class TupleElementNamesAttribute : Attribute
{
public TupleElementNamesAttribute(string[] transformNames) { }
}
}";
var tupleElementNamesAttribute_comp = CreateCompilationWithMscorlib40(tupleElementNamesAttribute_source);
tupleElementNamesAttribute_comp.VerifyDiagnostics();
var lib1_source = @"
using System.Threading.Tasks;
public interface I2<T, TResult>
{
Task<TResult> ExecuteAsync(T parameter);
}
public interface I1<T> : I2<T, (object a, object b)>
{
}
";
var lib1_comp = CreateCompilationWithMscorlib40(lib1_source, references: new[] { getReference(valueTuple_comp), getReference(tupleElementNamesAttribute_comp) });
lib1_comp.VerifyDiagnostics();
var lib2_source = @"
public interface I0 : I1<string>
{
}";
var lib2_comp = CreateCompilationWithMscorlib40(lib2_source, references: new[] { getReference(lib1_comp), getReference(valueTuple_comp) }); // missing TupleElementNamesAttribute
lib2_comp.VerifyDiagnostics(
// (2,18): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
// public interface I0 : I1<string>
Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "I0").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(2, 18)
);
lib2_comp.VerifyEmitDiagnostics(
// (2,18): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
// public interface I0 : I1<string>
Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "I0").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(2, 18)
);
var imc1 = (TypeSymbol)lib2_comp.GlobalNamespace.GetMember("I0");
AssertEx.SetEqual(
new[] { "I1<System.String>" },
imc1.InterfacesNoUseSiteDiagnostics().Select(i => i.ToTestDisplayString(includeNonNullable: true)));
AssertEx.SetEqual(
new[] { "I1<System.String>", "I2<System.String, (System.Object a, System.Object b)>" },
imc1.AllInterfacesNoUseSiteDiagnostics.Select(i => i.ToTestDisplayString(includeNonNullable: true)));
}
[Fact, WorkItem(40033, "https://github.com/dotnet/roslyn/issues/40033")]
public void SynthesizeTupleElementNamesAttributeBasedOnInterfacesToEmit_BaseAndDirectInterface()
{
var source = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
public override string ToString()
{
return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}';
}
}
}
namespace System.Runtime.CompilerServices
{
public class TupleElementNamesAttribute : Attribute
{
public TupleElementNamesAttribute() { } // Note: bad signature
}
}
public interface I<T> { }
public class Base<T> { }
public class C1 : I<(object a, object b)> { }
public class C2 : Base<(object a, object b)> { }
";
var comp = CreateCompilationWithMscorlib40(source);
comp.VerifyEmitDiagnostics(
// (34,14): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
// public class C1 : I<(object a, object b)> { }
Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "C1").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(34, 14),
// (34,21): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
// public class C1 : I<(object a, object b)> { }
Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(object a, object b)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(34, 21),
// (36,24): error CS8137: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?
// public class C2 : Base<(object a, object b)> { }
Diagnostic(ErrorCode.ERR_TupleElementNamesAttributeMissing, "(object a, object b)").WithArguments("System.Runtime.CompilerServices.TupleElementNamesAttribute").WithLocation(36, 24)
);
}
[Fact]
public void ExplicitAttributeFromSource()
{
var source =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute
{
public NullableAttribute(byte a) { }
public NullableAttribute(byte[] b) { }
}
}
class C
{
static void F(object? x, object?[] y) { }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ExplicitAttributeFromMetadata()
{
var source0 =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute
{
public NullableAttribute(byte a) { }
public NullableAttribute(byte[] b) { }
}
}";
var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7);
var ref0 = comp0.EmitToImageReference();
var source =
@"class C
{
static void F(object? x, object?[] y) { }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }, parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ExplicitAttribute_MissingSingleByteConstructor()
{
var source =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute
{
public NullableAttribute(byte[] b) { }
}
}
class C
{
static void F(object? x, object?[] y) { }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (5,34): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// public NullableAttribute(byte[] b) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "byte[] b").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(5, 34),
// (10,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 19),
// (10,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?[] y").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 30));
}
[Fact]
public void ExplicitAttribute_MissingConstructor()
{
var source =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute
{
public NullableAttribute() { }
}
}
class C
{
static void F(object? x, object?[] y) { }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (10,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 19),
// (10,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?[] y").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 30));
}
[Fact]
public void ExplicitAttribute_MissingBothNeededConstructors()
{
var source =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute
{
public NullableAttribute(string[] b) { }
}
}
class C
{
static void F(object? x, object?[] y) { }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (5,34): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// public NullableAttribute(string[] b) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "string[] b").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(5, 34),
// (10,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 19),
// (10,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// static void F(object? x, object?[] y) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?[] y").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 30));
}
[Fact]
public void ExplicitAttribute_ReferencedInSource()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal class NullableAttribute : System.Attribute
{
internal NullableAttribute(byte b) { }
}
}";
var source =
@"#pragma warning disable 169
using System.Runtime.CompilerServices;
[assembly: Nullable(0)]
[module: Nullable(0)]
[Nullable(0)]
class Program
{
[Nullable(0)]object F;
[Nullable(0)]static object M1() => throw null;
[return: Nullable(0)]static object M2() => throw null;
static void M3([Nullable(0)]object arg) { }
}";
// C#7
var comp = CreateCompilation(new[] { sourceAttribute, source }, parseOptions: TestOptions.Regular7);
verifyDiagnostics(comp);
// C#8
comp = CreateCompilation(new[] { sourceAttribute, source });
verifyDiagnostics(comp);
static void verifyDiagnostics(CSharpCompilation comp)
{
comp.VerifyDiagnostics(
// (5,2): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed.
// [Nullable(0)]
Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(5, 2),
// (8,6): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed.
// [Nullable(0)]object F;
Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(8, 6),
// (10,14): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed.
// [return: Nullable(0)]static object M2() => throw null;
Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(10, 14),
// (11,21): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed.
// static void M3([Nullable(0)]object arg) { }
Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(11, 21));
}
}
[Fact]
public void AttributeFromInternalsVisibleTo_01()
{
var sourceA =
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""B"")]
#nullable enable
class A
{
object? F = null;
}";
var options = TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All);
var comp = CreateCompilation(sourceA, assemblyName: "A", options: options);
CompileAndVerify(comp, symbolValidator: m => CheckAttribute(m.GlobalNamespace.GetMember("A.F").GetAttributes().Single(), "A"));
var refA = comp.EmitToImageReference();
var sourceB =
@"#nullable enable
class B
{
object? G = new A();
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, assemblyName: "B", options: options);
CompileAndVerify(comp, symbolValidator: m => CheckAttribute(m.GlobalNamespace.GetMember("B.G").GetAttributes().Single(), "B"));
}
[Fact]
public void AttributeFromInternalsVisibleTo_02()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
internal sealed class NullableAttribute : Attribute
{
public NullableAttribute(byte b) { }
public NullableAttribute(byte[] b) { }
}
}";
var sourceA =
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""B"")]
#nullable enable
class A
{
object? F = null;
}";
var options = TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All);
var comp = CreateCompilation(new[] { sourceAttribute, sourceA }, assemblyName: "A", options: options);
CompileAndVerify(comp, symbolValidator: m => CheckAttribute(m.GlobalNamespace.GetMember("A.F").GetAttributes().Single(), "A"));
var refA = comp.EmitToImageReference();
var sourceB =
@"#nullable enable
class B
{
object? G = new A();
}";
comp = CreateCompilation(sourceB, references: new[] { refA }, assemblyName: "B", options: options);
CompileAndVerify(comp, symbolValidator: m => CheckAttribute(m.GlobalNamespace.GetMember("B.G").GetAttributes().Single(), "A"));
}
private static void CheckAttribute(CSharpAttributeData attribute, string assemblyName)
{
var attributeType = attribute.AttributeClass;
Assert.Equal("System.Runtime.CompilerServices", attributeType.ContainingNamespace.QualifiedName);
Assert.Equal("NullableAttribute", attributeType.Name);
Assert.Equal(assemblyName, attributeType.ContainingAssembly.Name);
}
[Fact]
public void NullableAttribute_MissingByte()
{
var source0 =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public class Attribute
{
}
}";
var comp0 = CreateEmptyCompilation(source0, parseOptions: TestOptions.Regular7);
var ref0 = comp0.EmitToImageReference();
var source =
@"class C
{
object? F() => null;
}";
var comp = CreateEmptyCompilation(
source,
references: new[] { ref0 },
parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (3,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// object? F() => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 11),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Byte' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Int32' is not defined or imported
//
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "").WithArguments("System.Int32").WithLocation(1, 1));
}
[Fact]
public void NullableAttribute_MissingAttribute()
{
var source0 =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Byte { }
}";
var comp0 = CreateEmptyCompilation(source0, parseOptions: TestOptions.Regular7);
var ref0 = comp0.EmitToImageReference();
var source =
@"class C
{
object? F() => null;
}";
var comp = CreateEmptyCompilation(
source,
references: new[] { ref0 },
parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (3,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// object? F() => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 11),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0518: Predefined type 'System.Attribute' is not defined or imported
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
}
[Fact]
public void NullableAttribute_StaticAttributeConstructorOnly()
{
var source0 =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct Byte { }
public class Attribute
{
static Attribute() { }
public Attribute(object o) { }
}
}";
var comp0 = CreateEmptyCompilation(source0, parseOptions: TestOptions.Regular7);
var ref0 = comp0.EmitToImageReference();
var source =
@"class C
{
object? F() => null;
}";
var comp = CreateEmptyCompilation(
source,
references: new[] { ref0 },
parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics(
// (3,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// object? F() => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 11),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments
Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1),
// error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments
Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1),
// error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments
Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1),
// error CS1729: 'Attribute' does not contain a constructor that takes 0 arguments
Diagnostic(ErrorCode.ERR_BadCtorArgCount).WithArguments("System.Attribute", "0").WithLocation(1, 1));
}
[Fact]
public void MissingAttributeUsageAttribute()
{
var source =
@"#nullable enable
class Program
{
object? F() => null;
}";
var comp = CreateCompilation(source);
comp.MakeTypeMissing(WellKnownType.System_AttributeUsageAttribute);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
comp = CreateCompilation(source);
comp.MakeMemberMissing(WellKnownMember.System_AttributeUsageAttribute__ctor);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1));
comp = CreateCompilation(source);
comp.MakeMemberMissing(WellKnownMember.System_AttributeUsageAttribute__AllowMultiple);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1));
comp = CreateCompilation(source);
comp.MakeMemberMissing(WellKnownMember.System_AttributeUsageAttribute__Inherited);
comp.VerifyEmitDiagnostics(
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1),
// error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited'
Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1));
}
[Fact]
public void EmitAttribute_NoNullable()
{
var source =
@"public class C
{
public object F = new object();
}";
// C# 7.0: No NullableAttribute.
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
var type = assembly.GetTypeByMetadataName("C");
var field = (FieldSymbol)type.GetMembers("F").Single();
AssertNoNullableAttribute(field.GetAttributes());
AssertNoNullableAttribute(module.GetAttributes());
AssertAttributes(assembly.GetAttributes(),
"System.Runtime.CompilerServices.CompilationRelaxationsAttribute",
"System.Runtime.CompilerServices.RuntimeCompatibilityAttribute",
"System.Diagnostics.DebuggableAttribute");
});
// C# 8.0: NullableAttribute not included if no ? annotation.
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
var type = assembly.GetTypeByMetadataName("C");
var field = (FieldSymbol)type.GetMembers("F").Single();
AssertNoNullableAttribute(field.GetAttributes());
AssertNoNullableAttribute(module.GetAttributes());
AssertAttributes(assembly.GetAttributes(),
"System.Runtime.CompilerServices.CompilationRelaxationsAttribute",
"System.Runtime.CompilerServices.RuntimeCompatibilityAttribute",
"System.Diagnostics.DebuggableAttribute");
});
}
[Fact]
public void EmitAttribute_LocalFunctionConstraints()
{
var source = @"
class C
{
#nullable enable
void M1()
{
local(new C());
void local<T>(T t) where T : C?
{
}
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_OnlyAnnotationsEnabled_LocalFunctionConstraints()
{
var source = @"
class C
{
#nullable enable annotations
void M1()
{
local(new C());
void local<T>(T t) where T : C?
{
}
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_NullableEnabledInProject_LocalFunctionConstraints()
{
var source = @"
class C
{
void M1()
{
local(new C());
void local<T>(T t) where T : C?
{
}
}
}";
var comp = CreateCompilation(new[] { source }, options: WithNullable(NullableContextOptions.Enable), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_OnlyAnnotationsEnabledInProject_LocalFunctionConstraints()
{
var source = @"
class C
{
void M1()
{
local(new C());
void local<T>(T t) where T : C?
{
}
}
}";
var comp = CreateCompilation(new[] { source }, options: WithNullable(NullableContextOptions.Annotations), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_LocalFunctionConstraints_Nested()
{
var source = @"
interface I<T> { }
class C
{
#nullable enable
void M1()
{
void local<T>(T t) where T : I<C?>
{
}
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_LocalFunctionConstraints_NoAnnotation()
{
var source = @"
class C
{
#nullable enable
void M1()
{
local(new C());
void local<T>(T t) where T : C
{
}
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
Assert.NotNull(assembly.GetTypeByMetadataName("System.Runtime.CompilerServices.NullableAttribute"));
});
}
[Fact]
public void EmitAttribute_Module()
{
var source =
@"public class C
{
public object? F = new object();
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var assembly = module.ContainingAssembly;
var type = assembly.GetTypeByMetadataName("C");
var field = (FieldSymbol)type.GetMembers("F").Single();
AssertNullableAttribute(field.GetAttributes());
AssertNoNullableAttribute(module.GetAttributes());
AssertAttributes(assembly.GetAttributes(),
"System.Runtime.CompilerServices.CompilationRelaxationsAttribute",
"System.Runtime.CompilerServices.RuntimeCompatibilityAttribute",
"System.Diagnostics.DebuggableAttribute");
});
}
[Fact]
public void EmitAttribute_NetModule()
{
var source =
@"public class C
{
public object? F = new object();
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public object? F = new object();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "F").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 20));
}
[Fact]
public void EmitAttribute_NetModuleNoDeclarations()
{
var source = "";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseModule);
CompileAndVerify(comp, verify: Verification.Skipped, symbolValidator: module =>
{
AssertAttributes(module.GetAttributes());
});
}
[Fact]
public void EmitAttribute_01()
{
var source =
@"public class Program
{
public object? F;
public object?[]? G;
}";
var comp = CreateCompilation(source, options: WithNullableEnable());
var expected =
@"[NullableContext(2)] [Nullable(0)] Program
System.Object? F
System.Object?[]? G
Program()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_02()
{
var source =
@"public class Program
{
public object? F(object?[]? args) => null;
public object G(object[] args) => null!;
}";
var comp = CreateCompilation(source, options: WithNullableEnable());
var expected =
@"Program
[NullableContext(2)] System.Object? F(System.Object?[]? args)
System.Object?[]? args
[NullableContext(1)] System.Object! G(System.Object![]! args)
System.Object![]! args
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_03()
{
var source =
@"public class Program
{
public static void F(string x, string y, string z) { }
}";
var comp = CreateCompilation(source, options: WithNullableEnable());
var expected =
@"Program
[NullableContext(1)] void F(System.String! x, System.String! y, System.String! z)
System.String! x
System.String! y
System.String! z
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_BaseClass()
{
var source =
@"public class A<T>
{
}
public class B1 : A<object>
{
}
public class B2 : A<object?>
{
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
var expected =
@"A<T>
[Nullable(2)] T
[Nullable({ 0, 1 })] B1
[Nullable({ 0, 2 })] B2
";
AssertNullableAttributes(comp, expected);
var source2 =
@"class C
{
static void F(A<object> x, A<object?> y)
{
}
static void G(B1 x, B2 y)
{
F(x, x);
F(y, y);
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (8,14): warning CS8620: Argument of type 'B1' cannot be used as an input of type 'A<object?>' for parameter 'y' in 'void C.F(A<object> x, A<object?> y)' due to differences in the nullability of reference types.
// F(x, x);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B1", "A<object?>", "y", "void C.F(A<object> x, A<object?> y)").WithLocation(8, 14),
// (9,11): warning CS8620: Argument of type 'B2' cannot be used as an input of type 'A<object>' for parameter 'x' in 'void C.F(A<object> x, A<object?> y)' due to differences in the nullability of reference types.
// F(y, y);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B2", "A<object>", "x", "void C.F(A<object> x, A<object?> y)").WithLocation(9, 11));
}
[Fact]
public void EmitAttribute_Interface_01()
{
var source =
@"public interface I<T>
{
}
public class A : I<object>
{
}
#nullable disable
public class AOblivious : I<object> { }
#nullable enable
public class B : I<object?>
{
}
";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "A");
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
typeDef = GetTypeDefinitionByName(reader, "B");
interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
});
var source2 =
@"class C
{
static void F(I<object> x, I<object?> y) { }
#nullable disable
static void FOblivious(I<object> x) { }
#nullable enable
static void G(A x, B y, AOblivious z)
{
F(x, x);
F(y, y);
F(z, z);
FOblivious(x);
FOblivious(y);
FOblivious(z);
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (9,14): warning CS8620: Argument of type 'A' cannot be used as an input of type 'I<object?>' for parameter 'y' in 'void C.F(I<object> x, I<object?> y)' due to differences in the nullability of reference types.
// F(x, x);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("A", "I<object?>", "y", "void C.F(I<object> x, I<object?> y)").WithLocation(9, 14),
// (10,11): warning CS8620: Argument of type 'B' cannot be used as an input of type 'I<object>' for parameter 'x' in 'void C.F(I<object> x, I<object?> y)' due to differences in the nullability of reference types.
// F(y, y);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B", "I<object>", "x", "void C.F(I<object> x, I<object?> y)").WithLocation(10, 11));
}
[Fact]
public void EmitAttribute_Interface_02()
{
var source =
@"public interface I<T>
{
}
public class A : I<(object X, object Y)>
{
}
public class B : I<(object X, object? Y)>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "A");
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(),
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])");
typeDef = GetTypeDefinitionByName(reader, "B");
interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
AssertAttributes(reader, interfaceImpl.GetCustomAttributes(),
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])",
"MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
});
var source2 =
@"class C
{
static void F(I<(object, object)> a, I<(object, object?)> b)
{
}
static void G(A a, B b)
{
F(a, a);
F(b, b);
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (9,11): warning CS8620: Argument of type 'B' cannot be used as an input of type 'I<(object, object)>' for parameter 'a' in 'void C.F(I<(object, object)> a, I<(object, object?)> b)' due to differences in the nullability of reference types.
// F(b, b);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b").WithArguments("B", "I<(object, object)>", "a", "void C.F(I<(object, object)> a, I<(object, object?)> b)").WithLocation(9, 11));
var type = comp2.GetMember<NamedTypeSymbol>("A");
Assert.Equal("I<(System.Object X, System.Object Y)>", type.Interfaces()[0].ToTestDisplayString());
type = comp2.GetMember<NamedTypeSymbol>("B");
Assert.Equal("I<(System.Object X, System.Object? Y)>", type.Interfaces()[0].ToTestDisplayString());
}
[Fact]
public void EmitAttribute_ImplementedInterfaces_01()
{
var source =
@"#nullable enable
public interface I<T> { }
public class A :
I<object>,
I<string?>
{
public object FA1;
public object FA2;
}
public class B :
#nullable disable
I<object>,
#nullable enable
I<int>
{
public object FB1;
public object FB2;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(2)] I<T>
T
[NullableContext(1)] [Nullable(0)] A
System.Object! FA1
System.Object! FA2
A()
B
[Nullable(1)] System.Object! FB1
[Nullable(1)] System.Object! FB2
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ImplementedInterfaces_02()
{
var source =
@"#nullable enable
public interface IA { }
public interface IB<T> : IA { }
public interface IC<T> : IB<
#nullable disable
object
#nullable enable
>
{
}
public class C : IC<
#nullable disable
string
#nullable enable
>
{
public object F1;
public object F2;
public object F3;
}";
var comp = CreateCompilation(source);
var expected =
@"IB<T>
[Nullable(2)] T
IC<T>
[Nullable(2)] T
C
[Nullable(1)] System.Object! F1
[Nullable(1)] System.Object! F2
[Nullable(1)] System.Object! F3
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_TypeParameters()
{
var source =
@"#nullable enable
public interface I<T, U, V>
where U : class
where V : struct
{
T F1();
U F2();
U? F3();
V F4();
V? F5();
#nullable disable
T F6();
U F7();
U? F8();
V F9();
V? F10();
}";
var comp = CreateCompilation(source);
var expected =
@"I<T, U, V> where U : class! where V : struct
[Nullable(2)] T
[Nullable(1)] U
[NullableContext(1)] T F1()
[NullableContext(1)] U! F2()
[NullableContext(2)] U? F3()
[NullableContext(2)] U? F8()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Constraint_Nullable()
{
var source =
@"public class A
{
}
public class C<T> where T : A?
{
}
public class D<T> where T : A
{
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C`1");
var typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
var constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte)");
typeDef = GetTypeDefinitionByName(reader, "D`1");
typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte)");
});
var source2 =
@"class B : A { }
class Program
{
static void Main()
{
new C<A?>();
new C<A>();
new C<B?>();
new C<B>();
new D<A?>(); // warning
new D<A>();
new D<B?>(); // warning
new D<B>();
}
}";
var comp2 = CreateCompilation(new[] { source, source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp2.VerifyEmitDiagnostics(
// (10,15): warning CS8627: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'.
// new D<A?>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A?").WithArguments("D<T>", "A", "T", "A?").WithLocation(10, 15),
// (12,15): warning CS8627: The type 'B?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'B?' doesn't match constraint type 'A'.
// new D<B?>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "B?").WithArguments("D<T>", "A", "T", "B?").WithLocation(12, 15));
comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyEmitDiagnostics(
// (10,15): warning CS8627: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'.
// new D<A?>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A?").WithArguments("D<T>", "A", "T", "A?").WithLocation(10, 15),
// (12,15): warning CS8627: The type 'B?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'B?' doesn't match constraint type 'A'.
// new D<B?>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "B?").WithArguments("D<T>", "A", "T", "B?").WithLocation(12, 15));
var type = comp2.GetMember<NamedTypeSymbol>("C");
Assert.Equal("A?", type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
type = comp2.GetMember<NamedTypeSymbol>("D");
Assert.Equal("A!", type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
}
// https://github.com/dotnet/roslyn/issues/29976: Test with [NonNullTypes].
[Fact]
public void EmitAttribute_Constraint_Oblivious()
{
var source =
@"public class A<T>
{
}
public class C<T> where T : A<object>
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C`1");
var typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
var constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes());
});
var source2 =
@"class B1 : A<object?> { }
class B2 : A<object> { }
class Program
{
static void Main()
{
new C<A<object?>>();
new C<A<object>>();
new C<A<object?>?>();
new C<A<object>?>();
new C<B1>();
new C<B2>();
new C<B1?>();
new C<B2?>();
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics();
var type = comp2.GetMember<NamedTypeSymbol>("C");
Assert.Equal("A<System.Object>", type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
}
[WorkItem(27742, "https://github.com/dotnet/roslyn/issues/27742")]
[Fact]
public void EmitAttribute_Constraint_Nested()
{
var source =
@"public class A<T>
{
}
public class B<T> where T : A<object?>
{
}
public class C<T> where T : A<object>
{
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "B`1");
var typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
var constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
typeDef = GetTypeDefinitionByName(reader, "C`1");
typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte)");
});
var source2 =
@"class Program
{
static void Main()
{
new B<A<object?>>();
new B<A<object>>(); // warning
new C<A<object?>>(); // warning
new C<A<object>>();
}
}";
var comp2 = CreateCompilation(new[] { source, source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
comp2.VerifyEmitDiagnostics(
// (6,15): warning CS8627: The type 'A<object>' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. Nullability of type argument 'A<object>' doesn't match constraint type 'A<object?>'.
// new B<A<object>>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<object>").WithArguments("B<T>", "A<object?>", "T", "A<object>").WithLocation(6, 15),
// (7,15): warning CS8627: The type 'A<object?>' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'A<object?>' doesn't match constraint type 'A<object>'.
// new C<A<object?>>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<object?>").WithArguments("C<T>", "A<object>", "T", "A<object?>").WithLocation(7, 15));
comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (6,15): warning CS8627: The type 'A<object>' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. Nullability of type argument 'A<object>' doesn't match constraint type 'A<object?>'.
// new B<A<object>>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<object>").WithArguments("B<T>", "A<object?>", "T", "A<object>").WithLocation(6, 15),
// (7,15): warning CS8627: The type 'A<object?>' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'A<object?>' doesn't match constraint type 'A<object>'.
// new C<A<object?>>(); // warning
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<object?>").WithArguments("C<T>", "A<object>", "T", "A<object?>").WithLocation(7, 15));
var type = comp2.GetMember<NamedTypeSymbol>("B");
Assert.Equal("A<System.Object?>!", type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
type = comp2.GetMember<NamedTypeSymbol>("C");
Assert.Equal("A<System.Object!>!", type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
}
[Fact]
public void EmitAttribute_Constraint_TypeParameter()
{
var source =
@"public class C<T, U>
where T : class
where U : T?
{
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "C`2");
var typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[1]);
var constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
AssertAttributes(reader, constraint.GetCustomAttributes(), "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte)");
});
var source2 =
@"class Program
{
static void Main()
{
new C<object?, string?>();
new C<object?, string>();
new C<object, string?>();
new C<object, string>();
}
}";
var comp2 = CreateCompilation(new[] { source, source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
var expected = new[] {
// (5,15): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T, U>'. Nullability of type argument 'object?' doesn't match 'class' constraint.
// new C<object?, string?>();
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T, U>", "T", "object?").WithLocation(5, 15),
// (6,15): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T, U>'. Nullability of type argument 'object?' doesn't match 'class' constraint.
// new C<object?, string>();
Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T, U>", "T", "object?").WithLocation(6, 15)
};
comp2.VerifyEmitDiagnostics(expected);
comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyEmitDiagnostics(expected);
var type = comp2.GetMember<NamedTypeSymbol>("C");
Assert.Equal("T?", type.TypeParameters[1].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true));
}
[Fact]
public void EmitAttribute_Constraints()
{
var source =
@"#nullable enable
public abstract class Program
{
#nullable disable
public abstract void M0<T1, T2, T3, T4>()
where T1 : class
where T2 : class
where T3 : class
#nullable enable
where T4 : class?;
public abstract void M1<T1, T2, T3, T4>()
where T1 : class
where T2 : class
where T3 : class
#nullable disable
where T4 : class;
#nullable enable
public abstract void M2<T1, T2, T3, T4>()
where T1 : class?
where T2 : class?
where T3 : class?
where T4 : class;
private object _f1;
private object _f2;
private object _f3;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
[NullableContext(0)] void M0<T1, T2, T3, T4>() where T1 : class where T2 : class where T3 : class where T4 : class?
T1
T2
T3
[Nullable(2)] T4
void M1<T1, T2, T3, T4>() where T1 : class! where T2 : class! where T3 : class! where T4 : class
T1
T2
T3
[Nullable(0)] T4
[NullableContext(2)] void M2<T1, T2, T3, T4>() where T1 : class? where T2 : class? where T3 : class? where T4 : class!
T1
T2
T3
[Nullable(1)] T4
Program()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ClassConstraint_SameAsContext()
{
var source =
@"#nullable enable
public class Program
{
public class C0<T0>
#nullable disable
where T0 : class
#nullable enable
{
#nullable disable
public object F01;
public object F02;
#nullable enable
}
public class C1<T1>
where T1 : class
{
public object F11;
public object F12;
}
public class C2<T2>
where T2 : class?
{
public object? F21;
public object? F22;
}
public object F31;
public object F32;
public object F33;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
System.Object! F31
System.Object! F32
System.Object! F33
Program()
[NullableContext(0)] Program.C0<T0> where T0 : class
T0
System.Object F01
System.Object F02
C0()
[Nullable(0)] Program.C1<T1> where T1 : class!
T1
System.Object! F11
System.Object! F12
C1()
[NullableContext(2)] [Nullable(0)] Program.C2<T2> where T2 : class?
T2
System.Object? F21
System.Object? F22
C2()
";
CompileAndVerify(comp, symbolValidator: module =>
{
AssertNullableAttributes(module, expected);
verifyTypeParameterConstraint("Program.C0", null);
verifyTypeParameterConstraint("Program.C1", false);
verifyTypeParameterConstraint("Program.C2", true);
void verifyTypeParameterConstraint(string typeName, bool? expectedConstraintIsNullable)
{
var typeParameter = module.GlobalNamespace.GetMember<NamedTypeSymbol>(typeName).TypeParameters.Single();
Assert.True(typeParameter.HasReferenceTypeConstraint);
Assert.Equal(expectedConstraintIsNullable, typeParameter.ReferenceTypeConstraintIsNullable);
}
});
}
[Fact]
public void EmitAttribute_ClassConstraint_DifferentFromContext()
{
var source =
@"#nullable enable
public class Program
{
#nullable enable
public class C0<T0>
#nullable disable
where T0 : class
#nullable enable
{
public object F01;
public object F02;
}
public class C1<T1>
where T1 : class
{
public object? F11;
public object? F12;
}
public class C2<T2>
where T2 : class?
{
public object F21;
public object F22;
}
public object F31;
public object F32;
public object F33;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
System.Object! F31
System.Object! F32
System.Object! F33
Program()
[NullableContext(0)] Program.C0<T0> where T0 : class
T0
[Nullable(1)] System.Object! F01
[Nullable(1)] System.Object! F02
C0()
[NullableContext(2)] [Nullable(0)] Program.C1<T1> where T1 : class!
[Nullable(1)] T1
System.Object? F11
System.Object? F12
C1()
[Nullable(0)] Program.C2<T2> where T2 : class?
[Nullable(2)] T2
System.Object! F21
System.Object! F22
C2()
";
CompileAndVerify(comp, symbolValidator: module =>
{
AssertNullableAttributes(module, expected);
verifyTypeParameterConstraint("Program.C0", null);
verifyTypeParameterConstraint("Program.C1", false);
verifyTypeParameterConstraint("Program.C2", true);
void verifyTypeParameterConstraint(string typeName, bool? expectedConstraintIsNullable)
{
var typeParameter = module.GlobalNamespace.GetMember<NamedTypeSymbol>(typeName).TypeParameters.Single();
Assert.True(typeParameter.HasReferenceTypeConstraint);
Assert.Equal(expectedConstraintIsNullable, typeParameter.ReferenceTypeConstraintIsNullable);
}
});
}
[Fact]
public void EmitAttribute_NotNullConstraint()
{
var source =
@"#nullable enable
public class C0<T0>
where T0 : notnull
{
#nullable disable
public object F01;
public object F02;
#nullable enable
}
public class C1<T1>
where T1 : notnull
{
public object F11;
public object F12;
}
public class C2<T2>
where T2 : notnull
{
public object? F21;
public object? F22;
}";
var comp = CreateCompilation(source);
var expected =
@"C0<T0> where T0 : notnull
[Nullable(1)] T0
[NullableContext(1)] [Nullable(0)] C1<T1> where T1 : notnull
T1
System.Object! F11
System.Object! F12
C1()
[NullableContext(2)] [Nullable(0)] C2<T2> where T2 : notnull
[Nullable(1)] T2
System.Object? F21
System.Object? F22
C2()
";
CompileAndVerify(comp, symbolValidator: module =>
{
AssertNullableAttributes(module, expected);
verifyTypeParameterConstraint("C0");
verifyTypeParameterConstraint("C1");
verifyTypeParameterConstraint("C2");
void verifyTypeParameterConstraint(string typeName)
{
var typeParameter = module.GlobalNamespace.GetMember<NamedTypeSymbol>(typeName).TypeParameters.Single();
Assert.True(typeParameter.HasNotNullConstraint);
}
});
}
[Fact]
public void EmitAttribute_ConstraintTypes_01()
{
var source =
@"#nullable enable
public interface IA { }
public interface IB<T> { }
public interface I0<T>
#nullable disable
where T : IA, IB<int>
#nullable enable
{
object F01();
object F02();
}
public interface I1<T>
where T : IA, IB<int>
{
object? F11();
object? F12();
}
public interface I2<T>
where T : IA?, IB<object?>?
{
object F21();
object F22();
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(2)] IB<T>
T
I0<T> where T : IA, IB<System.Int32>
[NullableContext(1)] System.Object! F01()
[NullableContext(1)] System.Object! F02()
[NullableContext(1)] I1<T> where T : IA!, IB<System.Int32>!
[Nullable(0)] T
[NullableContext(2)] System.Object? F11()
[NullableContext(2)] System.Object? F12()
[NullableContext(1)] I2<T> where T : IA?, IB<System.Object?>?
[Nullable(0)] T
System.Object! F21()
System.Object! F22()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ConstraintTypes_02()
{
var source =
@"#nullable enable
public interface IA { }
public interface IB<T> { }
public class Program
{
public static void M0<T>(object x, object y)
#nullable disable
where T : IA, IB<int>
#nullable enable
{
}
public static void M1<T>(object? x, object? y)
where T : IA, IB<int>
{
}
public static void M2<T>(object x, object y)
where T : IA?, IB<object?>?
{
}
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(2)] IB<T>
T
Program
void M0<T>(System.Object! x, System.Object! y) where T : IA, IB<System.Int32>
[Nullable(1)] System.Object! x
[Nullable(1)] System.Object! y
[NullableContext(1)] void M1<T>(System.Object? x, System.Object? y) where T : IA!, IB<System.Int32>!
[Nullable(0)] T
[Nullable(2)] System.Object? x
[Nullable(2)] System.Object? y
[NullableContext(1)] void M2<T>(System.Object! x, System.Object! y) where T : IA?, IB<System.Object?>?
[Nullable(0)] T
System.Object! x
System.Object! y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_MethodReturnType()
{
var source =
@"public class C
{
public object? F() => null;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"C
[NullableContext(2)] System.Object? F()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_MethodParameters()
{
var source =
@"public class A
{
public void F(object?[] c) { }
}
#nullable enable
public class B
{
public void F(object x, object y) { }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"A
void F(System.Object?[] c)
[Nullable({ 0, 2 })] System.Object?[] c
B
[NullableContext(1)] void F(System.Object! x, System.Object! y)
System.Object! x
System.Object! y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_ConstructorParameters()
{
var source =
@"public class C
{
public C(object?[] c) { }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"C
C(System.Object?[] c)
[Nullable({ 0, 2 })] System.Object?[] c
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_PropertyType()
{
var source =
@"public class C
{
public object? P => null;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"[NullableContext(2)] [Nullable(0)] C
C()
System.Object? P { get; }
System.Object? P.get
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_PropertyParameters()
{
var source =
@"public class A
{
public object this[object x, object? y] => throw new System.NotImplementedException();
}
#nullable enable
public class B
{
public object this[object x, object y] => throw new System.NotImplementedException();
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"A
System.Object this[System.Object x, System.Object? y] { get; }
[Nullable(2)] System.Object? y
System.Object this[System.Object x, System.Object? y].get
[Nullable(2)] System.Object? y
[NullableContext(1)] [Nullable(0)] B
B()
System.Object! this[System.Object! x, System.Object! y] { get; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Indexers()
{
var source =
@"#nullable enable
public class Program
{
public object this[object? x, object? y] => throw new System.NotImplementedException();
public object this[object? z] { set { } }
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
Program()
System.Object! this[System.Object? x, System.Object? y] { get; }
System.Object? x
System.Object? y
[NullableContext(2)] [Nullable(1)] System.Object! this[System.Object? x, System.Object? y].get
System.Object? x
System.Object? y
System.Object! this[System.Object? z] { set; }
[Nullable(2)] System.Object? z
void this[System.Object? z].set
[Nullable(2)] System.Object? z
System.Object! value
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_OperatorReturnType()
{
var source =
@"public class C
{
public static object? operator+(C a, C b) => null;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"C
[Nullable(2)] System.Object? operator +(C a, C b)
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_OperatorParameters()
{
var source =
@"public class C
{
public static object operator+(C a, object?[] b) => a;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"C
System.Object operator +(C a, System.Object?[] b)
[Nullable({ 0, 2 })] System.Object?[] b
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_DelegateReturnType()
{
var source =
@"public delegate object? D();";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"D
[NullableContext(2)] System.Object? Invoke()
[Nullable(2)] System.Object? EndInvoke(System.IAsyncResult result)
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_DelegateParameters()
{
var source =
@"public delegate void D(object?[] o);";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
var expected =
@"D
void Invoke(System.Object?[] o)
[Nullable({ 0, 2 })] System.Object?[] o
System.IAsyncResult BeginInvoke(System.Object?[] o, System.AsyncCallback callback, System.Object @object)
[Nullable({ 0, 2 })] System.Object?[] o
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_NestedEnum()
{
var source =
@"#nullable enable
public class Program
{
public enum E
{
A,
B
}
public object F1;
public object F2;
public object F3;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
System.Object! F1
System.Object! F2
System.Object! F3
Program()
[NullableContext(0)] Program.E
A
B
E()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_LambdaReturnType_01()
{
var source =
@"delegate T D<T>();
class C
{
static void F<T>(D<T> d)
{
}
static void G(object o)
{
F(() =>
{
if (o != new object()) return o;
return null;
});
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
AssertNoNullableAttributes(comp);
}
[Fact]
public void EmitAttribute_LambdaReturnType_02()
{
var source =
@"delegate T D<T>();
class C
{
static void F<T>(D<T> d)
{
}
static void Main()
{
F(string?[] () => null);
}
}";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("C+<>c").GetMethod("<Main>b__1_0");
AssertAttributes(method.GetAttributes());
AssertNullableAttribute(method.GetReturnTypeAttributes());
});
}
[Fact]
public void EmitAttribute_LambdaParameters_01()
{
var source =
@"delegate void D<T>(T t);
class C
{
static void F<T>(D<T> d)
{
}
static void G()
{
F((object? o) => { });
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("C+<>c").GetMethod("<G>b__1_0");
AssertAttributes(method.GetAttributes(), "System.Runtime.CompilerServices.NullableContextAttribute");
AssertAttributes(method.Parameters[0].GetAttributes());
});
}
[Fact]
public void EmitAttribute_LambdaParameters_02()
{
var source =
@"delegate void D<T, U>(T t, U u);
class C
{
static void F<T, U>(D<T, U> d)
{
}
static void G()
{
F((object x, string? y) => { });
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("C+<>c").GetMethod("<G>b__1_0");
AssertAttributes(method.GetReturnTypeAttributes());
AssertAttributes(method.Parameters[0].GetAttributes());
AssertNullableAttribute(method.Parameters[1].GetAttributes());
});
}
// See https://github.com/dotnet/roslyn/issues/28862.
[Fact]
public void EmitAttribute_QueryClauseParameters()
{
var source0 =
@"public class A
{
public static object?[] F(object[] x) => x;
}";
var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular8);
var ref0 = comp0.EmitToImageReference();
var source =
@"using System.Linq;
class B
{
static void M(object[] c)
{
var z = from x in A.F(c)
let y = x
where y != null
select y;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, references: new[] { ref0 });
AssertNoNullableAttributes(comp);
}
[Fact]
public void EmitAttribute_LocalFunctionReturnType()
{
var source =
@"class C
{
static void M()
{
object?[] L() => throw new System.NotImplementedException();
L();
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("C").GetMethod("<M>g__L|0_0");
AssertNullableAttribute(method.GetReturnTypeAttributes());
AssertAttributes(method.GetAttributes(), "System.Runtime.CompilerServices.CompilerGeneratedAttribute");
});
}
[Fact]
public void EmitAttribute_LocalFunctionParameters()
{
var source =
@"class C
{
static void M()
{
void L(object? x, object y) { }
L(null, 2);
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("C").GetMethod("<M>g__L|0_0");
AssertNullableAttribute(method.Parameters[0].GetAttributes());
AssertNoNullableAttribute(method.Parameters[1].GetAttributes());
});
}
[WorkItem(36736, "https://github.com/dotnet/roslyn/issues/36736")]
[Fact]
public void EmitAttribute_Lambda_NetModule()
{
var source =
@"class Program
{
static void Main()
{
#nullable enable
var a1 = (object x) => { };
a1(1);
var a2 = string?[] () => null!;
a2();
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseModule);
// https://github.com/dotnet/roslyn/issues/36736: Not reporting missing NullableContextAttribute.
comp.VerifyDiagnostics(
// (6,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// var a1 = (object x) => { };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object x").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(6, 19),
// (8,31): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// var a2 = string?[] () => null!;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "=>").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(8, 31));
}
[WorkItem(36736, "https://github.com/dotnet/roslyn/issues/36736")]
[Fact]
public void EmitAttribute_LocalFunction_NetModule()
{
var source =
@"class Program
{
static void Main()
{
#nullable enable
void L1(object? x) { }
L1(null);
string[]? L2() => null;
L2();
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseModule);
// https://github.com/dotnet/roslyn/issues/36736: Not reporting missing NullableContextAttribute.
comp.VerifyDiagnostics(
// (6,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// void L1(object? x) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object? x").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(6, 17),
// (8,9): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// string[]? L2() => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "string[]?").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(8, 9));
}
[Fact]
public void EmitAttribute_Lambda_MissingNullableAttributeConstructor()
{
var sourceA =
@"namespace System.Runtime.CompilerServices
{
public class NullableAttribute : Attribute
{
private NullableAttribute() { }
}
}";
var sourceB =
@"class Program
{
static void Main()
{
#nullable enable
var a1 = (object x) => { };
a1(1);
var a2 = string?[] () => null!;
a2();
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB });
comp.VerifyDiagnostics(
// (6,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// var a1 = (object x) => { };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(6, 19),
// (8,31): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// var a2 = string?[] () => null!;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=>").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(8, 31));
}
[Fact]
public void EmitAttribute_LocalFunction_MissingNullableAttributeConstructor()
{
var sourceA =
@"namespace System.Runtime.CompilerServices
{
public class NullableAttribute : Attribute
{
private NullableAttribute() { }
}
}";
var sourceB =
@"class Program
{
static void Main()
{
#nullable enable
void L1(object? x) { }
L1(null);
string[]? L2() => null;
L2();
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB });
comp.VerifyDiagnostics(
// (6,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// void L1(object? x) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(6, 17),
// (8,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// string[]? L2() => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "string[]?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(8, 9));
}
[WorkItem(36736, "https://github.com/dotnet/roslyn/issues/36736")]
[Fact]
public void EmitAttribute_Lambda_MissingNullableContextAttributeConstructor()
{
var sourceA =
@"namespace System.Runtime.CompilerServices
{
public class NullableContextAttribute : Attribute
{
private NullableContextAttribute() { }
}
}";
var sourceB =
@"class Program
{
static void Main()
{
#nullable enable
var a1 = (object x) => { };
a1(1);
var a2 = string?[] () => null!;
a2();
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB });
// https://github.com/dotnet/roslyn/issues/36736: Not reporting missing NullableContextAttribute constructor.
comp.VerifyEmitDiagnostics();
}
[WorkItem(36736, "https://github.com/dotnet/roslyn/issues/36736")]
[Fact]
public void EmitAttribute_LocalFunction_MissingNullableContextAttributeConstructor()
{
var sourceA =
@"namespace System.Runtime.CompilerServices
{
public class NullableContextAttribute : Attribute
{
private NullableContextAttribute() { }
}
}";
var sourceB =
@"class Program
{
static void Main()
{
#nullable enable
void L1(object? x) { }
L1(null);
string[]? L2() => null;
L2();
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB });
// https://github.com/dotnet/roslyn/issues/36736: Not reporting missing NullableContextAttribute constructor.
comp.VerifyEmitDiagnostics();
}
[Fact]
public void EmitAttribute_ExplicitImplementationForwardingMethod()
{
var source0 =
@"public class A
{
public object? F() => null;
}";
var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular8);
var ref0 = comp0.EmitToImageReference();
var source =
@"interface I
{
object? F();
}
class B : A, I
{
}";
CompileAndVerify(
source,
references: new[] { ref0 },
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("B").GetMethod("I.F");
AssertNullableAttribute(method.GetReturnTypeAttributes());
AssertNoNullableAttribute(method.GetAttributes());
});
}
[Fact]
[WorkItem(30010, "https://github.com/dotnet/roslyn/issues/30010")]
public void EmitAttribute_Iterator_01()
{
var source =
@"using System.Collections.Generic;
class C
{
static IEnumerable<object?> F()
{
yield break;
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var property = module.ContainingAssembly.GetTypeByMetadataName("C").GetTypeMember("<F>d__0").GetProperty("System.Collections.Generic.IEnumerator<System.Object>.Current");
AssertNoNullableAttribute(property.GetAttributes());
var method = property.GetMethod;
AssertNullableAttribute(method.GetReturnTypeAttributes());
AssertAttributes(method.GetAttributes(), "System.Diagnostics.DebuggerHiddenAttribute");
});
}
[Fact]
public void EmitAttribute_Iterator_02()
{
var source =
@"using System.Collections.Generic;
class C
{
static IEnumerable<object?[]> F()
{
yield break;
}
}";
CompileAndVerify(
source,
parseOptions: TestOptions.Regular8,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var property = module.ContainingAssembly.GetTypeByMetadataName("C").GetTypeMember("<F>d__0").GetProperty("System.Collections.Generic.IEnumerator<System.Object[]>.Current");
AssertNoNullableAttribute(property.GetAttributes());
var method = property.GetMethod;
AssertNullableAttribute(method.GetReturnTypeAttributes());
AssertAttributes(method.GetAttributes(), "System.Diagnostics.DebuggerHiddenAttribute");
});
}
[Fact]
public void EmitAttribute_UnconstrainedTypeParameter()
{
var source =
@"#nullable enable
public class Program
{
public T F1<T>() => default!;
public T? F2<T>() => default;
public T F3<T>() where T : class => default!;
public T? F4<T>() where T : class => default;
public T F5<T>() where T : class? => default!;
public T F6<T>() where T : struct => default;
public T? F7<T>() where T : struct => default;
public T F8<T>() where T : notnull => default;
public T? F9<T>() where T : notnull => default!;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
var expected =
@"[NullableContext(1)] [Nullable(0)] Program
T F1<T>()
[Nullable(2)] T
[NullableContext(2)] T? F2<T>()
T
T! F3<T>() where T : class!
T
[Nullable(2)] T? F4<T>() where T : class!
T
T F5<T>() where T : class?
[Nullable(2)] T
[NullableContext(0)] T F6<T>() where T : struct
T
[NullableContext(0)] T? F7<T>() where T : struct
T
T F8<T>() where T : notnull
T
[Nullable(2)] T? F9<T>() where T : notnull
T
Program()
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitAttribute_Byte0()
{
var source =
@"#nullable enable
public class Program
{
#nullable disable
public object
#nullable enable
F1(object x, object y) => null;
#nullable disable
public object
#nullable enable
F2(object? x, object? y) => null;
}";
var comp = CreateCompilation(source);
var expected =
@"Program
[NullableContext(1)] [Nullable(0)] System.Object F1(System.Object! x, System.Object! y)
System.Object! x
System.Object! y
[NullableContext(2)] [Nullable(0)] System.Object F2(System.Object? x, System.Object? y)
System.Object? x
System.Object? y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
public void EmitPrivateMetadata_BaseTypes()
{
var source =
@"public class Base<T, U> { }
namespace Namespace
{
public class Public : Base<object, string?> { }
internal class Internal : Base<object, string?> { }
}
public class PublicTypes
{
public class Public : Base<object, string?> { }
internal class Internal : Base<object, string?> { }
protected class Protected : Base<object, string?> { }
protected internal class ProtectedInternal : Base<object, string?> { }
private protected class PrivateProtected : Base<object, string?> { }
private class Private : Base<object, string?> { }
}
internal class InternalTypes
{
public class Public : Base<object, string?> { }
internal class Internal : Base<object, string?> { }
protected class Protected : Base<object, string?> { }
protected internal class ProtectedInternal : Base<object, string?> { }
private protected class PrivateProtected : Base<object, string?> { }
private class Private : Base<object, string?> { }
}";
var expectedPublicOnly = @"
[NullableContext(2)] [Nullable(0)] Base<T, U>
T
U
Base()
PublicTypes
[Nullable({ 0, 1, 2 })] PublicTypes.Public
[Nullable({ 0, 1, 2 })] PublicTypes.Protected
[Nullable({ 0, 1, 2 })] PublicTypes.ProtectedInternal
[Nullable({ 0, 1, 2 })] Namespace.Public
";
var expectedPublicAndInternal = @"
[NullableContext(2)] [Nullable(0)] Base<T, U>
T
U
Base()
PublicTypes
[Nullable({ 0, 1, 2 })] PublicTypes.Public
[Nullable({ 0, 1, 2 })] PublicTypes.Internal
[Nullable({ 0, 1, 2 })] PublicTypes.Protected
[Nullable({ 0, 1, 2 })] PublicTypes.ProtectedInternal
[Nullable({ 0, 1, 2 })] PublicTypes.PrivateProtected
InternalTypes
[Nullable({ 0, 1, 2 })] InternalTypes.Public
[Nullable({ 0, 1, 2 })] InternalTypes.Internal
[Nullable({ 0, 1, 2 })] InternalTypes.Protected
[Nullable({ 0, 1, 2 })] InternalTypes.ProtectedInternal
[Nullable({ 0, 1, 2 })] InternalTypes.PrivateProtected
[Nullable({ 0, 1, 2 })] Namespace.Public
[Nullable({ 0, 1, 2 })] Namespace.Internal
";
var expectedAll = @"
[NullableContext(2)] [Nullable(0)] Base<T, U>
T
U
Base()
PublicTypes
[Nullable({ 0, 1, 2 })] PublicTypes.Public
[Nullable({ 0, 1, 2 })] PublicTypes.Internal
[Nullable({ 0, 1, 2 })] PublicTypes.Protected
[Nullable({ 0, 1, 2 })] PublicTypes.ProtectedInternal
[Nullable({ 0, 1, 2 })] PublicTypes.PrivateProtected
[Nullable({ 0, 1, 2 })] PublicTypes.Private
InternalTypes
[Nullable({ 0, 1, 2 })] InternalTypes.Public
[Nullable({ 0, 1, 2 })] InternalTypes.Internal
[Nullable({ 0, 1, 2 })] InternalTypes.Protected
[Nullable({ 0, 1, 2 })] InternalTypes.ProtectedInternal
[Nullable({ 0, 1, 2 })] InternalTypes.PrivateProtected
[Nullable({ 0, 1, 2 })] InternalTypes.Private
[Nullable({ 0, 1, 2 })] Namespace.Public
[Nullable({ 0, 1, 2 })] Namespace.Internal
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Delegates()
{
var source =
@"public class Program
{
protected delegate object ProtectedDelegate(object? arg);
internal delegate object InternalDelegate(object? arg);
private delegate object PrivateDelegate(object? arg);
}";
var expectedPublicOnly = @"
Program
Program.ProtectedDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
";
var expectedPublicAndInternal = @"
Program
Program.ProtectedDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
Program.InternalDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
";
var expectedAll = @"
Program
Program.ProtectedDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
Program.InternalDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
Program.PrivateDelegate
[NullableContext(1)] System.Object! Invoke(System.Object? arg)
[Nullable(2)] System.Object? arg
System.IAsyncResult BeginInvoke(System.Object? arg, System.AsyncCallback callback, System.Object @object)
[Nullable(2)] System.Object? arg
[Nullable(1)] System.Object! EndInvoke(System.IAsyncResult result)
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Events()
{
var source =
@"#nullable disable
public delegate void D<T>(T t);
#nullable enable
public class Program
{
public event D<object?>? PublicEvent { add { } remove { } }
internal event D<object> InternalEvent { add { } remove { } }
protected event D<object?> ProtectedEvent { add { } remove { } }
protected internal event D<object?> ProtectedInternalEvent { add { } remove { } }
private protected event D<object>? PrivateProtectedEvent { add { } remove { } }
private event D<object?>? PrivateEvent { add { } remove { } }
}";
var expectedPublicOnly = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
event D<System.Object?>? PublicEvent
void PublicEvent.add
D<System.Object?>? value
void PublicEvent.remove
D<System.Object?>? value
[Nullable(1)] event D<System.Object!>! InternalEvent
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedEvent
void ProtectedEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedInternalEvent
void ProtectedInternalEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedInternalEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 2, 1 })] event D<System.Object!>? PrivateProtectedEvent
";
var expectedPublicAndInternal = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
event D<System.Object?>? PublicEvent
void PublicEvent.add
D<System.Object?>? value
void PublicEvent.remove
D<System.Object?>? value
[Nullable(1)] event D<System.Object!>! InternalEvent
[NullableContext(1)] void InternalEvent.add
D<System.Object!>! value
[NullableContext(1)] void InternalEvent.remove
D<System.Object!>! value
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedEvent
void ProtectedEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedInternalEvent
void ProtectedInternalEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedInternalEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 2, 1 })] event D<System.Object!>? PrivateProtectedEvent
void PrivateProtectedEvent.add
[Nullable({ 2, 1 })] D<System.Object!>? value
void PrivateProtectedEvent.remove
[Nullable({ 2, 1 })] D<System.Object!>? value
";
var expectedAll = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
event D<System.Object?>? PublicEvent
void PublicEvent.add
D<System.Object?>? value
void PublicEvent.remove
D<System.Object?>? value
[Nullable(1)] event D<System.Object!>! InternalEvent
[NullableContext(1)] void InternalEvent.add
D<System.Object!>! value
[NullableContext(1)] void InternalEvent.remove
D<System.Object!>! value
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedEvent
void ProtectedEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 1, 2 })] event D<System.Object?>! ProtectedInternalEvent
void ProtectedInternalEvent.add
[Nullable({ 1, 2 })] D<System.Object?>! value
void ProtectedInternalEvent.remove
[Nullable({ 1, 2 })] D<System.Object?>! value
[Nullable({ 2, 1 })] event D<System.Object!>? PrivateProtectedEvent
void PrivateProtectedEvent.add
[Nullable({ 2, 1 })] D<System.Object!>? value
void PrivateProtectedEvent.remove
[Nullable({ 2, 1 })] D<System.Object!>? value
event D<System.Object?>? PrivateEvent
void PrivateEvent.add
D<System.Object?>? value
void PrivateEvent.remove
D<System.Object?>? value
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Fields()
{
var source =
@"public class Program
{
public object PublicField;
internal object? InternalField;
protected object ProtectedField;
protected internal object? ProtectedInternalField;
private protected object? PrivateProtectedField;
private object? PrivateField;
}";
var expectedPublicOnly = @"
[NullableContext(1)] [Nullable(0)] Program
System.Object! PublicField
System.Object! ProtectedField
[Nullable(2)] System.Object? ProtectedInternalField
Program()
";
var expectedPublicAndInternal = @"
[NullableContext(2)] [Nullable(0)] Program
[Nullable(1)] System.Object! PublicField
System.Object? InternalField
[Nullable(1)] System.Object! ProtectedField
System.Object? ProtectedInternalField
System.Object? PrivateProtectedField
Program()
";
var expectedAll = @"
[NullableContext(2)] [Nullable(0)] Program
[Nullable(1)] System.Object! PublicField
System.Object? InternalField
[Nullable(1)] System.Object! ProtectedField
System.Object? ProtectedInternalField
System.Object? PrivateProtectedField
System.Object? PrivateField
Program()
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Methods()
{
var source =
@"public class Program
{
public void PublicMethod(object arg) { }
internal object? InternalMethod(object? arg) => null;
protected object ProtectedMethod(object? arg) => null;
protected internal object? ProtectedInternalMethod(object? arg) => null;
private protected void PrivateProtectedMethod(object? arg) { }
private object? PrivateMethod(object? arg) => null;
}";
var expectedPublicOnly = @"
[NullableContext(1)] [Nullable(0)] Program
void PublicMethod(System.Object! arg)
System.Object! arg
System.Object! ProtectedMethod(System.Object? arg)
[Nullable(2)] System.Object? arg
[NullableContext(2)] System.Object? ProtectedInternalMethod(System.Object? arg)
System.Object? arg
Program()
";
var expectedPublicAndInternal = @"
[NullableContext(2)] [Nullable(0)] Program
[NullableContext(1)] void PublicMethod(System.Object! arg)
System.Object! arg
System.Object? InternalMethod(System.Object? arg)
System.Object? arg
[NullableContext(1)] System.Object! ProtectedMethod(System.Object? arg)
[Nullable(2)] System.Object? arg
System.Object? ProtectedInternalMethod(System.Object? arg)
System.Object? arg
void PrivateProtectedMethod(System.Object? arg)
System.Object? arg
Program()
";
var expectedAll = @"
[NullableContext(2)] [Nullable(0)] Program
[NullableContext(1)] void PublicMethod(System.Object! arg)
System.Object! arg
System.Object? InternalMethod(System.Object? arg)
System.Object? arg
[NullableContext(1)] System.Object! ProtectedMethod(System.Object? arg)
[Nullable(2)] System.Object? arg
System.Object? ProtectedInternalMethod(System.Object? arg)
System.Object? arg
void PrivateProtectedMethod(System.Object? arg)
System.Object? arg
System.Object? PrivateMethod(System.Object? arg)
System.Object? arg
Program()
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Properties()
{
var source =
@"public class Program
{
public object PublicProperty => null;
internal object? InternalProperty => null;
protected object ProtectedProperty => null;
protected internal object? ProtectedInternalProperty => null;
private protected object? PrivateProtectedProperty => null;
private object? PrivateProperty => null;
}";
var expectedPublicOnly = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
[Nullable(1)] System.Object! PublicProperty { get; }
[NullableContext(1)] System.Object! PublicProperty.get
[Nullable(1)] System.Object! ProtectedProperty { get; }
[NullableContext(1)] System.Object! ProtectedProperty.get
System.Object? ProtectedInternalProperty { get; }
System.Object? ProtectedInternalProperty.get
";
var expectedPublicAndInternal = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
[Nullable(1)] System.Object! PublicProperty { get; }
[NullableContext(1)] System.Object! PublicProperty.get
System.Object? InternalProperty { get; }
System.Object? InternalProperty.get
[Nullable(1)] System.Object! ProtectedProperty { get; }
[NullableContext(1)] System.Object! ProtectedProperty.get
System.Object? ProtectedInternalProperty { get; }
System.Object? ProtectedInternalProperty.get
System.Object? PrivateProtectedProperty { get; }
System.Object? PrivateProtectedProperty.get
";
var expectedAll = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
[Nullable(1)] System.Object! PublicProperty { get; }
[NullableContext(1)] System.Object! PublicProperty.get
System.Object? InternalProperty { get; }
System.Object? InternalProperty.get
[Nullable(1)] System.Object! ProtectedProperty { get; }
[NullableContext(1)] System.Object! ProtectedProperty.get
System.Object? ProtectedInternalProperty { get; }
System.Object? ProtectedInternalProperty.get
System.Object? PrivateProtectedProperty { get; }
System.Object? PrivateProtectedProperty.get
System.Object? PrivateProperty { get; }
System.Object? PrivateProperty.get
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Indexers()
{
var source =
@"public class Program
{
public class PublicType
{
public object? this[object? x, object y] => null;
}
internal class InternalType
{
public object this[object x, object y] { get => null; set { } }
}
protected class ProtectedType
{
public object? this[object x, object? y] { get => null; set { } }
}
protected internal class ProtectedInternalType
{
public object this[object x, object y] { set { } }
}
private protected class PrivateProtectedType
{
public object this[object x, object y] => null;
}
private class PrivateType
{
public object this[object x, object y] => null;
}
}";
var expectedPublicOnly = @"
[NullableContext(2)] [Nullable(0)] Program
Program()
[Nullable(0)] Program.PublicType
PublicType()
System.Object? this[System.Object? x, System.Object! y] { get; }
System.Object? x
[Nullable(1)] System.Object! y
System.Object? this[System.Object? x, System.Object! y].get
System.Object? x
[Nullable(1)] System.Object! y
[Nullable(0)] Program.ProtectedType
ProtectedType()
System.Object? this[System.Object! x, System.Object? y] { get; set; }
[Nullable(1)] System.Object! x
System.Object? y
System.Object? this[System.Object! x, System.Object? y].get
[Nullable(1)] System.Object! x
System.Object? y
void this[System.Object! x, System.Object? y].set
[Nullable(1)] System.Object! x
System.Object? y
System.Object? value
[NullableContext(1)] [Nullable(0)] Program.ProtectedInternalType
ProtectedInternalType()
System.Object! this[System.Object! x, System.Object! y] { set; }
System.Object! x
System.Object! y
void this[System.Object! x, System.Object! y].set
System.Object! x
System.Object! y
System.Object! value
";
var expectedPublicAndInternal = @"
[NullableContext(1)] [Nullable(0)] Program
Program()
[NullableContext(2)] [Nullable(0)] Program.PublicType
PublicType()
System.Object? this[System.Object? x, System.Object! y] { get; }
System.Object? x
[Nullable(1)] System.Object! y
System.Object? this[System.Object? x, System.Object! y].get
System.Object? x
[Nullable(1)] System.Object! y
[Nullable(0)] Program.InternalType
InternalType()
System.Object! this[System.Object! x, System.Object! y] { get; set; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
void this[System.Object! x, System.Object! y].set
System.Object! x
System.Object! y
System.Object! value
[NullableContext(2)] [Nullable(0)] Program.ProtectedType
ProtectedType()
System.Object? this[System.Object! x, System.Object? y] { get; set; }
[Nullable(1)] System.Object! x
System.Object? y
System.Object? this[System.Object! x, System.Object? y].get
[Nullable(1)] System.Object! x
System.Object? y
void this[System.Object! x, System.Object? y].set
[Nullable(1)] System.Object! x
System.Object? y
System.Object? value
[Nullable(0)] Program.ProtectedInternalType
ProtectedInternalType()
System.Object! this[System.Object! x, System.Object! y] { set; }
System.Object! x
System.Object! y
void this[System.Object! x, System.Object! y].set
System.Object! x
System.Object! y
System.Object! value
[Nullable(0)] Program.PrivateProtectedType
PrivateProtectedType()
System.Object! this[System.Object! x, System.Object! y] { get; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
";
var expectedAll = @"
[NullableContext(1)] [Nullable(0)] Program
Program()
[NullableContext(2)] [Nullable(0)] Program.PublicType
PublicType()
System.Object? this[System.Object? x, System.Object! y] { get; }
System.Object? x
[Nullable(1)] System.Object! y
System.Object? this[System.Object? x, System.Object! y].get
System.Object? x
[Nullable(1)] System.Object! y
[Nullable(0)] Program.InternalType
InternalType()
System.Object! this[System.Object! x, System.Object! y] { get; set; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
void this[System.Object! x, System.Object! y].set
System.Object! x
System.Object! y
System.Object! value
[NullableContext(2)] [Nullable(0)] Program.ProtectedType
ProtectedType()
System.Object? this[System.Object! x, System.Object? y] { get; set; }
[Nullable(1)] System.Object! x
System.Object? y
System.Object? this[System.Object! x, System.Object? y].get
[Nullable(1)] System.Object! x
System.Object? y
void this[System.Object! x, System.Object? y].set
[Nullable(1)] System.Object! x
System.Object? y
System.Object? value
[Nullable(0)] Program.ProtectedInternalType
ProtectedInternalType()
System.Object! this[System.Object! x, System.Object! y] { set; }
System.Object! x
System.Object! y
void this[System.Object! x, System.Object! y].set
System.Object! x
System.Object! y
System.Object! value
[Nullable(0)] Program.PrivateProtectedType
PrivateProtectedType()
System.Object! this[System.Object! x, System.Object! y] { get; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
[Nullable(0)] Program.PrivateType
PrivateType()
System.Object! this[System.Object! x, System.Object! y] { get; }
System.Object! x
System.Object! y
System.Object! this[System.Object! x, System.Object! y].get
System.Object! x
System.Object! y
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_TypeParameters()
{
var source =
@"public class Base { }
public class Program
{
protected static void ProtectedMethod<T, U>()
where T : notnull
where U : class
{
}
internal static void InternalMethod<T, U>()
where T : notnull
where U : class
{
}
private static void PrivateMethod<T, U>()
where T : notnull
where U : class
{
}
}";
var expectedPublicOnly = @"
Program
[NullableContext(1)] void ProtectedMethod<T, U>() where T : notnull where U : class!
T
U
";
var expectedPublicAndInternal = @"
[NullableContext(1)] [Nullable(0)] Program
void ProtectedMethod<T, U>() where T : notnull where U : class!
T
U
void InternalMethod<T, U>() where T : notnull where U : class!
T
U
Program()
";
var expectedAll = @"
[NullableContext(1)] [Nullable(0)] Program
void ProtectedMethod<T, U>() where T : notnull where U : class!
T
U
void InternalMethod<T, U>() where T : notnull where U : class!
T
U
void PrivateMethod<T, U>() where T : notnull where U : class!
T
U
Program()
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
[WorkItem(37161, "https://github.com/dotnet/roslyn/issues/37161")]
public void EmitPrivateMetadata_ExplicitImplementation()
{
var source =
@"public interface I<T>
{
T M(T[] args);
T P { get; set; }
T[] this[T index] { get; }
}
public class C : I<object?>
{
object? I<object?>.M(object?[] args) => throw null!;
object? I<object?>.P { get; set; }
object?[] I<object?>.this[object? index] => throw null!;
}";
// Attributes emitted for explicitly-implemented property and indexer, but not for accessors.
var expectedPublicOnly = @"
[NullableContext(1)] I<T>
[Nullable(2)] T
T M(T[]! args)
T[]! args
T P { get; set; }
T P.get
void P.set
T value
T[]! this[T index] { get; }
T index
T[]! this[T index].get
T index
C
[Nullable(2)] System.Object? I<System.Object>.P { get; set; }
[Nullable({ 1, 2 })] System.Object?[]! I<System.Object>.Item[System.Object index] { get; }
";
// Attributes emitted for explicitly-implemented property and indexer, but not for accessors.
var expectedPublicAndInternal = @"
[NullableContext(1)] I<T>
[Nullable(2)] T
T M(T[]! args)
T[]! args
T P { get; set; }
T P.get
void P.set
T value
T[]! this[T index] { get; }
T index
T[]! this[T index].get
T index
C
[Nullable(2)] System.Object? I<System.Object>.P { get; set; }
[Nullable({ 1, 2 })] System.Object?[]! I<System.Object>.Item[System.Object index] { get; }
";
var expectedAll = @"
[NullableContext(1)] I<T>
[Nullable(2)] T
T M(T[]! args)
T[]! args
T P { get; set; }
T P.get
void P.set
T value
T[]! this[T index] { get; }
T index
T[]! this[T index].get
T index
[NullableContext(2)] [Nullable(0)] C
System.Object? <I<System.Object>.P>k__BackingField
System.Object? I<System.Object>.M(System.Object?[]! args)
[Nullable({ 1, 2 })] System.Object?[]! args
[Nullable({ 1, 2 })] System.Object?[]! I<System.Object>.get_Item(System.Object? index)
System.Object? index
C()
System.Object? I<System.Object>.P { get; set; }
System.Object? I<System.Object>.P.get
void I<System.Object>.P.set
System.Object? value
[Nullable({ 1, 2 })] System.Object?[]! I<System.Object>.Item[System.Object? index] { get; }
System.Object? index
[Nullable({ 1, 2 })] System.Object?[]! I<System.Object>.get_Item(System.Object? index)
System.Object? index
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_SynthesizedFields()
{
var source =
@"public struct S<T> { }
public class Public
{
public static void PublicMethod()
{
S<object?> s;
System.Action a = () => { s.ToString(); };
}
}";
var expectedPublicOnly = @"
S<T>
[Nullable(2)] T
";
var expectedPublicAndInternal = @"
S<T>
[Nullable(2)] T
";
var expectedAll = @"
S<T>
[Nullable(2)] T
Public
Public.<>c__DisplayClass0_0
[Nullable({ 0, 2 })] S<System.Object?> s
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_SynthesizedParameters()
{
var source =
@"public class Public
{
private static void PrivateMethod(string x)
{
_ = new System.Action<string?>((string y) => { });
}
}";
var expectedPublicOnly = @"";
var expectedPublicAndInternal = @"";
var expectedAll = @"
Public
[NullableContext(1)] void PrivateMethod(System.String! x)
System.String! x
Public.<>c
[Nullable({ 0, 2 })] System.Action<System.String?> <>9__0_0
[NullableContext(1)] void <PrivateMethod>b__0_0(System.String! y)
System.String! y
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_AnonymousType()
{
var source =
@"public class Program
{
public static void Main()
{
_ = new { A = new object(), B = (string?)null };
}
}";
var expectedPublicOnly = @"";
var expectedPublicAndInternal = @"";
var expectedAll = @"";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
[Fact]
public void EmitPrivateMetadata_Iterator()
{
var source =
@"using System.Collections.Generic;
public class Program
{
public static IEnumerable<object?> F()
{
yield break;
}
}";
var expectedPublicOnly = @"
Program
[Nullable({ 1, 2 })] System.Collections.Generic.IEnumerable<System.Object?>! F()
";
var expectedPublicAndInternal = @"
Program
[Nullable({ 1, 2 })] System.Collections.Generic.IEnumerable<System.Object?>! F()
";
var expectedAll = @"
Program
[Nullable({ 1, 2 })] System.Collections.Generic.IEnumerable<System.Object?>! F()
Program.<F>d__0
[Nullable(2)] System.Object? <>2__current
System.Object System.Collections.Generic.IEnumerator<System.Object>.Current { get; }
[Nullable(2)] System.Object? System.Collections.Generic.IEnumerator<System.Object>.Current.get
";
EmitPrivateMetadata(source, expectedPublicOnly, expectedPublicAndInternal, expectedAll);
}
private void EmitPrivateMetadata(string source, string expectedPublicOnly, string expectedPublicAndInternal, string expectedAll)
{
var sourceIVTs =
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""Other"")]";
var options = WithNullableEnable().WithMetadataImportOptions(MetadataImportOptions.All);
var parseOptions = TestOptions.Regular8;
AssertNullableAttributes(CreateCompilation(source, options: options, parseOptions: parseOptions), expectedAll);
AssertNullableAttributes(CreateCompilation(source, options: options, parseOptions: parseOptions.WithFeature("nullablePublicOnly")), expectedPublicOnly);
AssertNullableAttributes(CreateCompilation(new[] { source, sourceIVTs }, options: options, parseOptions: parseOptions), expectedAll);
AssertNullableAttributes(CreateCompilation(new[] { source, sourceIVTs }, options: options, parseOptions: parseOptions.WithFeature("nullablePublicOnly")), expectedPublicAndInternal);
}
/// <summary>
/// Should only require NullableAttribute constructor if nullable annotations are emitted.
/// </summary>
[Fact]
public void EmitPrivateMetadata_MissingAttributeConstructor()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute { }
}";
var source =
@"#pragma warning disable 0067
#pragma warning disable 0169
#pragma warning disable 8321
public class A
{
private object? F;
private static object? M(object arg) => null;
private object? P => null;
private object? this[object x, object? y] => null;
private event D<object?> E;
public static void M()
{
object? f(object arg) => arg;
object? l(object arg) { return arg; }
D<object> d = () => new object();
}
}
internal delegate T D<T>();
internal interface I<T> { }
internal class B : I<object>
{
public static object operator!(B b) => b;
public event D<object?> E;
private (object, object?) F;
}";
var options = WithNullableEnable();
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(new[] { sourceAttribute, source }, options: options, parseOptions: parseOptions);
comp.VerifyEmitDiagnostics(
// (6,21): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? F;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(6, 21),
// (7,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private static object? M(object arg) => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(7, 20),
// (7,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private static object? M(object arg) => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object arg").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(7, 30),
// (8,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? P => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(8, 13),
// (9,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 13),
// (9,26): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 26),
// (9,36): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? y").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 36),
// (10,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private event D<object?> E;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "E").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 30),
// (10,30): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable.
// private event D<object?> E;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(10, 30),
// (13,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// object? f(object arg) => arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(13, 9),
// (13,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// object? f(object arg) => arg;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object arg").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(13, 19),
// (14,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// object? l(object arg) { return arg; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(14, 9),
// (14,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// object? l(object arg) { return arg; }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object arg").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(14, 19),
// (15,26): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// D<object> d = () => new object();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=>").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(15, 26),
// (18,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// internal delegate T D<T>();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(18, 19),
// (18,23): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// internal delegate T D<T>();
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(18, 23),
// (19,22): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// internal interface I<T> { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(19, 22),
// (20,16): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// internal class B : I<object>
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "B").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(20, 16),
// (22,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// public static object operator!(B b) => b;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(22, 19),
// (22,36): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// public static object operator!(B b) => b;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "B b").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(22, 36),
// (23,29): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// public event D<object?> E;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "E").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(23, 29),
// (23,29): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable.
// public event D<object?> E;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(23, 29),
// (24,31): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private (object, object?) F;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(24, 31));
comp = CreateCompilation(new[] { sourceAttribute, source }, options: options, parseOptions: parseOptions.WithFeature("nullablePublicOnly"));
comp.VerifyEmitDiagnostics(
// (8,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? P => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(8, 13),
// (9,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 13),
// (9,26): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object x").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 26),
// (9,36): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? this[object x, object? y] => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object? y").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(9, 36),
// (10,30): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private event D<object?> E;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "E").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(10, 30),
// (10,30): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable.
// private event D<object?> E;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(10, 30),
// (23,29): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable.
// public event D<object?> E;
Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(23, 29)
);
}
[Fact]
public void EmitPrivateMetadata_MissingAttributeConstructor_NullableDisabled()
{
var sourceAttribute =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute { }
}";
var source =
@"#pragma warning disable 414
public class Program
{
private object? F = null;
private object? P => null;
}";
var options = TestOptions.ReleaseDll;
var parseOptions = TestOptions.Regular8;
var comp = CreateCompilation(new[] { sourceAttribute, source }, options: options, parseOptions: parseOptions);
comp.VerifyEmitDiagnostics(
// (4,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// private object? F = null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 19),
// (4,21): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? F = null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "F").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(4, 21),
// (5,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? P => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(5, 13),
// (5,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// private object? P => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 19));
comp = CreateCompilation(new[] { sourceAttribute, source }, options: options, parseOptions: parseOptions.WithFeature("nullablePublicOnly"));
comp.VerifyEmitDiagnostics(
// (4,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// private object? F = null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 19),
// (5,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'
// private object? P => null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute", ".ctor").WithLocation(5, 13),
// (5,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
// private object? P => null;
Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 19));
}
[Fact]
public void EmitAttribute_ValueTypes_01()
{
var source =
@"#nullable enable
struct S1<T> { }
struct S2<T, U> { }
class C1<T> { }
class C2<T, U> { }
class Program
{
static void F() { }
int F11;
int? F12;
#nullable disable
object F21;
#nullable enable
object F22;
S1<int> F31;
S1<int?>? F32;
S1<
#nullable disable
object
#nullable enable
> F33;
S1<object?> F34;
S2<int, int> F41;
S2<int,
#nullable disable
object
#nullable enable
> F42;
S2<
#nullable disable
object,
#nullable enable
int> F43;
S2<
#nullable disable
object, object
#nullable enable
> F44;
S2<int, object> F45;
S2<object?, int> F46;
S2<
#nullable disable
object,
#nullable enable
object> F47;
S2<object?,
#nullable disable
object
#nullable enable
> F48;
S2<object, object?> F49;
C1<int
#nullable disable
> F51;
#nullable enable
C1<int?
#nullable disable
> F52;
#nullable enable
C1<int> F53;
C1<int?> F54;
C1<
#nullable disable
object> F55;
#nullable enable
C1<object
#nullable disable
> F56;
#nullable enable
C1<
#nullable disable
object
#nullable enable
>? F57;
C1<object>? F58;
C2<int,
#nullable disable
object> F60;
#nullable enable
C2<int, object
#nullable disable
> F61;
#nullable enable
C2<object?, int
#nullable disable
> F62;
#nullable enable
C2<int, object> F63;
C2<object?, int>? F64;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<MethodSymbol>("Program.F").ReturnTypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "void");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F11").TypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "int");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F12").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { }, "int?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F21").TypeWithAnnotations, new byte[] { 0 }, new byte[] { 0 }, "object");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F22").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "object!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F31").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "S1<int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F32").TypeWithAnnotations, new byte[] { 0, 0, 0, 0 }, new byte[] { 0 }, "S1<int?>?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F33").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "S1<object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F34").TypeWithAnnotations, new byte[] { 0, 2 }, new byte[] { 0, 2 }, "S1<object?>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F41").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0 }, "S2<int, int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F42").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "S2<int, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F43").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "S2<object, int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F44").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0, 0 }, "S2<object, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F45").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 1 }, "S2<int, object!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F46").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2 }, "S2<object?, int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F47").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 1 }, "S2<object, object!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F48").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2, 0 }, "S2<object?, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F49").TypeWithAnnotations, new byte[] { 0, 1, 2 }, new byte[] { 0, 1, 2 }, "S2<object!, object?>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F51").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "C1<int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F52").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0 }, "C1<int?>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F53").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "C1<int>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F54").TypeWithAnnotations, new byte[] { 1, 0, 0 }, new byte[] { 1 }, "C1<int?>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F55").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "C1<object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F56").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "C1<object!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F57").TypeWithAnnotations, new byte[] { 2, 0 }, new byte[] { 2, 0 }, "C1<object>?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F58").TypeWithAnnotations, new byte[] { 2, 1 }, new byte[] { 2, 1 }, "C1<object!>?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F60").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "C2<int, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F61").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 1 }, "C2<int, object!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F62").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2 }, "C2<object?, int>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F63").TypeWithAnnotations, new byte[] { 1, 0, 1 }, new byte[] { 1, 1 }, "C2<int, object!>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F64").TypeWithAnnotations, new byte[] { 2, 2, 0 }, new byte[] { 2, 2 }, "C2<object?, int>?");
}
}
[Fact]
public void EmitAttribute_ValueTypes_02()
{
var source =
@"#nullable enable
struct S<T> { }
class Program
{
int
#nullable disable
[] F1;
#nullable enable
int[] F2;
int?[]? F3;
int
#nullable disable
[]
#nullable enable
[] F4;
int?[]
#nullable disable
[] F5;
#nullable enable
S<int
#nullable disable
[]
#nullable enable
> F6;
S<int?[]?>? F7;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "int[]");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "int[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 2, 0, 0 }, new byte[] { 2 }, "int?[]?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 1, 0 }, new byte[] { 0, 1 }, "int[]![]");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 1, 0, 0, 0 }, new byte[] { 1, 0 }, "int?[][]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "S<int[]>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F7").TypeWithAnnotations, new byte[] { 0, 0, 2, 0, 0 }, new byte[] { 0, 2 }, "S<int?[]?>?");
}
}
[Fact]
public void EmitAttribute_ValueTypes_03()
{
var source =
@"#nullable enable
class Program
{
System.ValueTuple F0;
(int, int) F1;
(int?, int?)? F2;
#nullable disable
(int, object) F3;
(object, int) F4;
#nullable enable
(int, object?) F5;
(object, int) F6;
((int, int), ((int, int), int)) F7;
((int, int), ((int, object), int)) F8;
#nullable disable
(int _1, int _2, int _3, int _4, int _5, int _6, int _7, object _8) F9;
#nullable enable
(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9) F10;
(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, object _9) F11;
(int _1, int _2, int _3, int _4, int _5, int _6, int _7, object _8, int _9) F12;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F0").TypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "System.ValueTuple");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0 }, "(int, int)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0 }, new byte[] { 0 }, "(int?, int?)?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "(int, object)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "(object, int)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0, 2 }, new byte[] { 0, 2 }, "(int, object?)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 0, 1, 0 }, new byte[] { 0, 1 }, "(object!, int)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F7").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new byte[] { 0, 0, 0, 0 }, "((int, int), ((int, int), int))");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F8").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 1, 0 }, new byte[] { 0, 0, 0, 0, 1 }, "((int, int), ((int, object!), int))");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F9").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new byte[] { 0, 0, 0 }, "(int _1, int _2, int _3, int _4, int _5, int _6, int _7, object _8)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F10").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new byte[] { 0, 0 }, "(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, int _9)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F11").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, new byte[] { 0, 0, 1 }, "(int _1, int _2, int _3, int _4, int _5, int _6, int _7, int _8, object! _9)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F12").TypeWithAnnotations, new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 }, new byte[] { 0, 0, 1 }, "(int _1, int _2, int _3, int _4, int _5, int _6, int _7, object! _8, int _9)");
}
}
[Fact]
public void EmitAttribute_ValueTypes_04()
{
var source =
@"#nullable enable
struct S0
{
internal struct S { }
internal class C { }
}
struct S1<T>
{
internal struct S { }
internal class C { }
}
class C0
{
internal struct S { }
internal class C { }
}
class C1<T>
{
internal struct S { }
internal class C { }
}
class Program
{
S0.S F11;
#nullable disable
S0.C F12;
#nullable enable
S0.C F13;
S1<int>.S F21;
#nullable disable
S1<int>.C F22;
#nullable enable
S1<int>.C F23;
#nullable disable
S1<object>.S F24;
#nullable enable
S1<object>.S F25;
S1<
#nullable disable
object
#nullable enable
>.C F26;
S1<object
#nullable disable
>.C F27;
#nullable enable
S1<int>.S[] F28;
S1<C1<object>.S> F29;
C0.S F31;
#nullable disable
C0.C F32;
#nullable enable
C0.C F33;
C1<int>.S F41;
#nullable disable
C1<int>.C F42;
#nullable enable
C1<int>.C F43;
#nullable disable
C1<object>.S F44;
#nullable enable
C1<object>.S F45;
C1<
#nullable disable
object
#nullable enable
>.C F46;
C1<object
#nullable disable
>.C F47;
#nullable enable
C1<int>.S[] F48;
C1<S1<object>.S> F49;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F11").TypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "S0.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F12").TypeWithAnnotations, new byte[] { 0 }, new byte[] { 0 }, "S0.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F13").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "S0.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F21").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "S1<int>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F22").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "S1<int>.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F23").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "S1<int>.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F24").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "S1<object>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F25").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "S1<object!>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F26").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1, 0 }, "S1<object>.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F27").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "S1<object!>.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F28").TypeWithAnnotations, new byte[] { 1, 0, 0 }, new byte[] { 1, 0 }, "S1<int>.S[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F29").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 1 }, "S1<C1<object!>.S>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F31").TypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "C0.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F32").TypeWithAnnotations, new byte[] { 0 }, new byte[] { 0 }, "C0.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F33").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "C0.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F41").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "C1<int>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F42").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "C1<int>.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F43").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "C1<int>.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F44").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "C1<object>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F45").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "C1<object!>.S");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F46").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1, 0 }, "C1<object>.C!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F47").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "C1<object!>.C");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F48").TypeWithAnnotations, new byte[] { 1, 0, 0 }, new byte[] { 1, 0 }, "C1<int>.S[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F49").TypeWithAnnotations, new byte[] { 1, 0, 1 }, new byte[] { 1, 0, 1 }, "C1<S1<object!>.S>!");
}
}
[Fact]
public void EmitAttribute_ValueTypes_05()
{
var source =
@"#nullable enable
interface I0
{
internal delegate void D();
internal enum E { }
internal interface I { }
}
interface I1<T>
{
internal delegate void D();
internal enum E { }
internal interface I { }
}
class Program
{
I0.D F1;
I0.E F2;
I0.I F3;
I1<int>.D F4;
I1<int>.E F5;
I1<int>.I F6;
#nullable disable
I1<object>.D F7;
I1<object>.E F8;
I1<object>.I F9;
#nullable enable
I1<object>.E F10;
I1<int>.E[] F11;
I1<I0.E> F12;
I1<I1<object>.E>.E F13;
I1<I1<int>.D>.I F14;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "I0.D!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 0 }, new byte[] { }, "I0.E");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "I0.I!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "I1<int>.D!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "I1<int>.E");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "I1<int>.I!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F7").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "I1<object>.D");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F8").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "I1<object>.E");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F9").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "I1<object>.I");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F10").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "I1<object!>.E");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F11").TypeWithAnnotations, new byte[] { 1, 0, 0 }, new byte[] { 1, 0 }, "I1<int>.E[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F12").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1 }, "I1<I0.E>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F13").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 1 }, "I1<I1<object!>.E>.E");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F14").TypeWithAnnotations, new byte[] { 1, 1, 0 }, new byte[] { 1, 1 }, "I1<I1<int>.D!>.I!");
}
}
[Fact]
public void EmitAttribute_ValueTypes_06()
{
var source =
@"#nullable enable
struct S<T> { }
class C<T> { }
unsafe class Program
{
int* F1;
int?* F2;
S<int*> F3;
S<int>* F4;
#nullable disable
C<int*> F5;
#nullable enable
C<int*> F6;
}";
var comp = CreateCompilation(source);
var globalNamespace = comp.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "int*");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0 }, "int?*");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "S<int*>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "S<int>*");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0, 0 }, new byte[] { 0, 0 }, "C<int*>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 1, 0, 0 }, new byte[] { 1, 0 }, "C<int*>!");
}
[Fact]
public void EmitAttribute_ValueTypes_07()
{
var source =
@"#nullable enable
class C<T> { }
struct S<T> { }
class Program<T, U, V>
where U : class
where V : struct
{
T F11;
T[] F12;
C<T> F13;
S<T> F14;
#nullable disable
U F21;
#nullable enable
U? F22;
U[] F23;
C<U> F24;
S<U> F25;
V F31;
V? F32;
V[] F33;
C<V> F34;
S<V> F35;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var globalNamespace = module.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F11").TypeWithAnnotations, new byte[] { 1 }, new byte[] { 1 }, "T");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F12").TypeWithAnnotations, new byte[] { 1, 1 }, new byte[] { 1, 1 }, "T[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F13").TypeWithAnnotations, new byte[] { 1, 1 }, new byte[] { 1, 1 }, "C<T>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F14").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "S<T>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F21").TypeWithAnnotations, new byte[] { 0 }, new byte[] { 0 }, "U");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F22").TypeWithAnnotations, new byte[] { 2 }, new byte[] { 2 }, "U?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F23").TypeWithAnnotations, new byte[] { 1, 1 }, new byte[] { 1, 1 }, "U![]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F24").TypeWithAnnotations, new byte[] { 1, 1 }, new byte[] { 1, 1 }, "C<U!>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F25").TypeWithAnnotations, new byte[] { 0, 1 }, new byte[] { 0, 1 }, "S<U!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F31").TypeWithAnnotations, new byte[] { 0 }, new byte[] { 0 }, "V");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F32").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0 }, "V?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F33").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1, 0 }, "V[]!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F34").TypeWithAnnotations, new byte[] { 1, 0 }, new byte[] { 1, 0 }, "C<V>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F35").TypeWithAnnotations, new byte[] { 0, 0 }, new byte[] { 0, 0 }, "S<V>");
}
}
[Fact]
public void EmitAttribute_ValueTypes_08()
{
var source0 =
@"public struct S0 { }
public struct S2<T, U> { }";
var comp = CreateCompilation(source0);
var ref0 = comp.EmitToImageReference();
var source1 =
@"#nullable enable
public class C2<T, U> { }
public class Program
{
public C2<S0, object?> F1;
public C2<object, S0>? F2;
public S2<S0, object> F3;
public S2<object?, S0> F4;
public (S0, object) F5;
public (object?, S0) F6;
}";
// With reference assembly.
comp = CreateCompilation(source1, references: new[] { ref0 });
var ref1 = comp.EmitToImageReference();
var globalNamespace = comp.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 1, 0, 2 }, new byte[] { 1, 2 }, "C2<S0, object?>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 2, 1, 0 }, new byte[] { 2, 1 }, "C2<object!, S0>?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 1 }, "S2<S0, object!>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2 }, "S2<object?, S0>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 1 }, "(S0, object!)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2 }, "(object?, S0)");
// Without reference assembly.
comp = CreateCompilation(source1);
globalNamespace = comp.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 1, 0, 2 }, new byte[] { 1, 1, 2 }, "C2<S0!, object?>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 2, 1, 0 }, new byte[] { 2, 1, 1 }, "C2<object!, S0!>?");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 1, 1, 1 }, "S2<S0!, object!>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 1, 2, 1 }, "S2<object?, S0!>!");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 1, 1 }, "(S0!, object!)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 2, 1 }, "(object?, S0!)");
var source2 =
@"";
// Without reference assembly.
comp = CreateCompilation(source2, references: new[] { ref1 });
globalNamespace = comp.GlobalNamespace;
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F1").TypeWithAnnotations, new byte[] { 1, 0, 2 }, new byte[] { 0, 0, 0 }, "C2<S0, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F2").TypeWithAnnotations, new byte[] { 2, 1, 0 }, new byte[] { 0, 0, 0 }, "C2<object, S0>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F3").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 0 }, "S2<S0, object>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F4").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 0, 0 }, "S2<object, S0>");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F5").TypeWithAnnotations, new byte[] { 0, 0, 1 }, new byte[] { 0, 0, 0 }, "(S0, object)");
VerifyBytes(globalNamespace.GetMember<FieldSymbol>("Program.F6").TypeWithAnnotations, new byte[] { 0, 2, 0 }, new byte[] { 0, 0, 0 }, "(object, S0)");
}
private static readonly SymbolDisplayFormat _displayFormat = SymbolDisplayFormat.TestFormat.
WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.UseSpecialTypes).
WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None);
private static void VerifyBytes(TypeWithAnnotations type, byte[] expectedPreviously, byte[] expectedNow, string expectedDisplay)
{
var builder = ArrayBuilder<byte>.GetInstance();
type.AddNullableTransforms(builder);
var actualBytes = builder.ToImmutableAndFree();
Assert.Equal(expectedNow, actualBytes);
Assert.Equal(expectedDisplay, type.ToDisplayString(_displayFormat));
var underlyingType = type.SetUnknownNullabilityForReferenceTypes();
// Verify re-applying the same bytes gives the same result.
TypeWithAnnotations updated;
int position = 0;
Assert.True(underlyingType.ApplyNullableTransforms(0, actualBytes, ref position, out updated));
Assert.True(updated.Equals(type, TypeCompareKind.ConsiderEverything));
// If the expected byte[] is shorter than earlier builds, verify that
// applying the previous byte[] does not consume all bytes.
if (!expectedPreviously.SequenceEqual(expectedNow))
{
position = 0;
underlyingType.ApplyNullableTransforms(0, ImmutableArray.Create(expectedPreviously), ref position, out _);
Assert.Equal(position, expectedNow.Length);
}
}
[Fact]
public void EmitAttribute_ValueTypes_09()
{
var source1 =
@"#nullable enable
public interface I
{
void M1(int x);
void M2(int[]? x);
void M3(int x, object? y);
}";
var comp = CreateCompilation(source1);
var expected1 =
@"[NullableContext(2)] I
void M1(System.Int32 x)
System.Int32 x
void M2(System.Int32[]? x)
System.Int32[]? x
void M3(System.Int32 x, System.Object? y)
System.Int32 x
System.Object? y
";
AssertNullableAttributes(comp, expected1);
var ref0 = comp.EmitToImageReference();
var source2 =
@"#nullable enable
class C : I
{
public void M1(int x) { }
public void M2(int[]? x) { }
public void M3(int x, object? y) { }
}";
comp = CreateCompilation(source2, references: new[] { ref0 });
comp.VerifyDiagnostics();
}
[Fact]
public void EmitAttribute_ValueTypes_10()
{
var source1 =
@"#nullable enable
public class C<T> { }
public interface I1
{
void M(int x, object? y, object? z);
}
public interface I2
{
void M(C<int>? x, object? y, object? z);
}";
var comp = CreateCompilation(source1);
var expected1 =
@"C<T>
[Nullable(2)] T
[NullableContext(2)] I1
void M(System.Int32 x, System.Object? y, System.Object? z)
System.Int32 x
System.Object? y
System.Object? z
[NullableContext(2)] I2
void M(C<System.Int32>? x, System.Object? y, System.Object? z)
C<System.Int32>? x
System.Object? y
System.Object? z
";
AssertNullableAttributes(comp, expected1);
var ref0 = comp.EmitToImageReference();
var source2 =
@"#nullable enable
class C1 : I1
{
public void M(int x, object? y, object? z) { }
}
class C2 : I2
{
public void M(C<int>? x, object? y, object? z) { }
}";
comp = CreateCompilation(source2, references: new[] { ref0 });
comp.VerifyDiagnostics();
}
[Fact]
public void EmitAttribute_ValueTypes_11()
{
var source1 =
@"#nullable enable
public interface I1<T>
{
void M(T x, object? y, object? z);
}
public interface I2<T> where T : class
{
void M(T? x, object? y, object? z);
}
public interface I3<T> where T : struct
{
void M(T x, object? y, object? z);
}";
var comp = CreateCompilation(source1);
var expected1 =
@"[NullableContext(2)] I1<T>
T
void M(T x, System.Object? y, System.Object? z)
[Nullable(1)] T x
System.Object? y
System.Object? z
[NullableContext(1)] I2<T> where T : class!
T
[NullableContext(2)] void M(T? x, System.Object? y, System.Object? z)
T? x
System.Object? y
System.Object? z
I3<T> where T : struct
[NullableContext(2)] void M(T x, System.Object? y, System.Object? z)
[Nullable(0)] T x
System.Object? y
System.Object? z
";
AssertNullableAttributes(comp, expected1);
var ref0 = comp.EmitToImageReference();
var source2 =
@"#nullable enable
class C1A<T> : I1<T> where T : struct
{
public void M(T x, object? y, object? z) { }
}
class C1B : I1<int>
{
public void M(int x, object? y, object? z) { }
}
class C2A<T> : I2<T> where T : class
{
public void M(T? x, object? y, object? z) { }
}
class C2B : I2<string>
{
public void M(string? x, object? y, object? z) { }
}
class C3A<T> : I3<T> where T : struct
{
public void M(T x, object? y, object? z) { }
}
class C3B : I3<int>
{
public void M(int x, object? y, object? z) { }
}";
comp = CreateCompilation(source2, references: new[] { ref0 });
comp.VerifyDiagnostics();
}
[Fact]
public void UseSiteError_LambdaReturnType()
{
var source0 =
@"namespace System
{
public class Object { }
public abstract class ValueType { }
public struct Void { }
public struct Boolean { }
public struct IntPtr { }
public class MulticastDelegate { }
}";
var comp0 = CreateEmptyCompilation(source0);
var ref0 = comp0.EmitToImageReference();
var source =
@"delegate T D<T>();
class C
{
static void F<T>(D<T> d)
{
}
static void G(object o)
{
F(() =>
{
if (o != new object()) return o;
return null;
});
}
}";
var comp = CreateEmptyCompilation(
source,
references: new[] { ref0 },
parseOptions: TestOptions.Regular8);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ModuleMissingAttribute_BaseClass()
{
var source =
@"class A<T>
{
}
class B : A<object?>
{
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,9): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// class A<T>
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 9),
// (4,7): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// class B : A<object?>
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(4, 7));
}
[Fact]
public void ModuleMissingAttribute_Interface()
{
var source =
@"interface I<T>
{
}
class C : I<(object X, object? Y)>
{
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,11): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// interface I<T>
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "I").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(1, 11),
// (1,13): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// interface I<T>
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 13),
// (4,7): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// class C : I<(object X, object? Y)>
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(4, 7));
}
[Fact]
public void ModuleMissingAttribute_MethodReturnType()
{
var source =
@"class C
{
object? F() => null;
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,5): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object? F() => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 5),
// (3,13): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// object? F() => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "F").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(3, 13));
}
[Fact]
public void ModuleMissingAttribute_MethodParameters()
{
var source =
@"class C
{
void F(object?[] c) { }
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,12): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// void F(object?[] c) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?[] c").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 12));
}
[Fact]
public void ModuleMissingAttribute_ConstructorParameters()
{
var source =
@"class C
{
C(object?[] c) { }
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,7): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// C(object?[] c) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?[] c").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 7));
}
[Fact]
public void ModuleMissingAttribute_PropertyType()
{
var source =
@"class C
{
object? P => null;
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,7): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// class C
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(1, 7),
// (3,5): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object? P => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 5));
}
[Fact]
public void ModuleMissingAttribute_PropertyParameters()
{
var source =
@"class C
{
object this[object x, object? y] => throw new System.NotImplementedException();
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,7): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// class C
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(1, 7),
// (3,5): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object this[object x, object? y] => throw new System.NotImplementedException();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 5),
// (3,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object this[object x, object? y] => throw new System.NotImplementedException();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object x").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 17),
// (3,27): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object this[object x, object? y] => throw new System.NotImplementedException();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object? y").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 27));
}
[Fact]
public void ModuleMissingAttribute_OperatorReturnType()
{
var source =
@"class C
{
public static object? operator+(C a, C b) => null;
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object? operator+(C a, C b) => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 19),
// (3,35): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// public static object? operator+(C a, C b) => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "+").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(3, 35),
// (3,37): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object? operator+(C a, C b) => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C a").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 37),
// (3,42): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object? operator+(C a, C b) => null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C b").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 42)
);
}
[Fact]
public void ModuleMissingAttribute_OperatorParameters()
{
var source =
@"class C
{
public static object operator+(C a, object?[] b) => a;
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (3,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object operator+(C a, object?[] b) => a;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 19),
// (3,34): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// public static object operator+(C a, object?[] b) => a;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "+").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(3, 34),
// (3,36): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object operator+(C a, object?[] b) => a;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C a").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 36),
// (3,41): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// public static object operator+(C a, object?[] b) => a;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?[] b").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(3, 41));
}
[Fact]
public void ModuleMissingAttribute_DelegateReturnType()
{
var source =
@"delegate object? D();";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,10): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// delegate object? D();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 10),
// (1,18): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// delegate object? D();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "D").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(1, 18));
}
[Fact]
public void ModuleMissingAttribute_DelegateParameters()
{
var source =
@"delegate void D(object?[] o);";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// delegate void D(object?[] o);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?[] o").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 17));
}
[Fact]
public void ModuleMissingAttribute_LambdaReturnType()
{
var source =
@"delegate T D<T>();
class C
{
static void F<T>(D<T> d)
{
}
static void G(object o)
{
F(() =>
{
if (o != new object()) return o;
return null;
});
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseModule);
// The lambda signature is emitted without a [Nullable] attribute because
// the return type is inferred from flow analysis, not from initial binding.
// As a result, there is no missing attribute warning.
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ModuleMissingAttribute_LambdaParameters()
{
var source =
@"delegate void D<T>(T t);
class C
{
static void F<T>(D<T> d)
{
}
static void G()
{
F((object? o) => { });
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (1,15): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// delegate void D<T>(T t);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "D").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(1, 15),
// (1,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// delegate void D<T>(T t);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 17),
// (1,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// delegate void D<T>(T t);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T t").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(1, 20),
// (4,17): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableContextAttribute' is not defined or imported
// static void F<T>(D<T> d)
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "F").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(4, 17),
// (4,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// static void F<T>(D<T> d)
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(4, 19),
// (4,22): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// static void F<T>(D<T> d)
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "D<T> d").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(4, 22),
// (9,12): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// F((object? o) => { });
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object? o").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(9, 12));
}
[Fact]
public void ModuleMissingAttribute_LocalFunctionReturnType()
{
var source =
@"class C
{
static void M()
{
object?[] L() => throw new System.NotImplementedException();
L();
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (5,9): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// object?[] L() => throw new System.NotImplementedException();
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object?[]").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(5, 9));
}
[Fact]
public void ModuleMissingAttribute_LocalFunctionParameters()
{
var source =
@"class C
{
static void M()
{
void L(object? x, object y) { }
L(null, 2);
}
}";
var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseModule));
comp.VerifyEmitDiagnostics(
// (5,16): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// void L(object? x, object y) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object? x").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(5, 16),
// (5,27): error CS0518: Predefined type 'System.Runtime.CompilerServices.NullableAttribute' is not defined or imported
// void L(object? x, object y) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "object y").WithArguments("System.Runtime.CompilerServices.NullableAttribute").WithLocation(5, 27));
}
[Fact]
public void Tuples()
{
var source =
@"public class A
{
public static ((object?, object) _1, object? _2, object _3, ((object?[], object), object?) _4) Nested;
public static (object? _1, object _2, object? _3, object _4, object? _5, object _6, object? _7, object _8, object? _9) Long;
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "A");
var fieldDefs = typeDef.GetFields().Select(f => reader.GetFieldDefinition(f)).ToArray();
// Nested tuple
var field = fieldDefs.Single(f => reader.StringComparer.Equals(f.Name, "Nested"));
var customAttributes = field.GetCustomAttributes();
AssertAttributes(reader, customAttributes,
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])",
"MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
var customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
AssertEx.Equal(ImmutableArray.Create<byte>(0, 0, 2, 0, 2, 0, 0, 0, 0, 2, 0, 2), reader.ReadByteArray(customAttribute.Value));
// Long tuple
field = fieldDefs.Single(f => reader.StringComparer.Equals(f.Name, "Long"));
customAttributes = field.GetCustomAttributes();
AssertAttributes(reader, customAttributes,
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])",
"MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
AssertEx.Equal(ImmutableArray.Create<byte>(0, 2, 0, 2, 0, 2, 0, 2, 0, 0, 2), reader.ReadByteArray(customAttribute.Value));
});
var source2 =
@"class B
{
static void Main()
{
A.Nested._1.Item1.ToString(); // 1
A.Nested._1.Item2.ToString();
A.Nested._2.ToString(); // 2
A.Nested._3.ToString();
A.Nested._4.Item1.Item1.ToString();
A.Nested._4.Item1.Item1[0].ToString(); // 3
A.Nested._4.Item1.Item2.ToString();
A.Nested._4.Item2.ToString(); // 4
A.Long._1.ToString(); // 5
A.Long._2.ToString();
A.Long._3.ToString(); // 6
A.Long._4.ToString();
A.Long._5.ToString(); // 7
A.Long._6.ToString();
A.Long._7.ToString(); // 8
A.Long._8.ToString();
A.Long._9.ToString(); // 9
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (5,9): warning CS8602: Dereference of a possibly null reference.
// A.Nested._1.Item1.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Nested._1.Item1").WithLocation(5, 9),
// (7,9): warning CS8602: Dereference of a possibly null reference.
// A.Nested._2.ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Nested._2").WithLocation(7, 9),
// (10,9): warning CS8602: Dereference of a possibly null reference.
// A.Nested._4.Item1.Item1[0].ToString(); // 3
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Nested._4.Item1.Item1[0]").WithLocation(10, 9),
// (12,9): warning CS8602: Dereference of a possibly null reference.
// A.Nested._4.Item2.ToString(); // 4
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Nested._4.Item2").WithLocation(12, 9),
// (13,9): warning CS8602: Dereference of a possibly null reference.
// A.Long._1.ToString(); // 5
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Long._1").WithLocation(13, 9),
// (15,9): warning CS8602: Dereference of a possibly null reference.
// A.Long._3.ToString(); // 6
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Long._3").WithLocation(15, 9),
// (17,9): warning CS8602: Dereference of a possibly null reference.
// A.Long._5.ToString(); // 7
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Long._5").WithLocation(17, 9),
// (19,9): warning CS8602: Dereference of a possibly null reference.
// A.Long._7.ToString(); // 8
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Long._7").WithLocation(19, 9),
// (21,9): warning CS8602: Dereference of a possibly null reference.
// A.Long._9.ToString(); // 9
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "A.Long._9").WithLocation(21, 9));
var type = comp2.GetMember<NamedTypeSymbol>("A");
Assert.Equal(
"((System.Object?, System.Object) _1, System.Object? _2, System.Object _3, ((System.Object?[], System.Object), System.Object?) _4)",
type.GetMember<FieldSymbol>("Nested").TypeWithAnnotations.ToTestDisplayString());
Assert.Equal(
"(System.Object? _1, System.Object _2, System.Object? _3, System.Object _4, System.Object? _5, System.Object _6, System.Object? _7, System.Object _8, System.Object? _9)",
type.GetMember<FieldSymbol>("Long").TypeWithAnnotations.ToTestDisplayString());
}
// DynamicAttribute and NullableAttribute formats should be aligned.
[Fact]
public void TuplesDynamic()
{
var source =
@"#pragma warning disable 0067
using System;
public interface I<T> { }
public class A<T> { }
public class B<T> :
A<(object? _1, (object _2, object? _3), object _4, object? _5, object _6, object? _7, object _8, object? _9)>,
I<(object? _1, (object _2, object? _3), object _4, object? _5, object _6, object? _7, object _8, object? _9)>
where T : A<(object? _1, (object _2, object? _3), object _4, object? _5, object _6, object? _7, object _8, object? _9)>
{
public (dynamic? _1, (object _2, dynamic? _3), object _4, dynamic? _5, object _6, dynamic? _7, object _8, dynamic? _9) Field;
public event EventHandler<(dynamic? _1, (object _2, dynamic? _3), object _4, dynamic? _5, object _6, dynamic? _7, object _8, dynamic? _9)> Event;
public (dynamic? _1, (object _2, dynamic? _3), object _4, dynamic? _5, object _6, dynamic? _7, object _8, dynamic? _9) Method(
(dynamic? _1, (object _2, dynamic? _3), object _4, dynamic? _5, object _6, dynamic? _7, object _8, dynamic? _9) arg) => arg;
public (dynamic? _1, (object _2, dynamic? _3), object _4, dynamic? _5, object _6, dynamic? _7, object _8, dynamic? _9) Property { get; set; }
}";
var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, validator: assembly =>
{
var reader = assembly.GetMetadataReader();
var typeDef = GetTypeDefinitionByName(reader, "B`1");
// Base type
checkAttributesNoDynamic(typeDef.GetCustomAttributes(), addOne: 0); // add one for A<T>
// Interface implementation
var interfaceImpl = reader.GetInterfaceImplementation(typeDef.GetInterfaceImplementations().Single());
checkAttributesNoDynamic(interfaceImpl.GetCustomAttributes(), addOne: 0); // add one for I<T>
// Type parameter constraint type
var typeParameter = reader.GetGenericParameter(typeDef.GetGenericParameters()[0]);
var constraint = reader.GetGenericParameterConstraint(typeParameter.GetConstraints()[0]);
checkAttributesNoDynamic(constraint.GetCustomAttributes(), addOne: 1); // add one for A<T>
// Field type
var field = typeDef.GetFields().Select(f => reader.GetFieldDefinition(f)).Single(f => reader.StringComparer.Equals(f.Name, "Field"));
checkAttributes(field.GetCustomAttributes());
// Event type
var @event = typeDef.GetEvents().Select(e => reader.GetEventDefinition(e)).Single(e => reader.StringComparer.Equals(e.Name, "Event"));
checkAttributes(@event.GetCustomAttributes(), addOne: 1); // add one for EventHandler<T>
// Method return type and parameter type
var method = typeDef.GetMethods().Select(m => reader.GetMethodDefinition(m)).Single(m => reader.StringComparer.Equals(m.Name, "Method"));
var parameters = method.GetParameters().Select(p => reader.GetParameter(p)).ToArray();
checkAttributes(parameters[0].GetCustomAttributes()); // return type
checkAttributes(parameters[1].GetCustomAttributes()); // parameter
// Property type
var property = typeDef.GetProperties().Select(p => reader.GetPropertyDefinition(p)).Single(p => reader.StringComparer.Equals(p.Name, "Property"));
checkAttributes(property.GetCustomAttributes());
void checkAttributes(CustomAttributeHandleCollection customAttributes, byte? addOne = null)
{
AssertAttributes(reader, customAttributes,
"MemberReference:Void System.Runtime.CompilerServices.DynamicAttribute..ctor(Boolean[])",
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])",
"MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
checkNullableAttribute(customAttributes, addOne);
}
void checkAttributesNoDynamic(CustomAttributeHandleCollection customAttributes, byte? addOne = null)
{
AssertAttributes(reader, customAttributes,
"MemberReference:Void System.Runtime.CompilerServices.TupleElementNamesAttribute..ctor(String[])",
"MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
checkNullableAttribute(customAttributes, addOne);
}
void checkNullableAttribute(CustomAttributeHandleCollection customAttributes, byte? addOne)
{
var customAttribute = GetAttributeByConstructorName(reader, customAttributes, "MethodDefinition:Void System.Runtime.CompilerServices.NullableAttribute..ctor(Byte[])");
var expectedBits = ImmutableArray.Create<byte>(0, 2, 0, 1, 2, 1, 2, 1, 2, 1, 0, 2);
if (addOne.HasValue)
{
expectedBits = ImmutableArray.Create(addOne.GetValueOrDefault()).Concat(expectedBits);
}
AssertEx.Equal(expectedBits, reader.ReadByteArray(customAttribute.Value));
}
});
var source2 =
@"class C
{
static void F(B<A<(object?, (object, object?), object, object?, object, object?, object, object?)>> b)
{
b.Field._8.ToString();
b.Field._9.ToString(); // 1
b.Method(default)._8.ToString();
b.Method(default)._9.ToString(); // 2
b.Property._8.ToString();
b.Property._9.ToString(); // 3
}
}";
var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { comp.EmitToImageReference() });
comp2.VerifyDiagnostics(
// (6,9): warning CS8602: Dereference of a possibly null reference.
// b.Field._9.ToString(); // 1
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Field._9").WithLocation(6, 9),
// (8,9): warning CS8602: Dereference of a possibly null reference.
// b.Method(default)._9.ToString(); // 2
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Method(default)._9").WithLocation(8, 9),
// (10,9): warning CS8602: Dereference of a possibly null reference.
// b.Property._9.ToString(); // 3
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Property._9").WithLocation(10, 9));
var type = comp2.GetMember<NamedTypeSymbol>("B");
Assert.Equal(
"A<(System.Object? _1, (System.Object _2, System.Object? _3), System.Object _4, System.Object? _5, System.Object _6, System.Object? _7, System.Object _8, System.Object? _9)>",
type.BaseTypeNoUseSiteDiagnostics.ToTestDisplayString());
Assert.Equal(
"I<(System.Object? _1, (System.Object _2, System.Object? _3), System.Object _4, System.Object? _5, System.Object _6, System.Object? _7, System.Object _8, System.Object? _9)>",
type.Interfaces()[0].ToTestDisplayString());
Assert.Equal(
"A<(System.Object? _1, (System.Object _2, System.Object? _3), System.Object _4, System.Object? _5, System.Object _6, System.Object? _7, System.Object _8, System.Object? _9)>",
type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString());
Assert.Equal(
"(dynamic? _1, (System.Object _2, dynamic? _3), System.Object _4, dynamic? _5, System.Object _6, dynamic? _7, System.Object _8, dynamic? _9)",
type.GetMember<FieldSymbol>("Field").TypeWithAnnotations.ToTestDisplayString());
Assert.Equal(
"System.EventHandler<(dynamic? _1, (System.Object _2, dynamic? _3), System.Object _4, dynamic? _5, System.Object _6, dynamic? _7, System.Object _8, dynamic? _9)>",
type.GetMember<EventSymbol>("Event").TypeWithAnnotations.ToTestDisplayString());
Assert.Equal(
"(dynamic? _1, (System.Object _2, dynamic? _3), System.Object _4, dynamic? _5, System.Object _6, dynamic? _7, System.Object _8, dynamic? _9) B<T>.Method((dynamic? _1, (System.Object _2, dynamic? _3), System.Object _4, dynamic? _5, System.Object _6, dynamic? _7, System.Object _8, dynamic? _9) arg)",
type.GetMember<MethodSymbol>("Method").ToTestDisplayString());
Assert.Equal(
"(dynamic? _1, (System.Object _2, dynamic? _3), System.Object _4, dynamic? _5, System.Object _6, dynamic? _7, System.Object _8, dynamic? _9) B<T>.Property { get; set; }",
type.GetMember<PropertySymbol>("Property").ToTestDisplayString());
}
[Fact]
[WorkItem(36934, "https://github.com/dotnet/roslyn/issues/36934")]
public void AttributeUsage()
{
var source =
@"#nullable enable
public class Program
{
public object? F;
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All));
CompileAndVerify(comp, symbolValidator: module =>
{
var attributeType = module.GlobalNamespace.GetMember<NamedTypeSymbol>("System.Runtime.CompilerServices.NullableAttribute");
AttributeUsageInfo attributeUsage = attributeType.GetAttributeUsageInfo();
Assert.False(attributeUsage.Inherited);
Assert.False(attributeUsage.AllowMultiple);
Assert.True(attributeUsage.HasValidAttributeTargets);
var expectedTargets = AttributeTargets.Class | AttributeTargets.Event | AttributeTargets.Field | AttributeTargets.GenericParameter | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue;
Assert.Equal(expectedTargets, attributeUsage.ValidTargets);
});
}
[Fact]
public void NullableFlags_Field_Exists()
{
var source =
@"public class C
{
public void F(object? x, object y, object z) { }
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
CompileAndVerify(comp, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("C");
var method = (MethodSymbol)type.GetMembers("F").Single();
var attributes = method.Parameters[0].GetAttributes();
AssertNullableAttribute(attributes);
var nullable = GetNullableAttribute(attributes);
var field = nullable.AttributeClass.GetField("NullableFlags");
Assert.NotNull(field);
Assert.Equal("System.Byte[]", field.TypeWithAnnotations.ToTestDisplayString());
});
}
[Fact]
public void NullableFlags_Field_Contains_ConstructorArguments_SingleByteConstructor()
{
var source =
@"
#nullable enable
using System;
using System.Linq;
public class C
{
public void F(object? x, object y, object z) { }
public static void Main()
{
var attribute = typeof(C).GetMethod(""F"").GetParameters()[0].GetCustomAttributes(true).Single(a => a.GetType().Name == ""NullableAttribute"");
var field = attribute.GetType().GetField(""NullableFlags"");
byte[] flags = (byte[])field.GetValue(attribute);
Console.Write($""{{ {string.Join("","", flags)} }}"");
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "{ 2 }", symbolValidator: module =>
{
var expected =
@"C
[NullableContext(1)] void F(System.Object? x, System.Object! y, System.Object! z)
[Nullable(2)] System.Object? x
System.Object! y
System.Object! z
";
AssertNullableAttributes(module, expected);
});
}
[Fact]
public void NullableFlags_Field_Contains_ConstructorArguments_ByteArrayConstructor()
{
var source =
@"
#nullable enable
using System;
using System.Linq;
public class C
{
public void F(Action<object?, Action<object, object?>?> c) { }
public static void Main()
{
var attribute = typeof(C).GetMethod(""F"").GetParameters()[0].GetCustomAttributes(true).Single(a => a.GetType().Name == ""NullableAttribute"");
var field = attribute.GetType().GetField(""NullableFlags"");
byte[] flags = (byte[])field.GetValue(attribute);
System.Console.Write($""{{ {string.Join("","", flags)} }}"");
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "{ 1,2,2,1,2 }", symbolValidator: module =>
{
var expected =
@"C
void F(System.Action<System.Object?, System.Action<System.Object!, System.Object?>?>! c)
[Nullable({ 1, 2, 2, 1, 2 })] System.Action<System.Object?, System.Action<System.Object!, System.Object?>?>! c
";
AssertNullableAttributes(module, expected);
});
}
[Fact]
[WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")]
public void PropertyAccessorWithNullableContextAttribute_01()
{
var source =
@"#nullable enable
public class A
{
public object? this[object x, object? y] => null;
public static A F(object x) => new A();
public static A F(object x, object? y) => new A();
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] A
A! F(System.Object! x)
System.Object! x
A! F(System.Object! x, System.Object? y)
System.Object! x
[Nullable(2)] System.Object? y
A()
[Nullable(2)] System.Object? this[System.Object! x, System.Object? y] { get; }
[Nullable(1)] System.Object! x
System.Object? y
[NullableContext(2)] System.Object? this[System.Object! x, System.Object? y].get
[Nullable(1)] System.Object! x
System.Object? y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
[WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")]
public void PropertyAccessorWithNullableContextAttribute_02()
{
var source =
@"#nullable enable
public class A
{
public object? this[object x, object? y] { set { } }
public static A F(object x) => new A();
public static A F(object x, object? y) => new A();
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(1)] [Nullable(0)] A
A! F(System.Object! x)
System.Object! x
A! F(System.Object! x, System.Object? y)
System.Object! x
[Nullable(2)] System.Object? y
A()
[Nullable(2)] System.Object? this[System.Object! x, System.Object? y] { set; }
[Nullable(1)] System.Object! x
System.Object? y
[NullableContext(2)] void this[System.Object! x, System.Object? y].set
[Nullable(1)] System.Object! x
System.Object? y
System.Object? value
";
AssertNullableAttributes(comp, expected);
}
[Fact]
[WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")]
public void PropertyAccessorWithNullableContextAttribute_03()
{
var source =
@"#nullable enable
public class A
{
public object this[object? x, object y] => null;
public static A? F0;
public static A? F1;
public static A? F2;
public static A? F3;
public static A? F4;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(2)] [Nullable(0)] A
A? F0
A? F1
A? F2
A? F3
A? F4
A()
[Nullable(1)] System.Object! this[System.Object? x, System.Object! y] { get; }
[Nullable(2)] System.Object? x
System.Object! y
[NullableContext(1)] System.Object! this[System.Object? x, System.Object! y].get
[Nullable(2)] System.Object? x
System.Object! y
";
AssertNullableAttributes(comp, expected);
}
[Fact]
[WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")]
public void PropertyAccessorWithNullableContextAttribute_04()
{
var source =
@"#nullable enable
public class A
{
public object this[object? x, object y] { set { } }
public static A? F0;
public static A? F1;
public static A? F2;
public static A? F3;
public static A? F4;
}";
var comp = CreateCompilation(source);
var expected =
@"[NullableContext(2)] [Nullable(0)] A
A? F0
A? F1
A? F2
A? F3
A? F4
A()
[Nullable(1)] System.Object! this[System.Object? x, System.Object! y] { set; }
[Nullable(2)] System.Object? x
System.Object! y
[NullableContext(1)] void this[System.Object? x, System.Object! y].set
[Nullable(2)] System.Object? x
System.Object! y
System.Object! value
";
AssertNullableAttributes(comp, expected);
}
private static MetadataReference GetAnnotationUtilsLibrary()
{
var source =
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
public static class Utils
{
public static string GetAnnotations(this Delegate d)
{
var method = d.Method;
var builder = new StringBuilder();
var contextValue = GetContextValue(method);
GetTypeAndAnnotation(builder, method.ReturnType, method.ReturnParameter.GetCustomAttributes(), contextValue);
builder.Append("" "");
builder.Append(method.DeclaringType.FullName);
builder.Append(""."");
builder.Append(method.Name);
builder.Append(""("");
foreach (var parameter in method.GetParameters())
{
GetTypeAndAnnotation(builder, parameter.ParameterType, parameter.GetCustomAttributes(), contextValue);
builder.Append("" "");
builder.Append(parameter.Name);
}
builder.Append("")"");
return builder.ToString();
}
private static int GetContextValue(MemberInfo member)
{
if (GetAttribute(member.GetCustomAttributes(), ""System.Runtime.CompilerServices.NullableContextAttribute"") is { } attribute)
{
var field = attribute.GetType().GetField(""Flag"");
return (int)(byte)field.GetValue(attribute);
}
if (member.DeclaringType is { } declaringType)
{
return GetContextValue(declaringType);
}
return 0;
}
private static void GetTypeAndAnnotation(StringBuilder builder, Type type, IEnumerable<Attribute> attributes, int contextValue)
{
builder.Append(type.FullName);
if (type.IsValueType)
{
return;
}
int value = contextValue;
if (GetAttribute(attributes, ""System.Runtime.CompilerServices.NullableAttribute"") is { } attribute)
{
var field = attribute.GetType().GetField(""NullableFlags"");
var bytes = (byte[])field.GetValue(attribute);
value = bytes.SingleOrDefault();
}
switch (value)
{
case 1:
builder.Append(""!"");
break;
case 2:
builder.Append(""?"");
break;
}
}
private static Attribute GetAttribute(IEnumerable<Attribute> attributes, string typeName)
{
return attributes.SingleOrDefault(attr => attr.GetType().FullName == typeName);
}
}";
var comp = CreateCompilation(source);
return comp.EmitToImageReference();
}
[Fact]
[WorkItem(55254, "https://github.com/dotnet/roslyn/issues/55254")]
public void LambdaAttributes_01()
{
var source =
@"#nullable enable
using System;
var dump = static (string s, Delegate d) => d.GetAnnotations();
Console.WriteLine(dump(""/"", (string? name) => $""Inline lambda {name}""));
Console.WriteLine(dump(""/o"", (string? name) => { }));
";
var library = GetAnnotationUtilsLibrary();
CompileAndVerify(source, options: TestOptions.ReleaseExe, references: new[] { library }, expectedOutput:
@"System.String Program+<>c.<<Main>$>b__0_1(System.String? name)
System.Void Program+<>c.<<Main>$>b__0_2(System.String? name)
");
}
[Fact]
[WorkItem(55254, "https://github.com/dotnet/roslyn/issues/55254")]
public void LambdaAttributes_02()
{
var source =
@"#nullable enable
using System;
var dump = static (string s, Delegate d) => d.GetAnnotations();
Console.WriteLine(dump(""/"", (string name) => $""Inline lambda {name}""));
Console.WriteLine(dump(""/o"", (string name) => { }));
";
var library = GetAnnotationUtilsLibrary();
CompileAndVerify(source, options: TestOptions.ReleaseExe, references: new[] { library }, expectedOutput:
@"System.String Program+<>c.<<Main>$>b__0_1(System.String! name)
System.Void Program+<>c.<<Main>$>b__0_2(System.String! name)
");
}
[Fact]
[WorkItem(55254, "https://github.com/dotnet/roslyn/issues/55254")]
public void LambdaAttributes_03()
{
var source =
@"#nullable enable
using System;
var dump = static (string s, Delegate d) => d.GetAnnotations();
Console.WriteLine(dump(""/"",
#nullable disable
(string name) =>
#nullable disable
$""Inline lambda {name}""));
Console.WriteLine(dump(""/o"",
#nullable disable
(string name) =>
#nullable disable
{ }));
";
var library = GetAnnotationUtilsLibrary();
CompileAndVerify(source, options: TestOptions.ReleaseExe, references: new[] { library }, expectedOutput:
@"System.String Program+<>c.<<Main>$>b__0_1(System.String name)
System.Void Program+<>c.<<Main>$>b__0_2(System.String name)
");
}
[Fact]
[WorkItem(55254, "https://github.com/dotnet/roslyn/issues/55254")]
public void LambdaAttributes_04()
{
var source =
@"using System;
class Program
{
static void Report(Delegate d) => Console.WriteLine(d.GetAnnotations());
static void Main()
{
#nullable enable
Report((string? s) => { });
object? f(string s) => null;
Report(f);
}
}";
var library = GetAnnotationUtilsLibrary();
CompileAndVerify(source, options: TestOptions.ReleaseExe, references: new[] { library }, expectedOutput:
@"System.Void Program+<>c.<Main>b__1_0(System.String? s)
System.Object? Program.<Main>g__f|1_1(System.String! s)
");
}
private static void AssertNoNullableAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
AssertAttributes(attributes);
}
private static void AssertNullableAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
AssertAttributes(attributes, "System.Runtime.CompilerServices.NullableAttribute");
}
private static void AssertAttributes(ImmutableArray<CSharpAttributeData> attributes, params string[] expectedNames)
{
var actualNames = attributes.Select(a => a.AttributeClass.ToTestDisplayString()).ToArray();
AssertEx.SetEqual(expectedNames, actualNames);
}
private static void AssertNoNullableAttributes(CSharpCompilation comp)
{
var image = comp.EmitToArray();
using (var reader = new PEReader(image))
{
var metadataReader = reader.GetMetadataReader();
var attributes = metadataReader.GetCustomAttributeRows().Select(metadataReader.GetCustomAttributeName).ToArray();
Assert.False(attributes.Contains("NullableContextAttribute"));
Assert.False(attributes.Contains("NullableAttribute"));
}
}
private static CSharpAttributeData GetNullableAttribute(ImmutableArray<CSharpAttributeData> attributes)
{
return attributes.Single(a => a.AttributeClass.ToTestDisplayString() == "System.Runtime.CompilerServices.NullableAttribute");
}
private static TypeDefinition GetTypeDefinitionByName(MetadataReader reader, string name)
{
return reader.GetTypeDefinition(reader.TypeDefinitions.Single(h => reader.StringComparer.Equals(reader.GetTypeDefinition(h).Name, name)));
}
private static string GetAttributeConstructorName(MetadataReader reader, CustomAttributeHandle handle)
{
return reader.Dump(reader.GetCustomAttribute(handle).Constructor);
}
private static CustomAttribute GetAttributeByConstructorName(MetadataReader reader, CustomAttributeHandleCollection handles, string name)
{
return reader.GetCustomAttribute(handles.FirstOrDefault(h => GetAttributeConstructorName(reader, h) == name));
}
private static void AssertAttributes(MetadataReader reader, CustomAttributeHandleCollection handles, params string[] expectedNames)
{
var actualNames = handles.Select(h => GetAttributeConstructorName(reader, h)).ToArray();
AssertEx.SetEqual(expectedNames, actualNames);
}
private void AssertNullableAttributes(CSharpCompilation comp, string expected)
{
CompileAndVerify(comp, symbolValidator: module => AssertNullableAttributes(module, expected));
}
private static void AssertNullableAttributes(ModuleSymbol module, string expected)
{
var actual = NullableAttributesVisitor.GetString((PEModuleSymbol)module);
AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual);
}
}
}
| 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/Test/Emit/Attributes/AttributeTests_RefReadOnly.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_RefReadOnly : CSharpTestBase
{
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Method()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
class Test
{
public ref readonly int M(in int x) { return ref x; }
}
";
CompileAndVerify(text, verify: Verification.Fails, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
var peModule = (PEModuleSymbol)module;
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)method).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEParameterSymbol)parameter).Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Public);
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Method_Parameter()
{
var text = @"
class Test
{
public void M(in int x) { }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
var peModule = (PEModuleSymbol)module;
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEParameterSymbol)parameter).Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_Method_ReturnType()
{
var text = @"
class Test
{
private int x;
public ref readonly int M() { return ref x; }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_Method()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
class Test
{
public ref readonly int M(in int x) { return ref x; }
}
";
CompileAndVerify(codeB, verify: Verification.Fails, references: new[] { referenceA }, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Operator()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
struct Test
{
public static int operator +(in Test x, in Test y) { return 0; }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("op_Addition");
Assert.Equal(2, method.ParameterCount);
foreach (var parameter in method.Parameters)
{
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
}
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Operator_Parameter()
{
var text = @"
struct Test
{
public static int operator +(in Test x, in Test y) { return 0; }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("op_Addition");
Assert.Equal(2, method.ParameterCount);
foreach (var parameter in method.Parameters)
{
Assert.Empty(parameter.GetAttributes());
}
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_Operator_Method()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
struct Test
{
public static int operator +(in Test x, in Test y) { return 0; }
}
";
CompileAndVerify(codeB, references: new[] { referenceA }, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("op_Addition");
Assert.Equal(2, method.ParameterCount);
foreach (var parameter in method.Parameters)
{
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
}
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Constructor()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
class Test
{
public Test(in int x) { }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod(".ctor").Parameters.Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Constructor_Parameter()
{
var text = @"
class Test
{
public Test(in int x) { }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod(".ctor").Parameters.Single();
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_Constructor_Method()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
class Test
{
public Test(in int x) { }
}
";
CompileAndVerify(codeB, references: new[] { referenceA }, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod(".ctor").Parameters.Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Property()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
class Test
{
private int x = 0;
public ref readonly int P1 { get { return ref x; } }
public ref readonly int P2 => ref x;
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Test");
AssertProperty(type.GetProperty("P1"));
AssertProperty(type.GetProperty("P2"));
void AssertProperty(PropertySymbol property)
{
Assert.Equal(RefKind.RefReadOnly, property.RefKind);
Assert.True(property.ReturnsByRefReadonly);
Assert.Empty(property.GetAttributes());
}
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_Property()
{
var text = @"
class Test
{
private int x = 0;
public ref readonly int P1 { get { return ref x; } }
public ref readonly int P2 => ref x;
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Test");
AssertProperty(type.GetProperty("P1"));
AssertProperty(type.GetProperty("P2"));
void AssertProperty(PropertySymbol property)
{
Assert.Equal(RefKind.RefReadOnly, property.RefKind);
Assert.True(property.ReturnsByRefReadonly);
Assert.Empty(property.GetAttributes());
}
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_Property()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
class Test
{
private int x = 0;
public ref readonly int P1 { get { return ref x; } }
public ref readonly int P2 => ref x;
}
";
CompileAndVerify(codeB, references: new[] { referenceA }, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Test");
AssertProperty(type.GetProperty("P1"));
AssertProperty(type.GetProperty("P2"));
void AssertProperty(PropertySymbol property)
{
Assert.Equal(RefKind.RefReadOnly, property.RefKind);
Assert.True(property.ReturnsByRefReadonly);
Assert.Empty(property.GetAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
}
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Indexer()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
class Test
{
public ref readonly int this[in int x] { get { return ref x; } }
}
";
CompileAndVerify(text, verify: Verification.Fails, symbolValidator: module =>
{
var indexer = module.ContainingAssembly.GetTypeByMetadataName("Test").GetProperty("this[]");
Assert.Equal(RefKind.RefReadOnly, indexer.RefKind);
Assert.True(indexer.ReturnsByRefReadonly);
var parameter = indexer.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(indexer.GetAttributes());
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Indexer_Parameter()
{
var text = @"
class Test
{
public int this[in int x] { get { return x; } }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetProperty("this[]").GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_Indexer_ReturnType()
{
var text = @"
class Test
{
private int x;
public ref readonly int this[int p] { get { return ref x; } }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var indexer = module.ContainingAssembly.GetTypeByMetadataName("Test").GetProperty("this[]");
Assert.Equal(RefKind.RefReadOnly, indexer.RefKind);
Assert.True(indexer.ReturnsByRefReadonly);
Assert.Empty(indexer.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_Indexer()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
class Test
{
public ref readonly int this[in int x] { get { return ref x; } }
}
";
CompileAndVerify(codeB, verify: Verification.Fails, references: new[] { referenceA }, symbolValidator: module =>
{
var indexer = module.ContainingAssembly.GetTypeByMetadataName("Test").GetProperty("this[]");
Assert.Equal(RefKind.RefReadOnly, indexer.RefKind);
Assert.True(indexer.ReturnsByRefReadonly);
var parameter = indexer.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(indexer.GetAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Delegate()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
public delegate ref readonly int D(in int x);
";
CompileAndVerify(text, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod;
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Delegate_Parameter()
{
var text = @"
public delegate void D(in int x);
";
CompileAndVerify(text, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_Delegate_ReturnType()
{
var text = @"
public delegate ref readonly int D();
";
CompileAndVerify(text, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod;
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_Delegate()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
public delegate ref readonly int D(in int x);
";
CompileAndVerify(codeB, references: new[] { referenceA }, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod;
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_LocalFunctions()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
public class Test
{
public void M()
{
ref readonly int Inner(in int x)
{
return ref x;
}
}
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, verify: Verification.Fails, options: options, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__Inner|0_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_LocalFunctions_Parameters()
{
var text = @"
public class Test
{
public void M()
{
void Inner(in int x) { }
}
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, options: options, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__Inner|0_0").GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_LocalFunctions_ReturnType()
{
var text = @"
public class Test
{
private int x;
public void M()
{
ref readonly int Inner()
{
return ref x;
}
}
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, verify: Verification.Fails, options: options, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__Inner|1_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_LocalFunctions()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
public class Test
{
public void M()
{
ref readonly int Inner(in int x)
{
return ref x;
}
}
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(codeB, verify: Verification.Fails, references: new[] { referenceA }, options: options, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__Inner|0_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Lambda()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
delegate ref readonly int D(in int x);
class Test
{
public void M1()
{
M2((in int x) => ref x);
}
public void M2(D value) { }
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, verify: Verification.Fails, options: options, symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>("Test.<>c.<M1>b__0_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Lambda_Parameter()
{
var text = @"
delegate void D(in int x);
class Test
{
public void M1()
{
M2((in int x) => {});
}
public void M2(D value) { }
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, options: options, symbolValidator: module =>
{
var parameter = module.GlobalNamespace.GetMember<MethodSymbol>("Test.<>c.<M1>b__0_0").GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_Lambda_ReturnType()
{
var text = @"
delegate ref readonly int D();
class Test
{
private int x;
public void M1()
{
M2(() => ref x);
}
public void M2(D value) { }
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, options: options, symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>("Test.<M1>b__1_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_Lambda()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
delegate ref readonly int D(in int x);
class Test
{
public void M1()
{
M2((in int x) => ref x);
}
public void M2(D value) { }
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(codeB, verify: Verification.Fails, options: options, references: new[] { referenceA }, symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>("Test.<>c.<M1>b__0_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Delegates()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
[IsReadOnly]
public delegate ref readonly int D([IsReadOnly]in int x);
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (4,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(4, 2),
// (5,37): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// public delegate ref readonly int D([IsReadOnly]in int x);
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(5, 37));
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Types()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
[IsReadOnly]
public class Test
{
}
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (4,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(4, 2));
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Fields()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
public class Test
{
[IsReadOnly]
private int x = 0;
public int X => x;
}
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (6,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(6, 6));
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Properties()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
public class Test
{
private int x = 0;
[IsReadOnly]
public ref readonly int Property => ref x;
}
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (8,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(8, 6));
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Methods()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
public class Test
{
[IsReadOnly]
[return: IsReadOnly]
public ref readonly int Method([IsReadOnly]in int x)
{
return ref x;
}
}
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (6,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(6, 6),
// (7,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [return: IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(7, 14),
// (8,37): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// public ref readonly int Method([IsReadOnly]in int x)
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(8, 37));
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Indexers()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
public class Test
{
[IsReadOnly]
public ref readonly int this[[IsReadOnly]in int x] { get { return ref x; } }
}
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (6,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(6, 6),
// (7,35): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// public ref readonly int this[[IsReadOnly]in int x] { get { return ref x; } }
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(7, 35));
}
[Fact]
public void UserReferencingEmbeddedAttributeShouldResultInAnError()
{
var code = @"
[Embedded]
public class Test
{
public ref readonly int M(in int p) => ref p;
}";
CreateCompilation(code).VerifyDiagnostics(
// (2,2): error CS0246: The type or namespace name 'EmbeddedAttribute' could not be found (are you missing a using directive or an assembly reference?)
// [Embedded]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Embedded").WithArguments("EmbeddedAttribute").WithLocation(2, 2),
// (2,2): error CS0246: The type or namespace name 'Embedded' could not be found (are you missing a using directive or an assembly reference?)
// [Embedded]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Embedded").WithArguments("Embedded").WithLocation(2, 2));
}
[Fact]
public void UserReferencingIsReadOnlyAttributeShouldResultInAnError()
{
var code = @"
[IsReadOnly]
public class Test
{
public ref readonly int M(in int p) => ref p;
}";
CreateCompilation(code).VerifyDiagnostics(
// (2,2): error CS0246: The type or namespace name 'IsReadOnlyAttribute' could not be found (are you missing a using directive or an assembly reference?)
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsReadOnly").WithArguments("IsReadOnlyAttribute").WithLocation(2, 2),
// (2,2): error CS0246: The type or namespace name 'IsReadOnly' could not be found (are you missing a using directive or an assembly reference?)
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsReadOnly").WithArguments("IsReadOnly").WithLocation(2, 2));
}
[Fact]
public void TypeReferencingAnotherTypeThatUsesAPublicAttributeFromAThirdNotReferencedAssemblyShouldGenerateItsOwn()
{
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
var code1 = CreateCompilation(@"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}");
var code2 = CreateCompilation(@"
public class Test1
{
public static ref readonly int M(in int p) => ref p;
}", references: new[] { code1.ToMetadataReference() }, options: options);
CompileAndVerify(code2, verify: Verification.Fails, symbolValidator: module =>
{
// IsReadOnly is not generated in assembly
var isReadOnlyAttributeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(isReadOnlyAttributeName));
});
var code3 = CreateCompilation(@"
public class Test2
{
public static ref readonly int M(in int p) => ref Test1.M(p);
}", references: new[] { code2.ToMetadataReference() }, options: options);
CompileAndVerify(code3, symbolValidator: module =>
{
// IsReadOnly is generated in assembly
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName);
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.IsReadOnlyAttribute.FullName);
});
}
[Fact]
public void BuildingAModuleRequiresIsReadOnlyAttributeToBeThere_Missing_SourceMethod()
{
var code = @"
public class Test
{
public void M(in int x) { }
}";
CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics(
// (4,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// public void M(in int x) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(4, 19));
}
[Fact]
public void BuildingAModuleRequiresIsReadOnlyAttributeToBeThere_Missing_SourceMethod_MultipleLocations()
{
var code = @"
public class Test
{
public void M1(in int x) { }
public void M2(in int x) { }
}";
CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics(
// (4,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// public void M1(in int x) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(4, 20),
// (5,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// public void M2(in int x) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(5, 20));
}
[Fact]
public void BuildingAModuleRequiresIsReadOnlyAttributeToBeThere_Missing_LocalFunctions()
{
var code = @"
public class Test
{
public void Parent()
{
void child(in int p) { }
int x = 0;
child(x);
}
}";
CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics(
// (6,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// void child(in int p) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int p").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(6, 20));
}
[Fact]
public void BuildingAModuleRequiresIsReadOnlyAttributeToBeThere_InAReference()
{
var reference = CreateCompilation(@"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}").ToMetadataReference();
var code = @"
public class Test
{
public void M(in int x) { }
}";
CompileAndVerify(code, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule, symbolValidator: module =>
{
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void ReferencingAnEmbeddedIsReadOnlyAttributeDoesNotUseIt_InternalsVisible()
{
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
var code1 = @"
[assembly:System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Assembly2"")]
public class Test1
{
public static ref readonly int M(in int p) => ref p;
}";
var comp1 = CompileAndVerify(code1, options: options, verify: Verification.Fails, symbolValidator: module =>
{
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName);
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.IsReadOnlyAttribute.FullName);
});
var code2 = @"
public class Test2
{
public static ref readonly int M(in int p) => ref Test1.M(p);
}";
CompileAndVerify(code2, options: options.WithModuleName("Assembly2"), references: new[] { comp1.Compilation.ToMetadataReference() }, symbolValidator: module =>
{
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName);
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.IsReadOnlyAttribute.FullName);
});
}
[Fact]
public void IfIsReadOnlyAttributeIsDefinedThenEmbeddedIsNotGenerated()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
class Test
{
public ref readonly int M(in int x) { return ref x; }
}
";
CompileAndVerify(text, verify: Verification.Fails, symbolValidator: module =>
{
Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName));
});
}
[Fact]
public void IsReadOnlyAttributeExistsWithWrongConstructorSignature_NetModule()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
class Test
{
public void M(in int x) { }
}";
CreateCompilation(text, options: TestOptions.ReleaseModule).VerifyDiagnostics(
// (11,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public void M(in int x) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 19));
}
[Fact]
public void IsReadOnlyAttributeExistsWithWrongConstructorSignature_Assembly()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
class Test
{
public void M(in int x) { }
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (11,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public void M(in int x) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 19));
}
[Fact]
public void IsReadOnlyAttributeExistsWithWrongConstructorSignature_PrivateConstructor()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
private IsReadOnlyAttribute() { }
}
}
class Test
{
public void M(in int x) { }
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (11,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public void M(in int x) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 19));
}
[Fact]
public void IsReadOnlyAttributesAreNotPortedInNoPia()
{
var comAssembly = CreateCompilationWithMscorlib40(@"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""test.dll"")]
[assembly: Guid(""9784f9a1-594a-4351-8f69-0fd2d2df03d3"")]
[ComImport()]
[Guid(""9784f9a1-594a-4351-8f69-0fd2d2df03d3"")]
public interface Test
{
ref readonly int Property { get; }
ref readonly int Method(in int x);
}");
CompileAndVerify(comAssembly, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Test");
var property = type.GetMember<PEPropertySymbol>("Property");
Assert.NotNull(property);
Assert.Empty(property.GetAttributes());
var method = type.GetMethod("Method");
Assert.NotNull(method);
Assert.Empty(method.GetReturnTypeAttributes());
var parameter = method.Parameters.Single();
Assert.NotNull(parameter);
Assert.Empty(parameter.GetAttributes());
});
var code = @"
class User
{
public void M(Test p)
{
p.Method(p.Property);
}
}";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
var compilation_CompilationReference = CreateCompilationWithMscorlib40(code, options: options, references: new[] { comAssembly.ToMetadataReference(embedInteropTypes: true) });
CompileAndVerify(compilation_CompilationReference, symbolValidator: symbolValidator);
var compilation_BinaryReference = CreateCompilationWithMscorlib40(code, options: options, references: new[] { comAssembly.EmitToImageReference(embedInteropTypes: true) });
CompileAndVerify(compilation_BinaryReference, symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
// No attribute is copied
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
var type = module.ContainingAssembly.GetTypeByMetadataName("Test");
var property = type.GetMember<PEPropertySymbol>("Property");
Assert.NotNull(property);
Assert.Empty(property.GetAttributes());
var method = type.GetMethod("Method");
Assert.NotNull(method);
Assert.Empty(method.GetReturnTypeAttributes());
var parameter = method.Parameters.Single();
Assert.NotNull(parameter);
Assert.Empty(parameter.GetAttributes());
}
}
[Fact]
public void TryingToBindFromSemanticModelDoesNotPolluteCompilation_Lambdas_Parameters()
{
var reference = CreateCompilation(@"
public delegate int D (in int x);
").VerifyEmitDiagnostics();
Assert.True(NeedsGeneratedIsReadOnlyAttribute(reference));
var compilation = CreateCompilation(@"
public class Test
{
public void Process(D lambda) { }
void User()
{
}
}", references: new[] { reference.ToMetadataReference() });
compilation.VerifyEmitDiagnostics();
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false);
var userFunction = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(method => method.Identifier.Text == "User");
var position = userFunction.Body.CloseBraceToken.Position;
var newInvocation = SyntaxFactory.ParseExpression("Process((in int x) => x)");
var result = model.GetSpeculativeSymbolInfo(position, newInvocation, SpeculativeBindingOption.BindAsExpression);
Assert.NotNull(result.Symbol);
Assert.Equal(CandidateReason.None, result.CandidateReason);
Assert.Empty(result.CandidateSymbols);
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
}
[Fact]
public void TryingToBindFromSemanticModelDoesNotPolluteCompilation_Lambdas_ReturnTypes()
{
var reference = CreateCompilation(@"
public delegate ref readonly int D ();
").VerifyEmitDiagnostics();
Assert.True(NeedsGeneratedIsReadOnlyAttribute(reference));
var compilation = CreateCompilation(@"
public class Test
{
private int x;
public void Process(D lambda)
{
x = lambda();
}
void User()
{
}
}", references: new[] { reference.ToMetadataReference() });
compilation.VerifyEmitDiagnostics();
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false);
var userFunction = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(method => method.Identifier.Text == "User");
var position = userFunction.Body.CloseBraceToken.Position;
var newInvocation = SyntaxFactory.ParseExpression("Process(() => ref x)");
var result = model.GetSpeculativeSymbolInfo(position, newInvocation, SpeculativeBindingOption.BindAsExpression);
Assert.NotNull(result.Symbol);
Assert.Equal(CandidateReason.None, result.CandidateReason);
Assert.Empty(result.CandidateSymbols);
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
}
[Fact]
public void TryingToBindFromSemanticModelDoesNotPolluteCompilation_LocalFunctions_Parameters()
{
var compilation = CreateCompilation(@"
public class Test
{
void User()
{
}
}");
compilation.VerifyEmitDiagnostics();
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false);
var userFunction = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(method => method.Identifier.Text == "User");
var position = userFunction.Body.CloseBraceToken.Position;
var localfunction = SyntaxFactory.ParseStatement("int localFunction(in int x) { return x; }");
Assert.True(model.TryGetSpeculativeSemanticModel(position, localfunction, out var newModel));
var localFunctionSymbol = newModel.GetDeclaredSymbol(localfunction);
Assert.NotNull(localFunctionSymbol);
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
}
[Fact]
public void TryingToBindFromSemanticModelDoesNotPolluteCompilation_LocalFunctions_ReturnTypes()
{
var compilation = CreateCompilation(@"
public class Test
{
void User()
{
}
}");
compilation.VerifyEmitDiagnostics();
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false);
var userFunction = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(method => method.Identifier.Text == "User");
var position = userFunction.Body.CloseBraceToken.Position;
var localfunction = SyntaxFactory.ParseStatement("ref readonly int localFunction(int x) { return ref x; }");
Assert.True(model.TryGetSpeculativeSemanticModel(position, localfunction, out var newModel));
var localFunctionSymbol = newModel.GetDeclaredSymbol(localfunction);
Assert.NotNull(localFunctionSymbol);
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
}
[Fact]
public void TryingPossibleBindingsForRefReadOnlyDoesNotPolluteCompilationForInvalidOnes()
{
var reference = CreateCompilation(@"
public delegate ref readonly int D1 ();
public delegate ref int D2 ();
").VerifyEmitDiagnostics();
Assert.True(NeedsGeneratedIsReadOnlyAttribute(reference));
var compilation = CreateCompilation(@"
public class Test
{
public void Process(D1 lambda, int x) { }
public void Process(D2 lambda, byte x) { }
void User()
{
byte byteVar = 0;
Process(() => { throw null; }, byteVar);
}
}", references: new[] { reference.ToMetadataReference() });
compilation.VerifyEmitDiagnostics();
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
}
[Fact]
public void RefReadOnlyErrorsForLambdasDoNotPolluteCompilationDeclarationsDiagnostics()
{
var reference = CreateCompilation(@"
public delegate int D (in int x);
").EmitToImageReference();
var code = @"
public class Test
{
public void Process(D lambda) { }
void User()
{
Process((in int p) => p);
}
}";
var compilation = CreateCompilation(code, options: TestOptions.ReleaseModule, references: new[] { reference });
compilation.DeclarationDiagnostics.Verify();
compilation.VerifyDiagnostics(
// (8,18): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// Process((in int p) => p);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int p").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(8, 18));
}
[Fact]
public void RefReadOnlyErrorsForLocalFunctionsDoNotPolluteCompilationDeclarationsDiagnostics()
{
var code = @"
public class Test
{
private int x = 0;
void User()
{
void local(in int x) { }
local(x);
}
}";
var compilation = CreateCompilation(code, options: TestOptions.ReleaseModule);
compilation.DeclarationDiagnostics.Verify();
compilation.VerifyDiagnostics(
// (7,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// void local(in int x) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(7, 20));
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_Class_NoParent()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute
{
private int value;
public ref readonly int Method(in int x) => ref value;
public static int operator +(in IsReadOnlyAttribute x, in IsReadOnlyAttribute y) => 0;
public ref readonly int Property => ref value;
public ref readonly int this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var isReadOnlyAttributeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(isReadOnlyAttributeName);
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var @operator = type.GetMethod("op_Addition");
Assert.Empty(@operator.Parameters[0].GetAttributes());
Assert.Empty(@operator.Parameters[1].GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_Class_CorrectParent()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
private int value;
public ref readonly int Method(in int x) => ref value;
public static int operator +(in IsReadOnlyAttribute x, in IsReadOnlyAttribute y) => 0;
public ref readonly int Property => ref value;
public ref readonly int this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var isReadOnlyAttributeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(isReadOnlyAttributeName);
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var @operator = type.GetMethod("op_Addition");
Assert.Empty(@operator.Parameters[0].GetAttributes());
Assert.Empty(@operator.Parameters[1].GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ClassInherit()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
}
}
public class Child : System.Runtime.CompilerServices.IsReadOnlyAttribute
{
private int value;
public ref readonly int Method(in int x) => ref value;
public static int operator +(in Child x, in Child y) => 0;
public ref readonly int Property => ref value;
public ref readonly int this[in int x] => ref value;
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Child");
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var @operator = type.GetMethod("op_Addition");
Assert.Empty(@operator.Parameters[0].GetAttributes());
Assert.Empty(@operator.Parameters[1].GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ClassOverride_SameAssembly()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public abstract class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute() { }
public abstract ref readonly int Method(in int x);
public abstract ref readonly int Property { get; }
public abstract ref readonly int this[in int x] { get; }
}
}
public class Child : System.Runtime.CompilerServices.IsReadOnlyAttribute
{
private int value;
public override ref readonly int Method(in int x) => ref value;
public override ref readonly int Property => ref value;
public override ref readonly int this[in int x] => ref value;
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Child");
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ClassOverride_ExternalAssembly()
{
var reference = CreateCompilation(@"
namespace System.Runtime.CompilerServices
{
public abstract class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute() { }
public abstract ref readonly int Method(in int x);
public abstract ref readonly int Property { get; }
public abstract ref readonly int this[in int x] { get; }
}
}", assemblyName: "testRef").ToMetadataReference();
var code = @"
public class Child : System.Runtime.CompilerServices.IsReadOnlyAttribute
{
private int value;
public override ref readonly int Method(in int x) => ref value;
public override ref readonly int Property => ref value;
public override ref readonly int this[in int x] => ref value;
}";
CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Child");
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ClassOverridden_SameAssembly()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public abstract class Parent : System.Attribute
{
public abstract ref readonly int Method(in int x);
public abstract ref readonly int Property { get; }
public abstract ref readonly int this[in int x] { get; }
}
public class IsReadOnlyAttribute : Parent
{
private int value;
public override ref readonly int Method(in int x) => ref value;
public override ref readonly int Property => ref value;
public override ref readonly int this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var typeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(typeName);
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ClassOverridden_ExternalAssembly()
{
var reference = CreateCompilation(@"
namespace System.Runtime.CompilerServices
{
public abstract class Parent : System.Attribute
{
public abstract ref readonly int Method(in int x);
public abstract ref readonly int Property { get; }
public abstract ref readonly int this[in int x] { get; }
}
}").ToMetadataReference();
var code = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : Parent
{
private int value;
public override ref readonly int Method(in int x) => ref value;
public override ref readonly int Property => ref value;
public override ref readonly int this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module =>
{
var typeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(typeName);
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_Class_WrongParent()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public class TestParent { }
public class IsReadOnlyAttribute : TestParent
{
private int value;
public ref readonly int Method(in int x) => ref value;
public static int operator +(in IsReadOnlyAttribute x, in IsReadOnlyAttribute y) => 0;
public ref readonly int Property => ref value;
public ref readonly int this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var isReadOnlyAttributeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(isReadOnlyAttributeName);
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var @operator = type.GetMethod("op_Addition");
Assert.Empty(@operator.Parameters[0].GetAttributes());
Assert.Empty(@operator.Parameters[1].GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_Interface()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public interface IsReadOnlyAttribute
{
ref readonly int Method(in int x);
}
}";
CreateCompilation(code).VerifyEmitDiagnostics(
// (6,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// ref readonly int Method(in int x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(6, 9),
// (6,33): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// ref readonly int Method(in int x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(6, 33));
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ExplicitInterfaceImplementation_SameAssembly()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public interface ITest
{
ref readonly int Method(in int x);
ref readonly int Property { get; }
ref readonly int this[in int x] { get; }
}
public class IsReadOnlyAttribute : ITest
{
private int value;
ref readonly int ITest.Method(in int x) => ref value;
ref readonly int ITest.Property => ref value;
ref readonly int ITest.this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var typeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(typeName);
var method = type.GetMethod("System.Runtime.CompilerServices.ITest.Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("System.Runtime.CompilerServices.ITest.Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("System.Runtime.CompilerServices.ITest.Item");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ExplicitInterfaceImplementation_ExternalAssembly()
{
var reference = CreateCompilation(@"
namespace System.Runtime.CompilerServices
{
public interface ITest
{
ref readonly int Method(in int x);
ref readonly int Property { get; }
ref readonly int this[in int x] { get; }
}
}").ToMetadataReference();
var code = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : ITest
{
private int value;
ref readonly int ITest.Method(in int x) => ref value;
ref readonly int ITest.Property => ref value;
ref readonly int ITest.this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module =>
{
var typeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(typeName);
var method = type.GetMethod("System.Runtime.CompilerServices.ITest.Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("System.Runtime.CompilerServices.ITest.Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("System.Runtime.CompilerServices.ITest.Item");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void IsReadOnlyAttributeIsGenerated_ExplicitInterfaceImplementation_SameAssembly()
{
var code = @"
public interface ITest
{
ref readonly int Method(in int x);
ref readonly int Property { get; }
ref readonly int this[in int x] { get; }
}
public class TestImpl : ITest
{
private int value;
ref readonly int ITest.Method(in int x) => ref value;
ref readonly int ITest.Property => ref value;
ref readonly int ITest.this[in int x] => ref value;
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("TestImpl");
var method = type.GetMethod("ITest.Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("ITest.Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("ITest.Item");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void IsReadOnlyAttributeIsGenerated_ExplicitInterfaceImplementation_ExternalAssembly()
{
var reference = CreateCompilation(@"
public interface ITest
{
ref readonly int Method(in int x);
ref readonly int Property { get; }
ref readonly int this[in int x] { get; }
}").ToMetadataReference();
var code = @"
public class TestImpl : ITest
{
private int value;
ref readonly int ITest.Method(in int x) => ref value;
ref readonly int ITest.Property => ref value;
ref readonly int ITest.this[in int x] => ref value;
}";
CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("TestImpl");
var method = type.GetMethod("ITest.Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("ITest.Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("ITest.Item");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_Delegate()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public delegate ref readonly int IsReadOnlyAttribute(in int x);
}";
CreateCompilation(code).VerifyEmitDiagnostics(
// (4,21): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public delegate ref readonly int IsReadOnlyAttribute(in int x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(4, 21),
// (4,58): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public delegate ref readonly int IsReadOnlyAttribute(in int x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(4, 58));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Constructor()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
public Test(in int x) { }
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (11,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public Test(in int x) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 17));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Method()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
public ref readonly int Method(in int x) => ref x;
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (11,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public ref readonly int Method(in int x) => ref x;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 12),
// (11,36): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public ref readonly int Method(in int x) => ref x;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 36));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_LocalFunction()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
public void M()
{
int x = 0;
ref readonly int local(in int p)
{
return ref p;
}
local(x);
}
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (15,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// ref readonly int local(in int p)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(15, 9),
// (15,32): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// ref readonly int local(in int p)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int p").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(15, 32));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Lambda()
{
var reference = CreateCompilation(@"
public delegate ref readonly int D(in int x);
").EmitToImageReference();
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
class Test
{
public void M1()
{
M2((in int x) => ref x);
}
public void M2(D value) { }
}";
CreateCompilation(text, references: new[] { reference }).VerifyEmitDiagnostics(
// (14,33): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// M2((in int x) => ref x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=>").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(14, 23),
// (14,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// M2((in int x) => ref x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(14, 13));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Property()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
private int value;
public ref readonly int Property => ref value;
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (12,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public ref readonly int Property => ref value;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(12, 12));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Indexer()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
public ref readonly int this[in int x] => ref x;
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (12,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public ref readonly int this[in int x] => ref x;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(12, 12),
// (12,34): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public ref readonly int this[in int x] => ref x;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(12, 34));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Operator()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
public static int operator + (in Test x, in Test y) => 0;
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (11,35): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public static int operator + (in Test x, in Test y) => 0;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in Test x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 35),
// (11,46): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public static int operator + (in Test x, in Test y) => 0;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in Test y").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 46));
}
private void AssertNoIsReadOnlyAttributeExists(AssemblySymbol assembly)
{
var isReadOnlyAttributeTypeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
Assert.Null(assembly.GetTypeByMetadataName(isReadOnlyAttributeTypeName));
}
private void AssertGeneratedEmbeddedAttribute(AssemblySymbol assembly, string expectedTypeName)
{
var typeSymbol = assembly.GetTypeByMetadataName(expectedTypeName);
Assert.NotNull(typeSymbol);
Assert.Equal(Accessibility.Internal, typeSymbol.DeclaredAccessibility);
var attributes = typeSymbol.GetAttributes().OrderBy(attribute => attribute.AttributeClass.Name).ToArray();
Assert.Equal(2, attributes.Length);
Assert.Equal(WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute), attributes[0].AttributeClass.ToDisplayString());
Assert.Equal(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName, attributes[1].AttributeClass.ToDisplayString());
}
private static bool NeedsGeneratedIsReadOnlyAttribute(CSharpCompilation compilation)
{
return (compilation.GetNeedsGeneratedAttributes() & EmbeddableAttributes.IsReadOnlyAttribute) != 0;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AttributeTests_RefReadOnly : CSharpTestBase
{
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Method()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
class Test
{
public ref readonly int M(in int x) { return ref x; }
}
";
CompileAndVerify(text, verify: Verification.Fails, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
var peModule = (PEModuleSymbol)module;
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEMethodSymbol)method).Signature.ReturnParam.Handle));
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEParameterSymbol)parameter).Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Public);
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Method_Parameter()
{
var text = @"
class Test
{
public void M(in int x) { }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
var peModule = (PEModuleSymbol)module;
Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PEParameterSymbol)parameter).Handle));
AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_Method_ReturnType()
{
var text = @"
class Test
{
private int x;
public ref readonly int M() { return ref x; }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_Method()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
class Test
{
public ref readonly int M(in int x) { return ref x; }
}
";
CompileAndVerify(codeB, verify: Verification.Fails, references: new[] { referenceA }, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Operator()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
struct Test
{
public static int operator +(in Test x, in Test y) { return 0; }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("op_Addition");
Assert.Equal(2, method.ParameterCount);
foreach (var parameter in method.Parameters)
{
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
}
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Operator_Parameter()
{
var text = @"
struct Test
{
public static int operator +(in Test x, in Test y) { return 0; }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("op_Addition");
Assert.Equal(2, method.ParameterCount);
foreach (var parameter in method.Parameters)
{
Assert.Empty(parameter.GetAttributes());
}
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_Operator_Method()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
struct Test
{
public static int operator +(in Test x, in Test y) { return 0; }
}
";
CompileAndVerify(codeB, references: new[] { referenceA }, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("op_Addition");
Assert.Equal(2, method.ParameterCount);
foreach (var parameter in method.Parameters)
{
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
}
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Constructor()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
class Test
{
public Test(in int x) { }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod(".ctor").Parameters.Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Constructor_Parameter()
{
var text = @"
class Test
{
public Test(in int x) { }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod(".ctor").Parameters.Single();
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_Constructor_Method()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
class Test
{
public Test(in int x) { }
}
";
CompileAndVerify(codeB, references: new[] { referenceA }, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod(".ctor").Parameters.Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Property()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
class Test
{
private int x = 0;
public ref readonly int P1 { get { return ref x; } }
public ref readonly int P2 => ref x;
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Test");
AssertProperty(type.GetProperty("P1"));
AssertProperty(type.GetProperty("P2"));
void AssertProperty(PropertySymbol property)
{
Assert.Equal(RefKind.RefReadOnly, property.RefKind);
Assert.True(property.ReturnsByRefReadonly);
Assert.Empty(property.GetAttributes());
}
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_Property()
{
var text = @"
class Test
{
private int x = 0;
public ref readonly int P1 { get { return ref x; } }
public ref readonly int P2 => ref x;
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Test");
AssertProperty(type.GetProperty("P1"));
AssertProperty(type.GetProperty("P2"));
void AssertProperty(PropertySymbol property)
{
Assert.Equal(RefKind.RefReadOnly, property.RefKind);
Assert.True(property.ReturnsByRefReadonly);
Assert.Empty(property.GetAttributes());
}
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_Property()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
class Test
{
private int x = 0;
public ref readonly int P1 { get { return ref x; } }
public ref readonly int P2 => ref x;
}
";
CompileAndVerify(codeB, references: new[] { referenceA }, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Test");
AssertProperty(type.GetProperty("P1"));
AssertProperty(type.GetProperty("P2"));
void AssertProperty(PropertySymbol property)
{
Assert.Equal(RefKind.RefReadOnly, property.RefKind);
Assert.True(property.ReturnsByRefReadonly);
Assert.Empty(property.GetAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
}
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Indexer()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
class Test
{
public ref readonly int this[in int x] { get { return ref x; } }
}
";
CompileAndVerify(text, verify: Verification.Fails, symbolValidator: module =>
{
var indexer = module.ContainingAssembly.GetTypeByMetadataName("Test").GetProperty("this[]");
Assert.Equal(RefKind.RefReadOnly, indexer.RefKind);
Assert.True(indexer.ReturnsByRefReadonly);
var parameter = indexer.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(indexer.GetAttributes());
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Indexer_Parameter()
{
var text = @"
class Test
{
public int this[in int x] { get { return x; } }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetProperty("this[]").GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_Indexer_ReturnType()
{
var text = @"
class Test
{
private int x;
public ref readonly int this[int p] { get { return ref x; } }
}
";
CompileAndVerify(text, symbolValidator: module =>
{
var indexer = module.ContainingAssembly.GetTypeByMetadataName("Test").GetProperty("this[]");
Assert.Equal(RefKind.RefReadOnly, indexer.RefKind);
Assert.True(indexer.ReturnsByRefReadonly);
Assert.Empty(indexer.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_Indexer()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
class Test
{
public ref readonly int this[in int x] { get { return ref x; } }
}
";
CompileAndVerify(codeB, verify: Verification.Fails, references: new[] { referenceA }, symbolValidator: module =>
{
var indexer = module.ContainingAssembly.GetTypeByMetadataName("Test").GetProperty("this[]");
Assert.Equal(RefKind.RefReadOnly, indexer.RefKind);
Assert.True(indexer.ReturnsByRefReadonly);
var parameter = indexer.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(indexer.GetAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Delegate()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
public delegate ref readonly int D(in int x);
";
CompileAndVerify(text, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod;
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Delegate_Parameter()
{
var text = @"
public delegate void D(in int x);
";
CompileAndVerify(text, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_Delegate_ReturnType()
{
var text = @"
public delegate ref readonly int D();
";
CompileAndVerify(text, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod;
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_Delegate()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
public delegate ref readonly int D(in int x);
";
CompileAndVerify(codeB, references: new[] { referenceA }, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("D").DelegateInvokeMethod;
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_LocalFunctions()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
public class Test
{
public void M()
{
ref readonly int Inner(in int x)
{
return ref x;
}
}
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, verify: Verification.Fails, options: options, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__Inner|0_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_LocalFunctions_Parameters()
{
var text = @"
public class Test
{
public void M()
{
void Inner(in int x) { }
}
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, options: options, symbolValidator: module =>
{
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__Inner|0_0").GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_LocalFunctions_ReturnType()
{
var text = @"
public class Test
{
private int x;
public void M()
{
ref readonly int Inner()
{
return ref x;
}
}
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, verify: Verification.Fails, options: options, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__Inner|1_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_LocalFunctions()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
public class Test
{
public void M()
{
ref readonly int Inner(in int x)
{
return ref x;
}
}
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(codeB, verify: Verification.Fails, references: new[] { referenceA }, options: options, symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("<M>g__Inner|0_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_SameAssembly_Lambda()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
delegate ref readonly int D(in int x);
class Test
{
public void M1()
{
M2((in int x) => ref x);
}
public void M2(D value) { }
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, verify: Verification.Fails, options: options, symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>("Test.<>c.<M1>b__0_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void InIsWrittenToMetadata_NeedsToBeGenerated_Lambda_Parameter()
{
var text = @"
delegate void D(in int x);
class Test
{
public void M1()
{
M2((in int x) => {});
}
public void M2(D value) { }
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, options: options, symbolValidator: module =>
{
var parameter = module.GlobalNamespace.GetMember<MethodSymbol>("Test.<>c.<M1>b__0_0").GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_NeedsToBeGenerated_Lambda_ReturnType()
{
var text = @"
delegate ref readonly int D();
class Test
{
private int x;
public void M1()
{
M2(() => ref x);
}
public void M2(D value) { }
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(text, options: options, symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>("Test.<M1>b__1_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
Assert.Empty(method.GetReturnTypeAttributes());
});
}
[Fact]
public void RefReadOnlyIsWrittenToMetadata_DifferentAssembly_Lambda()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
delegate ref readonly int D(in int x);
class Test
{
public void M1()
{
M2((in int x) => ref x);
}
public void M2(D value) { }
}
";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
CompileAndVerify(codeB, verify: Verification.Fails, options: options, references: new[] { referenceA }, symbolValidator: module =>
{
var method = module.GlobalNamespace.GetMember<MethodSymbol>("Test.<>c.<M1>b__0_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
Assert.True(method.ReturnsByRefReadonly);
var parameter = method.GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
Assert.Empty(method.GetReturnTypeAttributes());
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
});
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Delegates()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
[IsReadOnly]
public delegate ref readonly int D([IsReadOnly]in int x);
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (4,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(4, 2),
// (5,37): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// public delegate ref readonly int D([IsReadOnly]in int x);
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(5, 37));
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Types()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
[IsReadOnly]
public class Test
{
}
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (4,2): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(4, 2));
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Fields()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
public class Test
{
[IsReadOnly]
private int x = 0;
public int X => x;
}
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (6,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(6, 6));
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Properties()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
public class Test
{
private int x = 0;
[IsReadOnly]
public ref readonly int Property => ref x;
}
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (8,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(8, 6));
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Methods()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
public class Test
{
[IsReadOnly]
[return: IsReadOnly]
public ref readonly int Method([IsReadOnly]in int x)
{
return ref x;
}
}
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (6,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(6, 6),
// (7,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [return: IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(7, 14),
// (8,37): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// public ref readonly int Method([IsReadOnly]in int x)
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(8, 37));
}
[Fact]
public void IsReadOnlyAttributeIsDisallowedEverywhereInSource_Indexers()
{
var codeA = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}";
var referenceA = CreateCompilation(codeA).VerifyDiagnostics().ToMetadataReference();
var codeB = @"
using System.Runtime.CompilerServices;
public class Test
{
[IsReadOnly]
public ref readonly int this[[IsReadOnly]in int x] { get { return ref x; } }
}
";
CreateCompilation(codeB, references: new[] { referenceA }).VerifyDiagnostics(
// (6,6): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(6, 6),
// (7,35): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// public ref readonly int this[[IsReadOnly]in int x] { get { return ref x; } }
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(7, 35));
}
[Fact]
public void UserReferencingEmbeddedAttributeShouldResultInAnError()
{
var code = @"
[Embedded]
public class Test
{
public ref readonly int M(in int p) => ref p;
}";
CreateCompilation(code).VerifyDiagnostics(
// (2,2): error CS0246: The type or namespace name 'EmbeddedAttribute' could not be found (are you missing a using directive or an assembly reference?)
// [Embedded]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Embedded").WithArguments("EmbeddedAttribute").WithLocation(2, 2),
// (2,2): error CS0246: The type or namespace name 'Embedded' could not be found (are you missing a using directive or an assembly reference?)
// [Embedded]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Embedded").WithArguments("Embedded").WithLocation(2, 2));
}
[Fact]
public void UserReferencingIsReadOnlyAttributeShouldResultInAnError()
{
var code = @"
[IsReadOnly]
public class Test
{
public ref readonly int M(in int p) => ref p;
}";
CreateCompilation(code).VerifyDiagnostics(
// (2,2): error CS0246: The type or namespace name 'IsReadOnlyAttribute' could not be found (are you missing a using directive or an assembly reference?)
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsReadOnly").WithArguments("IsReadOnlyAttribute").WithLocation(2, 2),
// (2,2): error CS0246: The type or namespace name 'IsReadOnly' could not be found (are you missing a using directive or an assembly reference?)
// [IsReadOnly]
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IsReadOnly").WithArguments("IsReadOnly").WithLocation(2, 2));
}
[Fact]
public void TypeReferencingAnotherTypeThatUsesAPublicAttributeFromAThirdNotReferencedAssemblyShouldGenerateItsOwn()
{
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
var code1 = CreateCompilation(@"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}");
var code2 = CreateCompilation(@"
public class Test1
{
public static ref readonly int M(in int p) => ref p;
}", references: new[] { code1.ToMetadataReference() }, options: options);
CompileAndVerify(code2, verify: Verification.Fails, symbolValidator: module =>
{
// IsReadOnly is not generated in assembly
var isReadOnlyAttributeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(isReadOnlyAttributeName));
});
var code3 = CreateCompilation(@"
public class Test2
{
public static ref readonly int M(in int p) => ref Test1.M(p);
}", references: new[] { code2.ToMetadataReference() }, options: options);
CompileAndVerify(code3, symbolValidator: module =>
{
// IsReadOnly is generated in assembly
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName);
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.IsReadOnlyAttribute.FullName);
});
}
[Fact]
public void BuildingAModuleRequiresIsReadOnlyAttributeToBeThere_Missing_SourceMethod()
{
var code = @"
public class Test
{
public void M(in int x) { }
}";
CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics(
// (4,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// public void M(in int x) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(4, 19));
}
[Fact]
public void BuildingAModuleRequiresIsReadOnlyAttributeToBeThere_Missing_SourceMethod_MultipleLocations()
{
var code = @"
public class Test
{
public void M1(in int x) { }
public void M2(in int x) { }
}";
CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics(
// (4,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// public void M1(in int x) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(4, 20),
// (5,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// public void M2(in int x) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(5, 20));
}
[Fact]
public void BuildingAModuleRequiresIsReadOnlyAttributeToBeThere_Missing_LocalFunctions()
{
var code = @"
public class Test
{
public void Parent()
{
void child(in int p) { }
int x = 0;
child(x);
}
}";
CreateCompilation(code, options: TestOptions.ReleaseModule).VerifyDiagnostics(
// (6,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// void child(in int p) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int p").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(6, 20));
}
[Fact]
public void BuildingAModuleRequiresIsReadOnlyAttributeToBeThere_InAReference()
{
var reference = CreateCompilation(@"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}").ToMetadataReference();
var code = @"
public class Test
{
public void M(in int x) { }
}";
CompileAndVerify(code, verify: Verification.Fails, references: new[] { reference }, options: TestOptions.ReleaseModule, symbolValidator: module =>
{
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
var parameter = module.ContainingAssembly.GetTypeByMetadataName("Test").GetMethod("M").GetParameters().Single();
Assert.Equal(RefKind.In, parameter.RefKind);
Assert.Empty(parameter.GetAttributes());
});
}
[Fact]
public void ReferencingAnEmbeddedIsReadOnlyAttributeDoesNotUseIt_InternalsVisible()
{
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
var code1 = @"
[assembly:System.Runtime.CompilerServices.InternalsVisibleToAttribute(""Assembly2"")]
public class Test1
{
public static ref readonly int M(in int p) => ref p;
}";
var comp1 = CompileAndVerify(code1, options: options, verify: Verification.Fails, symbolValidator: module =>
{
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName);
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.IsReadOnlyAttribute.FullName);
});
var code2 = @"
public class Test2
{
public static ref readonly int M(in int p) => ref Test1.M(p);
}";
CompileAndVerify(code2, options: options.WithModuleName("Assembly2"), references: new[] { comp1.Compilation.ToMetadataReference() }, symbolValidator: module =>
{
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName);
AssertGeneratedEmbeddedAttribute(module.ContainingAssembly, AttributeDescription.IsReadOnlyAttribute.FullName);
});
}
[Fact]
public void IfIsReadOnlyAttributeIsDefinedThenEmbeddedIsNotGenerated()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute { }
}
class Test
{
public ref readonly int M(in int x) { return ref x; }
}
";
CompileAndVerify(text, verify: Verification.Fails, symbolValidator: module =>
{
Assert.Null(module.ContainingAssembly.GetTypeByMetadataName(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName));
});
}
[Fact]
public void IsReadOnlyAttributeExistsWithWrongConstructorSignature_NetModule()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
class Test
{
public void M(in int x) { }
}";
CreateCompilation(text, options: TestOptions.ReleaseModule).VerifyDiagnostics(
// (11,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public void M(in int x) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 19));
}
[Fact]
public void IsReadOnlyAttributeExistsWithWrongConstructorSignature_Assembly()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
class Test
{
public void M(in int x) { }
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (11,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public void M(in int x) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 19));
}
[Fact]
public void IsReadOnlyAttributeExistsWithWrongConstructorSignature_PrivateConstructor()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
private IsReadOnlyAttribute() { }
}
}
class Test
{
public void M(in int x) { }
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (11,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public void M(in int x) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 19));
}
[Fact]
public void IsReadOnlyAttributesAreNotPortedInNoPia()
{
var comAssembly = CreateCompilationWithMscorlib40(@"
using System;
using System.Runtime.InteropServices;
[assembly: ImportedFromTypeLib(""test.dll"")]
[assembly: Guid(""9784f9a1-594a-4351-8f69-0fd2d2df03d3"")]
[ComImport()]
[Guid(""9784f9a1-594a-4351-8f69-0fd2d2df03d3"")]
public interface Test
{
ref readonly int Property { get; }
ref readonly int Method(in int x);
}");
CompileAndVerify(comAssembly, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Test");
var property = type.GetMember<PEPropertySymbol>("Property");
Assert.NotNull(property);
Assert.Empty(property.GetAttributes());
var method = type.GetMethod("Method");
Assert.NotNull(method);
Assert.Empty(method.GetReturnTypeAttributes());
var parameter = method.Parameters.Single();
Assert.NotNull(parameter);
Assert.Empty(parameter.GetAttributes());
});
var code = @"
class User
{
public void M(Test p)
{
p.Method(p.Property);
}
}";
var options = TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All);
var compilation_CompilationReference = CreateCompilationWithMscorlib40(code, options: options, references: new[] { comAssembly.ToMetadataReference(embedInteropTypes: true) });
CompileAndVerify(compilation_CompilationReference, symbolValidator: symbolValidator);
var compilation_BinaryReference = CreateCompilationWithMscorlib40(code, options: options, references: new[] { comAssembly.EmitToImageReference(embedInteropTypes: true) });
CompileAndVerify(compilation_BinaryReference, symbolValidator: symbolValidator);
void symbolValidator(ModuleSymbol module)
{
// No attribute is copied
AssertNoIsReadOnlyAttributeExists(module.ContainingAssembly);
var type = module.ContainingAssembly.GetTypeByMetadataName("Test");
var property = type.GetMember<PEPropertySymbol>("Property");
Assert.NotNull(property);
Assert.Empty(property.GetAttributes());
var method = type.GetMethod("Method");
Assert.NotNull(method);
Assert.Empty(method.GetReturnTypeAttributes());
var parameter = method.Parameters.Single();
Assert.NotNull(parameter);
Assert.Empty(parameter.GetAttributes());
}
}
[Fact]
public void TryingToBindFromSemanticModelDoesNotPolluteCompilation_Lambdas_Parameters()
{
var reference = CreateCompilation(@"
public delegate int D (in int x);
").VerifyEmitDiagnostics();
Assert.True(NeedsGeneratedIsReadOnlyAttribute(reference));
var compilation = CreateCompilation(@"
public class Test
{
public void Process(D lambda) { }
void User()
{
}
}", references: new[] { reference.ToMetadataReference() });
compilation.VerifyEmitDiagnostics();
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false);
var userFunction = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(method => method.Identifier.Text == "User");
var position = userFunction.Body.CloseBraceToken.Position;
var newInvocation = SyntaxFactory.ParseExpression("Process((in int x) => x)");
var result = model.GetSpeculativeSymbolInfo(position, newInvocation, SpeculativeBindingOption.BindAsExpression);
Assert.NotNull(result.Symbol);
Assert.Equal(CandidateReason.None, result.CandidateReason);
Assert.Empty(result.CandidateSymbols);
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
}
[Fact]
public void TryingToBindFromSemanticModelDoesNotPolluteCompilation_Lambdas_ReturnTypes()
{
var reference = CreateCompilation(@"
public delegate ref readonly int D ();
").VerifyEmitDiagnostics();
Assert.True(NeedsGeneratedIsReadOnlyAttribute(reference));
var compilation = CreateCompilation(@"
public class Test
{
private int x;
public void Process(D lambda)
{
x = lambda();
}
void User()
{
}
}", references: new[] { reference.ToMetadataReference() });
compilation.VerifyEmitDiagnostics();
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false);
var userFunction = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(method => method.Identifier.Text == "User");
var position = userFunction.Body.CloseBraceToken.Position;
var newInvocation = SyntaxFactory.ParseExpression("Process(() => ref x)");
var result = model.GetSpeculativeSymbolInfo(position, newInvocation, SpeculativeBindingOption.BindAsExpression);
Assert.NotNull(result.Symbol);
Assert.Equal(CandidateReason.None, result.CandidateReason);
Assert.Empty(result.CandidateSymbols);
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
}
[Fact]
public void TryingToBindFromSemanticModelDoesNotPolluteCompilation_LocalFunctions_Parameters()
{
var compilation = CreateCompilation(@"
public class Test
{
void User()
{
}
}");
compilation.VerifyEmitDiagnostics();
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false);
var userFunction = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(method => method.Identifier.Text == "User");
var position = userFunction.Body.CloseBraceToken.Position;
var localfunction = SyntaxFactory.ParseStatement("int localFunction(in int x) { return x; }");
Assert.True(model.TryGetSpeculativeSemanticModel(position, localfunction, out var newModel));
var localFunctionSymbol = newModel.GetDeclaredSymbol(localfunction);
Assert.NotNull(localFunctionSymbol);
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
}
[Fact]
public void TryingToBindFromSemanticModelDoesNotPolluteCompilation_LocalFunctions_ReturnTypes()
{
var compilation = CreateCompilation(@"
public class Test
{
void User()
{
}
}");
compilation.VerifyEmitDiagnostics();
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false);
var userFunction = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single(method => method.Identifier.Text == "User");
var position = userFunction.Body.CloseBraceToken.Position;
var localfunction = SyntaxFactory.ParseStatement("ref readonly int localFunction(int x) { return ref x; }");
Assert.True(model.TryGetSpeculativeSemanticModel(position, localfunction, out var newModel));
var localFunctionSymbol = newModel.GetDeclaredSymbol(localfunction);
Assert.NotNull(localFunctionSymbol);
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
}
[Fact]
public void TryingPossibleBindingsForRefReadOnlyDoesNotPolluteCompilationForInvalidOnes()
{
var reference = CreateCompilation(@"
public delegate ref readonly int D1 ();
public delegate ref int D2 ();
").VerifyEmitDiagnostics();
Assert.True(NeedsGeneratedIsReadOnlyAttribute(reference));
var compilation = CreateCompilation(@"
public class Test
{
public void Process(D1 lambda, int x) { }
public void Process(D2 lambda, byte x) { }
void User()
{
byte byteVar = 0;
Process(() => { throw null; }, byteVar);
}
}", references: new[] { reference.ToMetadataReference() });
compilation.VerifyEmitDiagnostics();
Assert.False(NeedsGeneratedIsReadOnlyAttribute(compilation));
}
[Fact]
public void RefReadOnlyErrorsForLambdasDoNotPolluteCompilationDeclarationsDiagnostics()
{
var reference = CreateCompilation(@"
public delegate int D (in int x);
").EmitToImageReference();
var code = @"
public class Test
{
public void Process(D lambda) { }
void User()
{
Process((in int p) => p);
}
}";
var compilation = CreateCompilation(code, options: TestOptions.ReleaseModule, references: new[] { reference });
compilation.DeclarationDiagnostics.Verify();
compilation.VerifyDiagnostics(
// (8,18): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// Process((in int p) => p);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int p").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(8, 18));
}
[Fact]
public void RefReadOnlyErrorsForLocalFunctionsDoNotPolluteCompilationDeclarationsDiagnostics()
{
var code = @"
public class Test
{
private int x = 0;
void User()
{
void local(in int x) { }
local(x);
}
}";
var compilation = CreateCompilation(code, options: TestOptions.ReleaseModule);
compilation.DeclarationDiagnostics.Verify();
compilation.VerifyDiagnostics(
// (7,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// void local(in int x) { }
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(7, 20));
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_Class_NoParent()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute
{
private int value;
public ref readonly int Method(in int x) => ref value;
public static int operator +(in IsReadOnlyAttribute x, in IsReadOnlyAttribute y) => 0;
public ref readonly int Property => ref value;
public ref readonly int this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var isReadOnlyAttributeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(isReadOnlyAttributeName);
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var @operator = type.GetMethod("op_Addition");
Assert.Empty(@operator.Parameters[0].GetAttributes());
Assert.Empty(@operator.Parameters[1].GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_Class_CorrectParent()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
private int value;
public ref readonly int Method(in int x) => ref value;
public static int operator +(in IsReadOnlyAttribute x, in IsReadOnlyAttribute y) => 0;
public ref readonly int Property => ref value;
public ref readonly int this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var isReadOnlyAttributeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(isReadOnlyAttributeName);
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var @operator = type.GetMethod("op_Addition");
Assert.Empty(@operator.Parameters[0].GetAttributes());
Assert.Empty(@operator.Parameters[1].GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ClassInherit()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
}
}
public class Child : System.Runtime.CompilerServices.IsReadOnlyAttribute
{
private int value;
public ref readonly int Method(in int x) => ref value;
public static int operator +(in Child x, in Child y) => 0;
public ref readonly int Property => ref value;
public ref readonly int this[in int x] => ref value;
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Child");
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var @operator = type.GetMethod("op_Addition");
Assert.Empty(@operator.Parameters[0].GetAttributes());
Assert.Empty(@operator.Parameters[1].GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ClassOverride_SameAssembly()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public abstract class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute() { }
public abstract ref readonly int Method(in int x);
public abstract ref readonly int Property { get; }
public abstract ref readonly int this[in int x] { get; }
}
}
public class Child : System.Runtime.CompilerServices.IsReadOnlyAttribute
{
private int value;
public override ref readonly int Method(in int x) => ref value;
public override ref readonly int Property => ref value;
public override ref readonly int this[in int x] => ref value;
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Child");
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ClassOverride_ExternalAssembly()
{
var reference = CreateCompilation(@"
namespace System.Runtime.CompilerServices
{
public abstract class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute() { }
public abstract ref readonly int Method(in int x);
public abstract ref readonly int Property { get; }
public abstract ref readonly int this[in int x] { get; }
}
}", assemblyName: "testRef").ToMetadataReference();
var code = @"
public class Child : System.Runtime.CompilerServices.IsReadOnlyAttribute
{
private int value;
public override ref readonly int Method(in int x) => ref value;
public override ref readonly int Property => ref value;
public override ref readonly int this[in int x] => ref value;
}";
CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("Child");
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ClassOverridden_SameAssembly()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public abstract class Parent : System.Attribute
{
public abstract ref readonly int Method(in int x);
public abstract ref readonly int Property { get; }
public abstract ref readonly int this[in int x] { get; }
}
public class IsReadOnlyAttribute : Parent
{
private int value;
public override ref readonly int Method(in int x) => ref value;
public override ref readonly int Property => ref value;
public override ref readonly int this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var typeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(typeName);
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ClassOverridden_ExternalAssembly()
{
var reference = CreateCompilation(@"
namespace System.Runtime.CompilerServices
{
public abstract class Parent : System.Attribute
{
public abstract ref readonly int Method(in int x);
public abstract ref readonly int Property { get; }
public abstract ref readonly int this[in int x] { get; }
}
}").ToMetadataReference();
var code = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : Parent
{
private int value;
public override ref readonly int Method(in int x) => ref value;
public override ref readonly int Property => ref value;
public override ref readonly int this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module =>
{
var typeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(typeName);
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_Class_WrongParent()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public class TestParent { }
public class IsReadOnlyAttribute : TestParent
{
private int value;
public ref readonly int Method(in int x) => ref value;
public static int operator +(in IsReadOnlyAttribute x, in IsReadOnlyAttribute y) => 0;
public ref readonly int Property => ref value;
public ref readonly int this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var isReadOnlyAttributeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(isReadOnlyAttributeName);
var method = type.GetMethod("Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var @operator = type.GetMethod("op_Addition");
Assert.Empty(@operator.Parameters[0].GetAttributes());
Assert.Empty(@operator.Parameters[1].GetAttributes());
var property = type.GetProperty("Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("this[]");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_Interface()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public interface IsReadOnlyAttribute
{
ref readonly int Method(in int x);
}
}";
CreateCompilation(code).VerifyEmitDiagnostics(
// (6,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// ref readonly int Method(in int x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(6, 9),
// (6,33): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// ref readonly int Method(in int x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(6, 33));
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ExplicitInterfaceImplementation_SameAssembly()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public interface ITest
{
ref readonly int Method(in int x);
ref readonly int Property { get; }
ref readonly int this[in int x] { get; }
}
public class IsReadOnlyAttribute : ITest
{
private int value;
ref readonly int ITest.Method(in int x) => ref value;
ref readonly int ITest.Property => ref value;
ref readonly int ITest.this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var typeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(typeName);
var method = type.GetMethod("System.Runtime.CompilerServices.ITest.Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("System.Runtime.CompilerServices.ITest.Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("System.Runtime.CompilerServices.ITest.Item");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_ExplicitInterfaceImplementation_ExternalAssembly()
{
var reference = CreateCompilation(@"
namespace System.Runtime.CompilerServices
{
public interface ITest
{
ref readonly int Method(in int x);
ref readonly int Property { get; }
ref readonly int this[in int x] { get; }
}
}").ToMetadataReference();
var code = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : ITest
{
private int value;
ref readonly int ITest.Method(in int x) => ref value;
ref readonly int ITest.Property => ref value;
ref readonly int ITest.this[in int x] => ref value;
}
}";
CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module =>
{
var typeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
var type = module.ContainingAssembly.GetTypeByMetadataName(typeName);
var method = type.GetMethod("System.Runtime.CompilerServices.ITest.Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("System.Runtime.CompilerServices.ITest.Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("System.Runtime.CompilerServices.ITest.Item");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void IsReadOnlyAttributeIsGenerated_ExplicitInterfaceImplementation_SameAssembly()
{
var code = @"
public interface ITest
{
ref readonly int Method(in int x);
ref readonly int Property { get; }
ref readonly int this[in int x] { get; }
}
public class TestImpl : ITest
{
private int value;
ref readonly int ITest.Method(in int x) => ref value;
ref readonly int ITest.Property => ref value;
ref readonly int ITest.this[in int x] => ref value;
}";
CompileAndVerify(code, verify: Verification.Passes, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("TestImpl");
var method = type.GetMethod("ITest.Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("ITest.Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("ITest.Item");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void IsReadOnlyAttributeIsGenerated_ExplicitInterfaceImplementation_ExternalAssembly()
{
var reference = CreateCompilation(@"
public interface ITest
{
ref readonly int Method(in int x);
ref readonly int Property { get; }
ref readonly int this[in int x] { get; }
}").ToMetadataReference();
var code = @"
public class TestImpl : ITest
{
private int value;
ref readonly int ITest.Method(in int x) => ref value;
ref readonly int ITest.Property => ref value;
ref readonly int ITest.this[in int x] => ref value;
}";
CompileAndVerify(code, verify: Verification.Passes, references: new[] { reference }, symbolValidator: module =>
{
var type = module.ContainingAssembly.GetTypeByMetadataName("TestImpl");
var method = type.GetMethod("ITest.Method");
Assert.Empty(method.GetReturnTypeAttributes());
Assert.Empty(method.Parameters.Single().GetAttributes());
var property = type.GetProperty("ITest.Property");
Assert.Empty(property.GetAttributes());
var indexer = type.GetProperty("ITest.Item");
Assert.Empty(indexer.GetAttributes());
Assert.Empty(indexer.Parameters.Single().GetAttributes());
});
}
[Fact]
public void RefReadOnlyDefinitionsInsideUserDefinedIsReadOnlyAttribute_Delegate()
{
var code = @"
namespace System.Runtime.CompilerServices
{
public delegate ref readonly int IsReadOnlyAttribute(in int x);
}";
CreateCompilation(code).VerifyEmitDiagnostics(
// (4,21): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public delegate ref readonly int IsReadOnlyAttribute(in int x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(4, 21),
// (4,58): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public delegate ref readonly int IsReadOnlyAttribute(in int x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(4, 58));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Constructor()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
public Test(in int x) { }
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (11,17): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public Test(in int x) { }
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 17));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Method()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
public ref readonly int Method(in int x) => ref x;
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (11,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public ref readonly int Method(in int x) => ref x;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 12),
// (11,36): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public ref readonly int Method(in int x) => ref x;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 36));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_LocalFunction()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
public void M()
{
int x = 0;
ref readonly int local(in int p)
{
return ref p;
}
local(x);
}
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (15,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// ref readonly int local(in int p)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(15, 9),
// (15,32): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// ref readonly int local(in int p)
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int p").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(15, 32));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Lambda()
{
var reference = CreateCompilation(@"
public delegate ref readonly int D(in int x);
").EmitToImageReference();
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
class Test
{
public void M1()
{
M2((in int x) => ref x);
}
public void M2(D value) { }
}";
CreateCompilation(text, references: new[] { reference }).VerifyEmitDiagnostics(
// (14,33): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// M2((in int x) => ref x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=>").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(14, 23),
// (14,13): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// M2((in int x) => ref x);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(14, 13));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Property()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
private int value;
public ref readonly int Property => ref value;
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (12,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public ref readonly int Property => ref value;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(12, 12));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Indexer()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
public ref readonly int this[in int x] => ref x;
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (12,12): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public ref readonly int this[in int x] => ref x;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(12, 12),
// (12,34): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public ref readonly int this[in int x] => ref x;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(12, 34));
}
[Fact]
public void MissingRequiredConstructorWillReportErrorsOnApproriateSyntax_Operator()
{
var text = @"
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : System.Attribute
{
public IsReadOnlyAttribute(int p) { }
}
}
public class Test
{
public static int operator + (in Test x, in Test y) => 0;
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (11,35): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public static int operator + (in Test x, in Test y) => 0;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in Test x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 35),
// (11,46): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// public static int operator + (in Test x, in Test y) => 0;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in Test y").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(11, 46));
}
[Fact]
public void EmitAttribute_LambdaReturnType()
{
var source =
@"class Program
{
static void Main()
{
var f = (ref readonly int () => throw null);
f();
}
}";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program+<>c").GetMethod("<Main>b__0_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
});
}
[Fact]
public void EmitAttribute_LambdaParameters()
{
var source =
@"class Program
{
static void Main()
{
var f = (in int x, ref int y) => { };
int x = 1;
int y = 2;
f(x, ref y);
}
}";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program+<>c").GetMethod("<Main>b__0_0");
Assert.Equal(RefKind.RefReadOnly, method.Parameters[0].RefKind);
Assert.Equal(RefKind.Ref, method.Parameters[1].RefKind);
});
}
[Fact]
public void EmitAttribute_LocalFunctionReturnType()
{
var source =
@"class Program
{
static void Main()
{
ref readonly int L() => throw null;
L();
}
}";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<Main>g__L|0_0");
Assert.Equal(RefKind.RefReadOnly, method.RefKind);
});
}
[Fact]
public void EmitAttribute_LocalFunctionParameters()
{
var source =
@"class Program
{
static void Main()
{
void L(ref int x, in int y) { };
int x = 1;
int y = 2;
L(ref x, y);
}
}";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
symbolValidator: module =>
{
var method = module.ContainingAssembly.GetTypeByMetadataName("Program").GetMethod("<Main>g__L|0_0");
Assert.Equal(RefKind.Ref, method.Parameters[0].RefKind);
Assert.Equal(RefKind.RefReadOnly, method.Parameters[1].RefKind);
});
}
[Fact]
public void EmitAttribute_Lambda_NetModule()
{
var source =
@"class Program
{
static void Main()
{
var f1 = (in int x, ref int y) => { };
int x = 1;
int y = 2;
f1(x, ref y);
var f2 = (ref readonly int () => throw null);
f2();
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseModule);
comp.VerifyDiagnostics(
// (5,19): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// var f1 = (in int x, ref int y) => { };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(5, 19),
// (9,39): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// var f2 = (ref readonly int () => throw null);
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "=>").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(9, 39));
}
[Fact]
public void EmitAttribute_LocalFunction_NetModule()
{
var source =
@"class Program
{
static void Main()
{
void L1(ref int x, in int y) { };
int x = 1;
int y = 2;
L1(ref x, y);
ref readonly int L2() => throw null;
L2();
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseModule);
comp.VerifyDiagnostics(
// (5,28): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// void L1(ref int x, in int y) { };
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "in int y").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(5, 28),
// (9,9): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsReadOnlyAttribute' is not defined or imported
// ref readonly int L2() => throw null;
Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(9, 9));
}
[Fact]
public void EmitAttribute_Lambda_MissingAttributeConstructor()
{
var sourceA =
@"namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : Attribute
{
private IsReadOnlyAttribute() { }
}
}";
var sourceB =
@"class Program
{
static void Main()
{
var f1 = (in int x, ref int y) => { };
int x = 1;
int y = 2;
f1(x, ref y);
var f2 = (ref readonly int () => throw null);
f2();
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB });
comp.VerifyDiagnostics(
// (5,19): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// var f1 = (in int x, ref int y) => { };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int x").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(5, 19),
// (9,39): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// var f2 = (ref readonly int () => throw null);
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=>").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(9, 39));
}
[Fact]
public void EmitAttribute_LocalFunction_MissingAttributeConstructor()
{
var sourceA =
@"namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : Attribute
{
private IsReadOnlyAttribute() { }
}
}";
var sourceB =
@"class Program
{
static void Main()
{
void L1(ref int x, in int y) { };
int x = 1;
int y = 2;
L1(ref x, y);
ref readonly int L2() => throw null;
L2();
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB });
comp.VerifyDiagnostics(
// (5,28): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// void L1(ref int x, in int y) { };
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "in int y").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(5, 28),
// (9,9): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IsReadOnlyAttribute..ctor'
// ref readonly int L2() => throw null;
Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "ref readonly int").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute", ".ctor").WithLocation(9, 9));
}
private void AssertNoIsReadOnlyAttributeExists(AssemblySymbol assembly)
{
var isReadOnlyAttributeTypeName = WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute);
Assert.Null(assembly.GetTypeByMetadataName(isReadOnlyAttributeTypeName));
}
private void AssertGeneratedEmbeddedAttribute(AssemblySymbol assembly, string expectedTypeName)
{
var typeSymbol = assembly.GetTypeByMetadataName(expectedTypeName);
Assert.NotNull(typeSymbol);
Assert.Equal(Accessibility.Internal, typeSymbol.DeclaredAccessibility);
var attributes = typeSymbol.GetAttributes().OrderBy(attribute => attribute.AttributeClass.Name).ToArray();
Assert.Equal(2, attributes.Length);
Assert.Equal(WellKnownTypes.GetMetadataName(WellKnownType.System_Runtime_CompilerServices_CompilerGeneratedAttribute), attributes[0].AttributeClass.ToDisplayString());
Assert.Equal(AttributeDescription.CodeAnalysisEmbeddedAttribute.FullName, attributes[1].AttributeClass.ToDisplayString());
}
private static bool NeedsGeneratedIsReadOnlyAttribute(CSharpCompilation compilation)
{
return (compilation.GetNeedsGeneratedAttributes() & EmbeddableAttributes.IsReadOnlyAttribute) != 0;
}
}
}
| 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/Test/Emit/CodeGen/CodeGenLocalFunctionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public static class LocalFunctionTestsUtil
{
public static IMethodSymbol FindLocalFunction(this CompilationVerifier verifier, string localFunctionName)
{
localFunctionName = (char)GeneratedNameKind.LocalFunction + "__" + localFunctionName;
var methods = verifier.TestData.GetMethodsByName();
IMethodSymbol result = null;
foreach (var kvp in methods)
{
if (kvp.Key.Contains(localFunctionName))
{
Assert.Null(result); // more than one name matched
result = ((MethodSymbol)kvp.Value.Method).GetPublicSymbol();
}
}
Assert.NotNull(result); // no methods matched
return result;
}
}
[CompilerTrait(CompilerFeature.LocalFunctions)]
public class CodeGenLocalFunctionTests : CSharpTestBase
{
[Fact]
[WorkItem(37459, "https://github.com/dotnet/roslyn/pull/37459")]
public void StaticLocalFunctionCaptureConstants()
{
var src = @"
using System;
class C
{
const int X = 1;
void M()
{
const int Y = 5;
local();
return;
static void local()
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
}
public static void Main()
{
(new C()).M();
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: @"
1
5");
verifier.VerifyIL("C.<M>g__local|1_0", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ldc.i4.5
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ret
}");
}
[Fact]
[WorkItem(481125, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=481125")]
public void Repro481125()
{
var comp = CreateCompilation(@"
using System;
using System.Linq;
public class C
{
static void Main()
{
var c = new C();
Console.WriteLine(c.M(0).Count());
Console.WriteLine(c.M(1).Count());
}
public IQueryable<E> M(int salesOrderId)
{
using (var uow = new D())
{
return Local();
IQueryable<E> Local() => uow.ES.Where(so => so.Id == salesOrderId);
}
}
}
internal class D : IDisposable
{
public IQueryable<E> ES => new[] { new E() }.AsQueryable();
public void Dispose() { }
}
public class E
{
public int Id;
}", options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: @"1
0");
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(24647, "https://github.com/dotnet/roslyn/issues/24647")]
public void Repro24647()
{
var comp = CreateCompilation(@"
class Program
{
static void Main(string[] args)
{
void local() { } => new object();
}
}");
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var creation = localFunction.DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
var objectCreationOperation = model.GetOperation(creation);
var localFunctionOperation = (ILocalFunctionOperation)model.GetOperation(localFunction);
Assert.NotNull(objectCreationOperation);
comp.VerifyOperationTree(creation, expectedOperationTree:
@"
IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object, IsInvalid) (Syntax: 'new object()')
Arguments(0)
Initializer:
null
");
Assert.Equal(OperationKind.ExpressionStatement, objectCreationOperation.Parent.Kind);
Assert.Equal(OperationKind.Block, objectCreationOperation.Parent.Parent.Kind);
Assert.Same(localFunctionOperation.IgnoredBody, objectCreationOperation.Parent.Parent);
var info = model.GetTypeInfo(creation);
Assert.Equal("System.Object", info.Type.ToTestDisplayString());
Assert.Equal("System.Object", info.ConvertedType.ToTestDisplayString());
}
[Fact]
[WorkItem(22027, "https://github.com/dotnet/roslyn/issues/22027")]
public void Repro22027()
{
CompileAndVerify(@"
class Program
{
static void Main(string[] args)
{
}
public object TestLocalFn(object inp)
{
try
{
var sr = new object();
return sr;
void Local1()
{
var copy = inp;
Local2();
}
void Local2()
{
}
}
catch { throw; }
}
}");
}
[Fact]
[WorkItem(21768, "https://github.com/dotnet/roslyn/issues/21768")]
public void Repro21768()
{
var comp = CreateCompilation(@"
using System;
using System.Linq;
class C
{
void Function(int someField) //necessary to have a parameter
{
using (IInterface db = null) //necessary to have this using statement
{
void LocalFunction() //necessary
{
var results =
db.Query<Class1>() //need to call this method. using a constant array does not reproduce the bug.
.Where(cje => cje.SomeField >= someField) //need expression tree here referencing parameter
;
}
}
}
interface IInterface : IDisposable
{
IQueryable<T> Query<T>();
}
class Class1
{
public int SomeField { get; set; }
}
}");
CompileAndVerify(comp);
}
[Fact]
[WorkItem(21811, "https://github.com/dotnet/roslyn/issues/21811")]
public void Repro21811()
{
var comp = CreateCompilation(@"
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var history = new List<long>();
Enumerable.Range(0, 5)
.Select(i =>
{
history.Insert(0, i);
return Test(i);
bool Test(int v)
{
history.Remove(0);
return Square(v) > 5;
}
int Square(int w)
{
return w * w;
}
});
}
}");
}
[Fact]
[WorkItem(21645, "https://github.com/dotnet/roslyn/issues/21645")]
public void Repro21645()
{
CompileAndVerify(@"
public class Class1
{
private void Test()
{
bool outside = true;
void Inner() //This can also be a lambda (ie. Action action = () => { ... };)
{
void Bar()
{
}
void Foo()
{
Bar();
bool captured = outside;
}
}
}
}");
}
[Fact]
[WorkItem(21543, "https://github.com/dotnet/roslyn/issues/21543")]
public void Repro21543()
{
CompileAndVerify(@"
using System;
class Program
{
static void Method(Action action) { }
static void Main()
{
int value = 0;
Method(() =>
{
local();
void local()
{
Console.WriteLine(value);
Method(() =>
{
local();
});
}
});
}
}");
}
[Fact]
[WorkItem(472056, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=472056")]
public void Repro472056()
{
var comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
var task = WhyYouBreaky(new List<string>());
Console.WriteLine(task.Result);
}
static async Task<string> WhyYouBreaky(List<string> words)
{
await Task.Delay(1);
var word = """"; // moving me before the 'await' will make it work
words.Add(""Oh No!""); // I will crash here :(
return ""Great success!""; // Not so much.
void IDontEvenGetCalled()
{
// commenting out either of these lines will make it work
var a = word;
var b = words[0];
}
}
}
}", options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "Great success!");
}
[Fact]
public void AsyncStructClosure()
{
var comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Threading.Tasks;
class C
{
static void Main() => M().Wait();
static async Task M()
{
int x = 2;
int y = 3;
int L() => x + y;
Console.WriteLine(L());
await Task.FromResult(false);
}
}", options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: "5");
// No field captures
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"System.Runtime.CompilerServices.AsyncTaskMethodBuilder <>t__builder",
"System.Runtime.CompilerServices.TaskAwaiter<bool> <>u__1");
comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Threading.Tasks;
class C
{
static void Main() => M().Wait();
static async Task M()
{
int x = 2;
int y = 3;
int L() => x + y;
Console.WriteLine(L());
await Task.FromResult(false);
x++;
Console.WriteLine(x);
}
}", options: TestOptions.ReleaseExe);
verifier = CompileAndVerify(comp, expectedOutput: @"5
3");
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"System.Runtime.CompilerServices.AsyncTaskMethodBuilder <>t__builder",
// Display class capture
"C.<>c__DisplayClass1_0 <>8__1",
"System.Runtime.CompilerServices.TaskAwaiter<bool> <>u__1");
verifier.VerifySynthesizedFields("C.<>c__DisplayClass1_0",
"int x",
"int y");
comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Threading.Tasks;
class C
{
static void Main() => M().Wait();
static async Task M()
{
int x = 2;
int y = 3;
int L() => x + y;
Console.WriteLine(L());
await Task.FromResult(false);
x = 5;
y = 7;
Console.WriteLine(L());
}
}", options: TestOptions.ReleaseExe);
verifier = CompileAndVerify(comp, expectedOutput: @"5
12");
// Nothing captured across await
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"System.Runtime.CompilerServices.AsyncTaskMethodBuilder <>t__builder",
"System.Runtime.CompilerServices.TaskAwaiter<bool> <>u__1");
}
[Fact]
public void IteratorStructClosure()
{
var verifier = CompileAndVerify(@"
using System;
using System.Collections.Generic;
class C
{
static void Main()
{
foreach (var m in M())
{
Console.WriteLine(m);
}
}
static IEnumerable<int> M()
{
int x = 2;
int y = 3;
int L() => x + y;
yield return L();
}
}", expectedOutput: "5");
// No field captures
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"int <>2__current",
"int <>l__initialThreadId");
verifier = CompileAndVerify(@"
using System;
using System.Collections.Generic;
class C
{
static void Main()
{
foreach (var m in M())
{
Console.WriteLine(m);
}
}
static IEnumerable<int> M()
{
int x = 2;
int y = 3;
int L() => x + y;
yield return L();
x++;
yield return x;
}
}", expectedOutput: @"5
3");
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"int <>2__current",
"int <>l__initialThreadId",
// Display class capture
"C.<>c__DisplayClass1_0 <>8__1");
verifier.VerifySynthesizedFields("C.<>c__DisplayClass1_0",
"int x",
"int y");
verifier = CompileAndVerify(@"
using System;
using System.Collections.Generic;
class C
{
static void Main()
{
foreach (var m in M())
{
Console.WriteLine(m);
}
}
static IEnumerable<int> M()
{
int x = 2;
int y = 3;
int L() => x + y;
yield return L();
x = 5;
y = 7;
yield return L();
}
}", expectedOutput: @"5
12");
// No captures
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"int <>2__current",
"int <>l__initialThreadId");
}
[Fact]
[WorkItem(21409, "https://github.com/dotnet/roslyn/issues/21409")]
public void Repro21409()
{
CompileAndVerify(
@"
using System;
using System.Collections.Generic;
namespace Buggles
{
class Program
{
private static IEnumerable<int> Problem(IEnumerable<int> chunks)
{
var startOfChunk = 0;
var pendingChunks = new List<int>();
int GenerateChunk()
{
if (pendingChunks == null)
{
Console.WriteLine(""impossible in local function"");
return -1;
}
while (pendingChunks.Count > 0)
{
pendingChunks.RemoveAt(0);
}
return startOfChunk;
}
foreach (var chunk in chunks)
{
if (chunk - startOfChunk <= 0)
{
pendingChunks.Insert(0, chunk);
}
else
{
yield return GenerateChunk();
}
startOfChunk = chunk;
if (pendingChunks == null)
{
Console.WriteLine(""impossible in outer function"");
}
else
{
pendingChunks.Insert(0, chunk);
}
}
}
private static void Main()
{
var xs = Problem(new[] { 0, 1, 2, 3 });
foreach (var x in xs)
{
Console.WriteLine(x);
}
}
}
}
", expectedOutput: @"
0
1
2");
}
[Fact]
[WorkItem(294554, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=294554")]
public void ThisOnlyClosureBetweenStructCaptures()
{
CompileAndVerify(@"
using System;
class C
{
int _x = 0;
void M()
{
void L1()
{
int x = 0;
_x++;
void L2()
{
Action a2 = L2;
int y = 0;
L3();
void L3()
{
_x++;
y++;
}
}
L2();
void L5() => x++;
L5();
}
L1();
}
}");
}
[Fact]
public void CaptureThisInDifferentScopes()
{
CompileAndVerify(@"
using System;
class C
{
int _x;
void M()
{
{
int y = 0;
Func<int> f1 = () => _x + y;
}
{
int y = 0;
Func<int> f2 = () => _x + y;
}
}
}");
}
[Fact]
public void CaptureThisInDifferentScopes2()
{
CompileAndVerify(@"
using System;
class C
{
int _x;
void M()
{
{
int y = 0;
int L1() => _x + y;
}
{
int y = 0;
int L2() => _x + y;
}
}
}");
}
[Fact]
public void CaptureFramePointerInDifferentScopes()
{
CompileAndVerify(@"
using System;
class C
{
void M(int x)
{
Func<int> f1 = () => x;
{
int z = 0;
Func<int> f2 = () => x + z;
}
{
int z = 0;
Func<int> f3 = () => x + z;
}
}
}");
}
[Fact]
public void EnvironmentChainContainsStructEnvironment()
{
CompileAndVerify(@"
using System;
class C
{
void M(int x)
{
{
int y = 10;
void L() => Console.WriteLine(y);
{
int z = 5;
Action f2 = () => Console.WriteLine(z + x);
f2();
}
L();
}
}
public static void Main() => new C().M(3);
}", expectedOutput: @"8
10");
}
[Fact]
public void Repro20577()
{
var comp = CreateCompilation(@"
using System.Linq;
public class Program {
public static void Main(string[] args) {
object v;
void AAA() {
object BBB(object v2) {
var a = v;
((object[])v2).Select(i => BBB(i));
return null;
}
}
}
}");
CompileAndVerify(comp);
}
[Fact]
public void Repro19033()
{
CompileAndVerify(@"
using System;
class Program
{
void Q(int n = 0)
{
{
object mc;
string B(object map)
{
Action<int> a = _ => B(new object());
return n.ToString();
}
}
}
}");
}
[Fact]
public void Repro19033_2()
{
CompileAndVerify(@"
using System;
class C
{
static void F(Action a)
{
object x = null;
{
object y = null;
void G(object z)
{
F(() => G(x));
}
}
}
}");
}
[Fact]
[WorkItem(18814, "https://github.com/dotnet/roslyn/issues/18814")]
[WorkItem(18918, "https://github.com/dotnet/roslyn/issues/18918")]
public void IntermediateStructClosures1()
{
var verifier = CompileAndVerify(@"
using System;
class C
{
int _x = 0;
public static void Main() => new C().M();
public void M()
{
int var1 = 0;
void L1()
{
void L2()
{
void L3()
{
void L4()
{
int var2 = 0;
void L5()
{
int L6() => var2 + _x++;
L6();
}
L5();
}
L4();
}
L3();
}
L2();
int L8() => var1;
}
Console.WriteLine(_x);
L1();
Console.WriteLine(_x);
}
}", expectedOutput:
@"0
1");
verifier.VerifyIL("C.M()", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (C.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: ldloca.s V_0
IL_0002: ldarg.0
IL_0003: stfld ""C C.<>c__DisplayClass2_0.<>4__this""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.0
IL_000b: stfld ""int C.<>c__DisplayClass2_0.var1""
IL_0010: ldarg.0
IL_0011: ldfld ""int C._x""
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: ldarg.0
IL_001c: ldloca.s V_0
IL_001e: call ""void C.<M>g__L1|2_0(ref C.<>c__DisplayClass2_0)""
IL_0023: ldarg.0
IL_0024: ldfld ""int C._x""
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: ret
}");
// L1
verifier.VerifyIL("C.<M>g__L1|2_0(ref C.<>c__DisplayClass2_0)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""void C.<M>g__L2|2_1(ref C.<>c__DisplayClass2_0)""
IL_0007: ret
}");
// L2
verifier.VerifyIL("C.<M>g__L2|2_1(ref C.<>c__DisplayClass2_0)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""void C.<M>g__L3|2_3(ref C.<>c__DisplayClass2_0)""
IL_0007: ret
}");
// Skip some... L5
verifier.VerifyIL("C.<M>g__L5|2_5(ref C.<>c__DisplayClass2_0, ref C.<>c__DisplayClass2_1)", @"
{
// Code size 10 (0xa)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: call ""int C.<M>g__L6|2_6(ref C.<>c__DisplayClass2_0, ref C.<>c__DisplayClass2_1)""
IL_0008: pop
IL_0009: ret
}");
// L6
verifier.VerifyIL("C.<M>g__L6|2_6(ref C.<>c__DisplayClass2_0, ref C.<>c__DisplayClass2_1)", @"
{
// Code size 25 (0x19)
.maxstack 4
.locals init (int V_0)
IL_0000: ldarg.2
IL_0001: ldfld ""int C.<>c__DisplayClass2_1.var2""
IL_0006: ldarg.0
IL_0007: ldarg.0
IL_0008: ldfld ""int C._x""
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: ldc.i4.1
IL_0010: add
IL_0011: stfld ""int C._x""
IL_0016: ldloc.0
IL_0017: add
IL_0018: ret
}");
}
[Fact]
[WorkItem(18814, "https://github.com/dotnet/roslyn/issues/18814")]
[WorkItem(18918, "https://github.com/dotnet/roslyn/issues/18918")]
public void IntermediateStructClosures2()
{
CompileAndVerify(@"
class C
{
int _x;
void M()
{
int y = 0;
void L1()
{
void L2()
{
int z = 0;
int L3() => z + _x;
}
y++;
}
}
}");
}
[Fact]
[WorkItem(18814, "https://github.com/dotnet/roslyn/issues/18814")]
public void Repro18814()
{
CompileAndVerify(@"
class Program
{
private void ResolvingPackages()
{
string outerScope(int a) => """";
void C1(int cabinetIdx)
{
void modifyState()
{
var no = outerScope(cabinetIdx);
}
modifyState();
}
}
}");
}
[Fact]
[WorkItem(18918, "https://github.com/dotnet/roslyn/issues/18918")]
public void Repro18918()
{
CompileAndVerify(@"
public class Test
{
private int _field;
public void OuterMethod(int outerParam)
{
void InnerMethod1()
{
void InnerInnerMethod(int innerInnerParam)
{
InnerInnerInnerMethod();
bool InnerInnerInnerMethod()
{
return innerInnerParam != _field;
}
}
void InnerMethod2()
{
var temp = outerParam;
}
}
}
}");
}
[Fact]
[WorkItem(17719, "https://github.com/dotnet/roslyn/issues/17719")]
public void Repro17719()
{
var comp = CompileAndVerify(@"
using System;
class C
{
public static void Main()
{
T GetField<T>(string name, T @default = default(T))
{
return @default;
}
Console.WriteLine(GetField<int>(string.Empty));
}
}", expectedOutput: "0");
}
[Fact]
[WorkItem(17890, "https://github.com/dotnet/roslyn/issues/17890")]
public void Repro17890()
{
var comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Collections.Generic;
using System.Linq;
public class Class
{
public class Item
{
public int Id { get; set; }
}
public class ItemsContainer : IDisposable
{
public List<Item> Items { get; set; }
public void Dispose()
{
}
}
public static void CompilerError()
{
using (var itemsContainer = new ItemsContainer())
{
Item item = null;
itemsContainer.Items.Where(x => x.Id == item.Id);
void Local1()
{
itemsContainer.Items = null;
}
void Local2()
{
Local1();
}
}
}
}", references: new[] { LinqAssemblyRef });
CompileAndVerify(comp);
}
[Fact]
[WorkItem(16783, "https://github.com/dotnet/roslyn/issues/16783")]
public void GenericDefaultParams()
{
CompileAndVerify(@"
using System;
class C
{
public void M()
{
void Local<T>(T t = default(T))
{
Console.WriteLine(t);
}
Local<int>();
}
}
class C2
{
public static void Main()
{
new C().M();
}
}", expectedOutput: "0");
}
[Fact]
public void GenericCaptureDefaultParams()
{
CompileAndVerify(@"
using System;
class C<T>
{
public void M()
{
void Local(T t = default(T))
{
Console.WriteLine(t);
}
Local();
}
}
class C2
{
public static void Main()
{
new C<int>().M();
}
}", expectedOutput: "0");
}
[Fact]
public void NameofRecursiveDefaultParameter()
{
var comp = CreateCompilation(@"
using System;
class C
{
public static void Main()
{
void Local(string s = nameof(Local))
{
Console.WriteLine(s);
}
Local();
}
}", options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
comp.DeclarationDiagnostics.Verify();
CompileAndVerify(comp, expectedOutput: "Local");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope()
{
var src = @"
using System;
class C
{
public static void Main()
{
var d = """";
{
int x = 0;
void M()
{
if (d != null)
{
Action a = () => x++;
a();
}
}
M();
Console.WriteLine(x);
}
}
}";
CompileAndVerify(src, expectedOutput: "1");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope2()
{
var src = @"
using System;
class C
{
class D : IDisposable { public void Dispose() {} }
public static void Main()
{
using (var d = new D())
{
int x = 0;
void M()
{
if (d != null)
{
Action a = () => x++;
a();
}
}
M();
Console.WriteLine(x);
}
}
}";
CompileAndVerify(src, expectedOutput: "1");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope3()
{
var src = @"
using System;
class C
{
public static void Main()
{
var d = """";
{
int x = 0;
void M()
{
if (d != null)
{
void Local() => x++;
Action a = Local;
a();
}
}
M();
Console.WriteLine(x);
}
}
}";
CompileAndVerify(src, expectedOutput: "1");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope4()
{
var src = @"
using System;
class C
{
public static void Main()
{
var d = """";
{
int y = 0;
{
int x = 0;
void M()
{
if (d != null)
{
Action a = () => x++;;
a();
}
}
M();
Console.WriteLine(x);
}
y++;
}
}
}";
CompileAndVerify(src, expectedOutput: "1");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope5()
{
var src = @"
using System;
class C
{
public static void Main()
{
int x = 0;
{
int y = 0;
void L()
{
int z = 0;
void L2()
{
if (x == 0 && z == 0)
{
Action a = () => y++;
a();
}
}
L2();
}
L();
Console.WriteLine(y);
}
}
}";
CompileAndVerify(src, expectedOutput: "1");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope6()
{
var src = @"
using System;
class C
{
public static void Main()
{
int x = 0;
{
int y = 0;
void L()
{
int z = 0;
void L2()
{
if (x == 0 && y == 0)
{
Action a = () => z++;
a();
}
y++;
}
L2();
Console.WriteLine(z);
}
L();
Console.WriteLine(y);
}
((Action)(() => x++))();
Console.WriteLine(x);
}
}";
CompileAndVerify(src, expectedOutput: @"1
1
1");
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope7()
{
var src = @"
using System;
using System.Threading.Tasks;
class C
{
public static void Main()
{
int x = 0;
{
int y = 0;
void L()
{
if (x == 0)
{
async Task L2()
{
await Task.Delay(1);
y++;
}
L2().Wait();
}
}
L();
Console.WriteLine(y);
}
Console.WriteLine(x);
}
}";
CompileAndVerify(src,
targetFramework: TargetFramework.Mscorlib46,
expectedOutput: @"1
0");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope8()
{
var src = @"
using System;
using System.Collections.Generic;
class C
{
public static void Main()
{
int x = 0;
{
int y = 0;
void L()
{
if (x == 0)
{
IEnumerable<int> L2()
{
yield return 0;
y++;
}
foreach (var i in L2()) { }
}
}
L();
Console.WriteLine(y);
}
Console.WriteLine(x);
}
}";
CompileAndVerifyWithMscorlib46(src,
expectedOutput: @"1
0");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void LocalFunctionCaptureSkipScope()
{
var src = @"
using System;
class C
{
public static void Main(string[] args)
{
{
int uncaptured = 0;
uncaptured++;
{
int x = 0;
bool Local(int y) => x == 0 && args == null && y == 0;
Local(0);
}
}
}
}";
CompileAndVerify(src);
}
[Fact]
[WorkItem(16399, "https://github.com/dotnet/roslyn/issues/16399")]
public void RecursiveGenericLocalFunctionIterator()
{
var src = @"
using System;
using System.Collections.Generic;
using System.Linq;
public static class EnumerableExtensions
{
static void Main(string[] args)
{
GetLeaves<object>(new List<object>(), list => null);
var results = GetLeaves<object>(
new object[] {
new[] { ""a"", ""b""},
new[] { ""c"" },
new[] { new[] { ""d"" } }
}, node => node is string ? null : (IEnumerable<object>)node);
foreach (var i in results)
{
Console.WriteLine(i);
}
}
public static IEnumerable<T> GetLeaves<T>(T root, Func<T, IEnumerable<T>> getChildren)
{
return GetLeaves(root);
IEnumerable<T> GetLeaves(T node)
{
var children = getChildren(node);
if (children == null)
{
return new[] { node };
}
else
{
return children.SelectMany(GetLeaves);
}
}
}
}";
VerifyOutput(src, @"a
b
c
d");
}
[Fact]
[WorkItem(243633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/243633")]
public void CaptureGenericFieldAndParameter()
{
var src = @"
using System;
using System.Collections.Generic;
class Test<T>
{
T Value;
public bool Goo(IEqualityComparer<T> comparer)
{
bool local(T tmp)
{
return comparer.Equals(tmp, this.Value);
}
return local(this.Value);
}
}
";
var comp = CompileAndVerify(src);
}
[Fact]
public void CaptureGenericField()
{
var src = @"
using System;
class C<T>
{
T Value = default(T);
public void M()
{
void L()
{
Console.WriteLine(Value);
}
var f = (Action)(() => L());
f();
}
}
class C2
{
public static void Main(string[] args) => new C<int>().M();
}
";
VerifyOutput(src, "0");
}
[Fact]
public void CaptureGenericParam()
{
var src = @"
using System;
class C<T>
{
T Value = default(T);
public void M<U>(U val2)
{
void L()
{
Console.WriteLine(Value);
Console.WriteLine(val2);
}
var f = (Action)(() => L());
f();
}
}
class C2
{
public static void Main(string[] args) => new C<int>().M(10);
}
";
VerifyOutput(src, @"0
10");
}
[Fact]
public void CaptureGenericParamInGenericLocalFunc()
{
var src = @"
using System;
class C<T>
{
T Value = default(T);
public void M<U>(U v1)
{
void L<V>(V v2) where V : T
{
Console.WriteLine(Value);
Console.WriteLine(v1);
Console.WriteLine(v2);
}
var f = (Action)(() => L<T>(Value));
f();
}
}
class C2
{
public static void Main(string[] args) => new C<int>().M(10);
}
";
VerifyOutput(src, @"0
10
0");
}
[Fact]
public void DeepNestedLocalFuncsWithDifferentCaptures()
{
var src = @"
using System;
class C
{
int P = 100000;
void M()
{
C Local1() => this;
int capture1 = 1;
Func<int> f1 = () => capture1 + Local1().P;
Console.WriteLine(f1());
{
C Local2() => Local1();
int capture2 = 10;
Func<int> f2 = () => capture2 + Local2().P;
Console.WriteLine(f2());
{
C Local3() => Local2();
int capture3 = 100;
Func<int> f3 = () => capture1 + capture2 + capture3 + Local3().P;
Console.WriteLine(f3());
Console.WriteLine(Local3().P);
}
}
}
public static void Main() => new C().M();
}";
VerifyOutput(src, @"100001
100010
100111
100000");
}
[Fact]
public void LotsOfMutuallyRecursiveLocalFunctions()
{
var src = @"
class C
{
int P = 0;
public void M()
{
int Local1() => this.P;
int Local2() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local3() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local4() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local5() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local6() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local7() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local8() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local9() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local10() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local11() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local12() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
Local1();
Local2();
Local3();
Local4();
Local5();
Local6();
Local7();
Local8();
Local9();
Local10();
Local11();
Local12();
}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void LocalFuncAndLambdaWithDifferentThis()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local(int x) => x + this.P;
int y = 10;
var a = new Func<int>(() => Local(y));
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "11");
}
[Fact]
public void LocalFuncAndLambdaWithDifferentThis2()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local() => 10 + this.P;
int Local2(int x) => x + Local();
int y = 100;
var a = new Func<int>(() => Local2(y));
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "111");
}
[Fact]
public void LocalFuncAndLambdaWithDifferentThis3()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local()
{
if (this.P < 5)
{
return Local2(this.P++);
}
else
{
return 1;
}
}
int Local2(int x) => x + Local();
int y = 100;
var a = new Func<int>(() => Local2(y));
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "111");
}
[Fact]
public void LocalFuncAndLambdaWithDifferentThis4()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local(int x) => x + this.P;
int y = 10;
var a = new Func<int>(() =>
{
var b = (Func<int, int>)Local;
return b(y);
});
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "11");
}
[Fact]
public void LocalFuncAndLambdaWithDifferentThis5()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local(int x) => x + this.P;
int y = 10;
var a = new Func<int>(() =>
{
var b = new Func<int, int>(Local);
return b(y);
});
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "11");
}
[Fact]
public void TwoFrames()
{
var src = @"
using System;
class C
{
private int P = 0;
public void M()
{
int x = 0;
var a = new Func<int>(() =>
{
int Local() => x + this.P;
int z = 0;
int Local3() => z + Local();
return Local3();
});
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "0");
}
[Fact]
public void SameFrame()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int x = 10;
int Local() => x + this.P;
int y = 100;
int Local2() => y + Local();
Console.WriteLine(Local2());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "111");
}
[Fact]
public void MutuallyRecursiveThisCapture()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local()
{
if (this.P < 5)
{
return Local2(this.P++);
}
else
{
return 1;
}
}
int Local2(int x) => x + Local();
Console.WriteLine(Local());
}
public static void Main() => new C().M();
}";
VerifyOutput(src, "11");
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicParameterLocalFunction()
{
var src = @"
using System;
class C
{
static void Main(string[] args) => M(0);
static void M(int x)
{
dynamic y = x + 1;
Action a;
Action local(dynamic z)
{
Console.Write(z);
Console.Write(y);
return () => Console.Write(y + z + 1);
}
a = local(x);
a();
}
}";
VerifyOutput(src, "012");
}
[Fact]
public void EndToEnd()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
void Local()
{
Console.WriteLine(""Hello, world!"");
}
Local();
}
}
";
VerifyOutput(source, "Hello, world!");
}
[Fact]
[CompilerTrait(CompilerFeature.ExpressionBody)]
public void ExpressionBody()
{
var source = @"
int Local() => 2;
Console.Write(Local());
Console.Write(' ');
void VoidLocal() => Console.Write(2);
VoidLocal();
";
VerifyOutputInMain(source, "2 2", "System");
}
[Fact]
public void EmptyStatementAfter()
{
var source = @"
void Local()
{
Console.Write(2);
};
Local();
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
[CompilerTrait(CompilerFeature.Params)]
public void Params()
{
var source = @"
void Params(params int[] x)
{
Console.WriteLine(string.Join("","", x));
}
Params(2);
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void RefAndOut()
{
var source = @"
void RefOut(ref int x, out int y)
{
y = ++x;
}
int a = 1;
int b;
RefOut(ref a, out b);
Console.Write(a);
Console.Write(' ');
Console.Write(b);
";
VerifyOutputInMain(source, "2 2", "System");
}
[Fact]
public void NamedAndOptional()
{
var source = @"
void NamedOptional(int x = 2)
{
Console.Write(x);
}
NamedOptional(x: 3);
Console.Write(' ');
NamedOptional();
";
VerifyOutputInMain(source, "3 2", "System");
}
[Fact, WorkItem(51518, "https://github.com/dotnet/roslyn/issues/51518")]
public void OptionalParameterCodeGen()
{
var source = @"
public class C
{
public static void Main()
{
LocalFunc();
void LocalFunc(int a = 2) { }
}
}
";
var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedSignatures: new SignatureDescription[]
{
Signature("C", "Main", ".method public hidebysig static System.Void Main() cil managed"),
Signature("C", "<Main>g__LocalFunc|0_0", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] assembly hidebysig static System.Void <Main>g__LocalFunc|0_0([opt] System.Int32 a = 2) cil managed")
});
}
[Fact, WorkItem(53478, "https://github.com/dotnet/roslyn/issues/53478")]
public void OptionalParameterCodeGen_Reflection()
{
VerifyOutputInMain(@"void TestAction(int i = 5) { }
var d = (Action<int>)TestAction;
var p2 = d.Method.GetParameters();
Console.WriteLine(p2[0].HasDefaultValue);
Console.WriteLine(p2[0].DefaultValue);", @"True
5", new[] { "System" });
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicArgShadowing()
{
var src = @"
using System;
class C
{
static void Shadow(int x) => Console.Write(x + 1);
static void Main()
{
void Shadow(int x) => Console.Write(x);
dynamic val = 2;
Shadow(val);
}
}";
VerifyOutput(src, "2");
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicParameter()
{
var source = @"
using System;
class Program
{
static void Main()
{
void Local(dynamic x)
{
Console.Write(x);
}
Local(2);
}
}
";
VerifyOutput(source, "2");
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicReturn()
{
var source = @"
dynamic RetDyn()
{
return 2;
}
Console.Write(RetDyn());
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicDelegate()
{
var source = @"
using System;
class Program
{
static void Main()
{
dynamic Local(dynamic x)
{
return x;
}
dynamic L2(int x)
{
void L2_1(int y)
{
Console.Write(x);
Console.Write(y);
}
dynamic z = x + 1;
void L2_2() => L2_1(z);
return (Action)L2_2;
}
dynamic local = (Func<dynamic, dynamic>)Local;
Console.Write(local(2));
L2(3)();
}
}
";
VerifyOutput(source, "234");
}
[Fact]
public void Nameof()
{
var source = @"
void Local()
{
}
Console.Write(nameof(Local));
";
VerifyOutputInMain(source, "Local", "System");
}
[Fact]
public void ExpressionTreeParameter()
{
var source = @"
Expression<Func<int, int>> Local(Expression<Func<int, int>> f)
{
return f;
}
Console.Write(Local(x => x));
";
VerifyOutputInMain(source, "x => x", "System", "System.Linq.Expressions");
}
[Fact]
public void LinqInLocalFunction()
{
var source = @"
IEnumerable<int> Query(IEnumerable<int> values)
{
return from x in values where x < 5 select x * x;
}
Console.Write(string.Join("","", Query(Enumerable.Range(0, 10))));
";
VerifyOutputInMain(source, "0,1,4,9,16", "System", "System.Linq", "System.Collections.Generic");
}
[Fact]
public void ConstructorWithoutArg()
{
var source = @"
using System;
class Base
{
public int x;
public Base(int x)
{
this.x = x;
}
}
class Program : Base
{
Program() : base(2)
{
void Local()
{
Console.Write(x);
}
Local();
}
public static void Main()
{
new Program();
}
}
";
VerifyOutput(source, "2");
}
[Fact]
public void ConstructorWithArg()
{
var source = @"
using System;
class Base
{
public int x;
public Base(int x)
{
this.x = x;
}
}
class Program : Base
{
Program(int x) : base(x + 2)
{
void Local()
{
Console.Write(x);
Console.Write(' ');
Console.Write(base.x);
}
Local();
}
public static void Main()
{
new Program(2);
}
}
";
VerifyOutput(source, "2 4");
}
[Fact]
public void IfDef()
{
var source = @"
using System;
class Program
{
public static void Main()
{
#if LocalFunc
void Local()
{
Console.Write(2);
Console.Write(' ');
#endif
Console.Write(4);
#if LocalFunc
}
Local();
#endif
}
}
";
VerifyOutput(source, "4");
source = "#define LocalFunc" + source;
VerifyOutput(source, "2 4");
}
[Fact]
public void PragmaWarningDisableEntersLocfunc()
{
var source = @"
#pragma warning disable CS0168
void Local()
{
int x; // unused
Console.Write(2);
}
#pragma warning restore CS0168
Local();
";
// No diagnostics is asserted in VerifyOutput, so if the warning happens, then we'll catch it
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void ObsoleteAttributeRecursion()
{
var source = @"
using System;
class Program
{
[Obsolete]
public void Obs()
{
void Local()
{
Obs(); // shouldn't emit warning
}
Local();
}
public static void Main()
{
Console.Write(2);
}
}
";
VerifyOutput(source, "2");
}
[Fact]
public void MainLocfuncIsntEntry()
{
var source = @"
void Main()
{
Console.Write(4);
}
Console.Write(2);
Console.Write(' ');
Main();
";
VerifyOutputInMain(source, "2 4", "System");
}
[Fact]
public void Shadows()
{
var source = @"
using System;
class Program
{
static void Local()
{
Console.WriteLine(""bad"");
}
static void Main(string[] args)
{
void Local()
{
Console.Write(2);
}
Local();
}
}
";
VerifyOutput(source, "2");
}
[Fact]
public void ExtensionMethodClosure()
{
var source = @"
using System;
static class Program
{
public static void Ext(this int x)
{
void Local()
{
Console.Write(x);
}
Local();
}
public static void Main()
{
2.Ext();
}
}
";
// warning level 0 because extension method generates CS1685 (predefined type multiple definition) for ExtensionAttribute in System.Core and mscorlib
VerifyOutput(source, "2", TestOptions.ReleaseExe.WithWarningLevel(0));
}
[Fact]
public void Scoping()
{
var source = @"
void Local()
{
Console.Write(2);
}
if (true)
{
Local();
}
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void Property()
{
var source = @"
using System;
class Program
{
static int Goo
{
get
{
int Local()
{
return 2;
}
return Local();
}
}
static void Main(string[] args)
{
Console.Write(Goo);
}
}";
VerifyOutput(source, "2");
}
[Fact]
public void PropertyIterator()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
static int Goo
{
get
{
int a = 2;
IEnumerable<int> Local()
{
yield return a;
}
foreach (var x in Local())
{
return x;
}
return 0;
}
}
static void Main(string[] args)
{
Console.Write(Goo);
}
}";
VerifyOutput(source, "2");
}
[Fact]
public void DelegateFunc()
{
var source = @"
int Local(int x) => x;
Func<int, int> local = Local;
Console.Write(local(2));
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void DelegateFuncGenericImplicit()
{
var source = @"
T Local<T>(T x) => x;
Func<int, int> local = Local;
Console.Write(local(2));
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void DelegateFuncGenericExplicit()
{
var source = @"
T Local<T>(T x) => x;
Func<int, int> local = Local<int>;
Console.Write(local(2));
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void DelegateAction()
{
var source = @"
void Local()
{
Console.Write(2);
}
var local = new Action(Local);
local();
Console.Write(' ');
local = (Action)Local;
local();
";
VerifyOutputInMain(source, "2 2", "System");
}
[Fact]
public void InterpolatedString()
{
var source = @"
int x = 1;
int Bar() => ++x;
var str = $@""{((Func<int>)(() => { int Goo() => Bar(); return Goo(); }))()}"";
Console.Write(str + ' ' + x);
";
VerifyOutputInMain(source, "2 2", "System");
}
// StaticNoClosure*() are generic because the reference to the locfunc is constructed, and actual local function is not
// (i.e. testing to make sure we use MethodSymbol.OriginalDefinition in LambdaRewriter.Analysis)
[Fact]
public void StaticNoClosure()
{
var source = @"
T Goo<T>(T x)
{
return x;
}
Console.Write(Goo(2));
";
var verify = VerifyOutputInMain(source, "2", "System");
var goo = verify.FindLocalFunction("Goo");
Assert.True(goo.IsStatic);
Assert.Equal(verify.Compilation.GetTypeByMetadataName("Program"), goo.ContainingType);
}
[Fact]
public void StaticNoClosureDelegate()
{
var source = @"
T Goo<T>(T x)
{
return x;
}
Func<int, int> goo = Goo;
Console.Write(goo(2));
";
var verify = VerifyOutputInMain(source, "2", "System");
var goo = verify.FindLocalFunction("Goo");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.True(goo.IsStatic);
Assert.Equal(program, goo.ContainingType);
}
[Fact]
public void ClosureBasic()
{
var source = @"
using System;
class Program
{
static void Print(int a)
{
Console.Write(' ');
Console.Write(a);
}
static void A(int y)
{
int x = 1;
void Local()
{
Print(x); Print(y);
}
Local();
Print(x); Print(y);
x = 3;
y = 4;
Local();
Print(x); Print(y);
void Local2()
{
Print(x); Print(y);
x += 2;
y += 2;
Print(x); Print(y);
}
Local2();
Print(x); Print(y);
}
static void Main(string[] args)
{
A(2);
}
}
";
VerifyOutput(source, "1 2 1 2 3 4 3 4 3 4 5 6 5 6");
}
[Fact]
public void ClosureThisOnly()
{
var source = @"
using System;
class Program
{
int _a;
static void Print(int a)
{
Console.Write(' ');
Console.Write(a);
}
void B()
{
_a = 2;
void Local()
{
Print(_a);
_a++;
Print(_a);
}
Print(_a);
Local();
Print(_a);
}
static void Main(string[] args)
{
new Program().B();
}
}";
VerifyOutput(source, "2 2 3 3");
}
[Fact]
public void ClosureGeneralThisOnly()
{
var source = @"
var x = 0;
void Outer()
{
if (++x == 2)
{
Console.Write(x);
return;
}
void Inner()
{
Outer();
}
Inner();
}
Outer();
";
var verify = VerifyOutputInMain(source, "2", "System");
var outer = verify.FindLocalFunction("Outer");
var inner = verify.FindLocalFunction("Inner");
Assert.Equal(outer.ContainingType, inner.ContainingType);
}
[Fact]
public void ClosureStaticInInstance()
{
var source = @"
using System;
class Program
{
static int _sa;
static void Print(int a)
{
Console.Write(' ');
Console.Write(a);
}
void C()
{
_sa = 2;
void Local()
{
Print(_sa);
_sa++;
Print(_sa);
}
Print(_sa);
Local();
Print(_sa);
}
static void Main(string[] args)
{
new Program().C();
}
}";
VerifyOutput(source, "2 2 3 3");
}
[Fact]
public void ClosureGeneric()
{
var source = @"
using System;
class Program
{
static void Print(object a)
{
Console.Write(' ');
Console.Write(a);
}
class Gen<T1>
{
T1 t1;
public Gen(T1 t1)
{
this.t1 = t1;
}
public void D<T2>(T2 t2)
{
T2 Local(T1 x)
{
Print(x);
Print(t1);
t1 = (T1)(object)((int)(object)x + 2);
t2 = (T2)(object)x;
return (T2)(object)((int)(object)t2 + 4);
}
Print(t1);
Print(t2);
Print(Local(t1));
Print(t1);
Print(t2);
}
}
static void Main(string[] args)
{
new Gen<int>(2).D<int>(3);
}
}";
VerifyOutput(source, "2 3 2 2 6 4 2");
}
[Fact]
public void ClosureLambdasAndLocfuncs()
{
var source = @"
using System;
class Program
{
static void Print(int a)
{
Console.Write(' ');
Console.Write(a);
}
static void E()
{
int a = 2;
void M1()
{
int b = a;
Action M2 = () =>
{
int c = b;
void M3()
{
int d = c;
Print(d + b);
}
M3();
};
M2();
}
M1();
}
static void Main(string[] args)
{
E();
}
}";
VerifyOutput(source, "4");
}
[Fact]
public void ClosureTripleNested()
{
var source = @"
using System;
class Program
{
static void Print(int a)
{
Console.Write(' ');
Console.Write(a);
}
static void A()
{
int a = 0;
void M1()
{
int b = a;
void M2()
{
int c = b;
void M3()
{
Print(c);
c = 2;
}
Print(b);
M3();
Print(c);
b = 2;
}
Print(a);
M2();
Print(b);
a = 2;
}
M1();
Print(a);
}
static void B()
{
int a = 0;
void M1()
{
int b = a;
void M2()
{
void M3()
{
Print(b);
b = 2;
}
M3();
Print(b);
}
Print(a);
M2();
Print(b);
a = 2;
}
M1();
Print(a);
}
static void C()
{
int a = 0;
void M1()
{
void M2()
{
int c = a;
void M3()
{
Print(c);
c = 2;
}
Print(a);
M3();
Print(c);
a = 2;
}
M2();
Print(a);
}
M1();
Print(a);
}
static void D()
{
void M1()
{
int b = 0;
void M2()
{
int c = b;
void M3()
{
Print(c);
c = 2;
}
Print(b);
M3();
Print(c);
b = 2;
}
M2();
Print(b);
}
M1();
}
static void E()
{
int a = 0;
void M1()
{
void M2()
{
void M3()
{
Print(a);
a = 2;
}
M3();
Print(a);
}
M2();
Print(a);
}
M1();
Print(a);
}
static void F()
{
void M1()
{
int b = 0;
void M2()
{
void M3()
{
Print(b);
b = 2;
}
M3();
Print(b);
}
M2();
Print(b);
}
M1();
}
static void G()
{
void M1()
{
void M2()
{
int c = 0;
void M3()
{
Print(c);
c = 2;
}
M3();
Print(c);
}
M2();
}
M1();
}
static void Main(string[] args)
{
A();
Console.WriteLine();
B();
Console.WriteLine();
C();
Console.WriteLine();
D();
Console.WriteLine();
E();
Console.WriteLine();
F();
Console.WriteLine();
G();
Console.WriteLine();
}
}
";
VerifyOutput(source, @"
0 0 0 2 2 2
0 0 2 2 2
0 0 2 2 2
0 0 2 2
0 2 2 2
0 2 2
0 2
");
}
[Fact]
public void InstanceClosure()
{
var source = @"
using System;
class Program
{
int w;
int A(int y)
{
int x = 1;
int Local1(int z)
{
int Local2()
{
return Local1(x + y + w);
}
return z != -1 ? z : Local2();
}
return Local1(-1);
}
static void Main(string[] args)
{
var prog = new Program();
prog.w = 3;
Console.WriteLine(prog.A(2));
}
}
";
VerifyOutput(source, "6");
}
[Fact]
public void SelfClosure()
{
var source = @"
using System;
class Program
{
static int Test()
{
int x = 2;
int Local1(int y)
{
int Local2()
{
return Local1(x);
}
return y != 0 ? y : Local2();
}
return Local1(0);
}
static void Main(string[] args)
{
Console.WriteLine(Test());
}
}
";
VerifyOutput(source, "2");
}
[Fact]
public void StructClosure()
{
var source = @"
int x = 2;
void Goo()
{
Console.Write(x);
}
Goo();
";
var verify = VerifyOutputInMain(source, "2", "System");
var goo = verify.FindLocalFunction("Goo");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.Equal(program, goo.ContainingType);
Assert.True(goo.IsStatic);
Assert.Equal(RefKind.Ref, goo.Parameters[0].RefKind);
Assert.True(goo.Parameters[0].Type.IsValueType);
}
[Fact]
public void StructClosureGeneric()
{
var source = @"
int x = 2;
void Goo<T1>()
{
int y = x;
void Bar<T2>()
{
Console.Write(x + y);
}
Bar<T1>();
}
Goo<int>();
";
var verify = VerifyOutputInMain(source, "4", "System");
var goo = verify.FindLocalFunction("Goo");
var bar = verify.FindLocalFunction("Bar");
Assert.Equal(1, goo.Parameters.Length);
Assert.Equal(2, bar.Parameters.Length);
Assert.Equal(RefKind.Ref, goo.Parameters[0].RefKind);
Assert.Equal(RefKind.Ref, bar.Parameters[0].RefKind);
Assert.Equal(RefKind.Ref, bar.Parameters[1].RefKind);
Assert.True(goo.Parameters[0].Type.IsValueType);
Assert.True(bar.Parameters[0].Type.IsValueType);
Assert.True(bar.Parameters[1].Type.IsValueType);
Assert.Equal(goo.Parameters[0].Type.OriginalDefinition, bar.Parameters[0].Type.OriginalDefinition);
var gooFrame = (INamedTypeSymbol)goo.Parameters[0].Type;
var barFrame = (INamedTypeSymbol)bar.Parameters[1].Type;
Assert.Equal(0, gooFrame.Arity);
Assert.Equal(1, barFrame.Arity);
}
[Fact]
public void ClosureOfStructClosure()
{
var source = @"
void Outer()
{
int a = 0;
void Middle()
{
int b = 0;
void Inner()
{
a++;
b++;
}
a++;
Inner();
}
Middle();
Console.WriteLine(a);
}
Outer();
";
var verify = VerifyOutputInMain(source, "2", "System");
var inner = verify.FindLocalFunction("Inner");
var middle = verify.FindLocalFunction("Middle");
var outer = verify.FindLocalFunction("Outer");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.Equal(program, inner.ContainingType);
Assert.Equal(program, middle.ContainingType);
Assert.Equal(program, outer.ContainingType);
Assert.True(inner.IsStatic);
Assert.True(middle.IsStatic);
Assert.True(outer.IsStatic);
Assert.Equal(2, inner.Parameters.Length);
Assert.Equal(1, middle.Parameters.Length);
Assert.Equal(0, outer.Parameters.Length);
Assert.Equal(RefKind.Ref, inner.Parameters[0].RefKind);
Assert.Equal(RefKind.Ref, inner.Parameters[1].RefKind);
Assert.Equal(RefKind.Ref, middle.Parameters[0].RefKind);
Assert.True(inner.Parameters[0].Type.IsValueType);
Assert.True(inner.Parameters[1].Type.IsValueType);
Assert.True(middle.Parameters[0].Type.IsValueType);
}
[Fact]
public void ThisClosureCallingOtherClosure()
{
var source = @"
using System;
class Program
{
int _x;
int Test()
{
int First()
{
return ++_x;
}
int Second()
{
return First();
}
return Second();
}
static void Main()
{
Console.Write(new Program() { _x = 1 }.Test());
}
}
";
var verify = VerifyOutput(source, "2");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.Equal(program, verify.FindLocalFunction("First").ContainingType);
Assert.Equal(program, verify.FindLocalFunction("Second").ContainingType);
}
[Fact]
public void RecursiveStructClosure()
{
var source = @"
int x = 0;
void Goo()
{
if (x != 2)
{
x++;
Goo();
}
else
{
Console.Write(x);
}
}
Goo();
";
var verify = VerifyOutputInMain(source, "2", "System");
var goo = verify.FindLocalFunction("Goo");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.Equal(program, goo.ContainingType);
Assert.True(goo.IsStatic);
Assert.Equal(RefKind.Ref, goo.Parameters[0].RefKind);
Assert.True(goo.Parameters[0].Type.IsValueType);
}
[Fact]
public void MutuallyRecursiveStructClosure()
{
var source = @"
int x = 0;
void Goo(int depth)
{
int dummy = 0;
void Bar(int depth2)
{
dummy++;
Goo(depth2);
}
if (depth != 2)
{
x++;
Bar(depth + 1);
}
else
{
Console.Write(x);
}
}
Goo(0);
";
var verify = VerifyOutputInMain(source, "2", "System");
var program = verify.Compilation.GetTypeByMetadataName("Program");
var goo = verify.FindLocalFunction("Goo");
var bar = verify.FindLocalFunction("Bar");
Assert.Equal(program, goo.ContainingType);
Assert.Equal(program, bar.ContainingType);
Assert.True(goo.IsStatic);
Assert.True(bar.IsStatic);
Assert.Equal(2, goo.Parameters.Length);
Assert.Equal(3, bar.Parameters.Length);
Assert.Equal(RefKind.Ref, goo.Parameters[1].RefKind);
Assert.Equal(RefKind.Ref, bar.Parameters[1].RefKind);
Assert.Equal(RefKind.Ref, bar.Parameters[2].RefKind);
Assert.True(goo.Parameters[1].Type.IsValueType);
Assert.True(bar.Parameters[1].Type.IsValueType);
Assert.True(bar.Parameters[2].Type.IsValueType);
}
[Fact]
public void Recursion()
{
var source = @"
void Goo(int depth)
{
if (depth > 10)
{
Console.WriteLine(2);
return;
}
Goo(depth + 1);
}
Goo(0);
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void MutualRecursion()
{
var source = @"
void Goo(int depth)
{
if (depth > 10)
{
Console.WriteLine(2);
return;
}
void Bar(int depth2)
{
Goo(depth2 + 1);
}
Bar(depth + 1);
}
Goo(0);
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void RecursionThisOnlyClosure()
{
var source = @"
using System;
class Program
{
int _x;
void Outer()
{
void Inner()
{
if (_x == 0)
{
return;
}
Console.Write(_x);
Console.Write(' ');
_x = 0;
Inner();
}
Inner();
}
public static void Main()
{
new Program() { _x = 2 }.Outer();
}
}
";
var verify = VerifyOutput(source, "2");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.Equal(program, verify.FindLocalFunction("Inner").ContainingType);
}
[Fact]
public void RecursionFrameCaptureTest()
{
// ensures that referring to a local function in an otherwise noncapturing Inner captures the frame of Outer.
var source = @"
int x = 0;
int Outer(bool isRecursive)
{
if (isRecursive)
{
return x;
}
x++;
int Middle()
{
int Inner()
{
return Outer(true);
}
return Inner();
}
return Middle();
}
Console.Write(Outer(false));
Console.Write(' ');
Console.Write(x);
";
VerifyOutputInMain(source, "1 1", "System");
}
[Fact]
[CompilerTrait(CompilerFeature.Iterator)]
public void IteratorBasic()
{
var source = @"
IEnumerable<int> Local()
{
yield return 2;
}
Console.Write(string.Join("","", Local()));
";
VerifyOutputInMain(source, "2", "System", "System.Collections.Generic");
}
[Fact]
[CompilerTrait(CompilerFeature.Iterator)]
public void IteratorGeneric()
{
var source = @"
IEnumerable<T> LocalGeneric<T>(T val)
{
yield return val;
}
Console.Write(string.Join("","", LocalGeneric(2)));
";
VerifyOutputInMain(source, "2", "System", "System.Collections.Generic");
}
[Fact]
[CompilerTrait(CompilerFeature.Iterator)]
public void IteratorNonGeneric()
{
var source = @"
IEnumerable LocalNongen()
{
yield return 2;
}
foreach (int x in LocalNongen())
{
Console.Write(x);
}
";
VerifyOutputInMain(source, "2", "System", "System.Collections");
}
[Fact]
[CompilerTrait(CompilerFeature.Iterator)]
public void IteratorEnumerator()
{
var source = @"
IEnumerator LocalEnumerator()
{
yield return 2;
}
var y = LocalEnumerator();
y.MoveNext();
Console.Write(y.Current);
";
VerifyOutputInMain(source, "2", "System", "System.Collections");
}
[Fact]
public void Generic()
{
var source = @"
using System;
class Program
{
// No closure. Return 'valu'.
static T A1<T>(T val)
{
T Local(T valu)
{
return valu;
}
return Local(val);
}
static int B1(int val)
{
T Local<T>(T valu)
{
return valu;
}
return Local(val);
}
static T1 C1<T1>(T1 val)
{
T2 Local<T2>(T2 valu)
{
return valu;
}
return Local<T1>(val);
}
// General closure. Return 'val'.
static T A2<T>(T val)
{
T Local(T valu)
{
return val;
}
return Local(val);
}
static int B2(int val)
{
T Local<T>(T valu)
{
return (T)(object)val;
}
return Local(val);
}
static T1 C2<T1>(T1 val)
{
T2 Local<T2>(T2 valu)
{
return (T2)(object)val;
}
return Local<T1>(val);
}
// This-only closure. Return 'field'.
int field = 2;
T A3<T>(T val)
{
T Local(T valu)
{
return (T)(object)field;
}
return Local(val);
}
int B3(int val)
{
T Local<T>(T valu)
{
return (T)(object)field;
}
return Local(val);
}
T1 C3<T1>(T1 val)
{
T2 Local<T2>(T2 valu)
{
return (T2)(object)field;
}
return Local<T1>(val);
}
static void Main(string[] args)
{
var program = new Program();
Console.WriteLine(Program.A1(2));
Console.WriteLine(Program.B1(2));
Console.WriteLine(Program.C1(2));
Console.WriteLine(Program.A2(2));
Console.WriteLine(Program.B2(2));
Console.WriteLine(Program.C2(2));
Console.WriteLine(program.A3(2));
Console.WriteLine(program.B3(2));
Console.WriteLine(program.C3(2));
}
}
";
var output = @"
2
2
2
2
2
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericConstraint()
{
var source = @"
using System;
class Program
{
static T A<T>(T val) where T : struct
{
T Local(T valu)
{
return valu;
}
return Local(val);
}
static int B(int val)
{
T Local<T>(T valu) where T : struct
{
return valu;
}
return Local(val);
}
static T1 C<T1>(T1 val) where T1 : struct
{
T2 Local<T2>(T2 valu) where T2 : struct
{
return valu;
}
return Local(val);
}
static object D(object val)
{
T Local<T>(T valu) where T : class
{
return valu;
}
return Local(val);
}
static void Main(string[] args)
{
Console.WriteLine(A(2));
Console.WriteLine(B(2));
Console.WriteLine(C(2));
Console.WriteLine(D(2));
}
}
";
var output = @"
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericTripleNestedNoClosure()
{
var source = @"
using System;
class Program
{
// Name of method is T[outer][middle][inner] where brackets are g=generic n=nongeneric
// One generic
static T1 Tgnn<T1>(T1 a)
{
T1 Local(T1 aa)
{
T1 Local2(T1 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static int Tngn(int a)
{
T1 Local<T1>(T1 aa)
{
T1 Local2(T1 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static int Tnng(int a)
{
int Local(int aa)
{
T1 Local2<T1>(T1 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
// Two generic
static T1 Tggn<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T2 Local2(T2 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static T1 Tgng<T1>(T1 a)
{
T1 Local(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static int Tngg(int a)
{
T1 Local<T1>(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
// Three generic
static T1 Tggg<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static void Main(string[] args)
{
Console.WriteLine(Program.Tgnn(2));
Console.WriteLine(Program.Tngn(2));
Console.WriteLine(Program.Tnng(2));
Console.WriteLine(Program.Tggn(2));
Console.WriteLine(Program.Tgng(2));
Console.WriteLine(Program.Tngg(2));
Console.WriteLine(Program.Tggg(2));
}
}
";
var output = @"
2
2
2
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericTripleNestedMiddleClosure()
{
var source = @"
using System;
class Program
{
// Name of method is T[outer][middle][inner] where brackets are g=generic n=nongeneric
// One generic
static T1 Tgnn<T1>(T1 a)
{
T1 Local(T1 aa)
{
T1 Local2(T1 aaa)
{
return (T1)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
static int Tngn(int a)
{
T1 Local<T1>(T1 aa)
{
T1 Local2(T1 aaa)
{
return (T1)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
static int Tnng(int a)
{
int Local(int aa)
{
T1 Local2<T1>(T1 aaa)
{
return (T1)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
// Two generic
static T1 Tggn<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T2 Local2(T2 aaa)
{
return (T2)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
static T1 Tgng<T1>(T1 a)
{
T1 Local(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return (T2)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
static int Tngg(int a)
{
T1 Local<T1>(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return (T2)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
// Three generic
static T1 Tggg<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
return (T3)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
static void Main(string[] args)
{
Console.WriteLine(Program.Tgnn(2));
Console.WriteLine(Program.Tngn(2));
Console.WriteLine(Program.Tnng(2));
Console.WriteLine(Program.Tggn(2));
Console.WriteLine(Program.Tgng(2));
Console.WriteLine(Program.Tngg(2));
Console.WriteLine(Program.Tggg(2));
}
}
";
var output = @"
2
2
2
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericTripleNestedOuterClosure()
{
var source = @"
using System;
class Program
{
// Name of method is T[outer][middle][inner] where brackets are g=generic n=nongeneric
// One generic
static T1 Tgnn<T1>(T1 a)
{
T1 Local(T1 aa)
{
T1 Local2(T1 aaa)
{
return (T1)(object)a;
}
return Local2(aa);
}
return Local(a);
}
static int Tngn(int a)
{
T1 Local<T1>(T1 aa)
{
T1 Local2(T1 aaa)
{
return (T1)(object)a;
}
return Local2(aa);
}
return Local(a);
}
static int Tnng(int a)
{
int Local(int aa)
{
T1 Local2<T1>(T1 aaa)
{
return (T1)(object)a;
}
return Local2(aa);
}
return Local(a);
}
// Two generic
static T1 Tggn<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T2 Local2(T2 aaa)
{
return (T2)(object)a;
}
return Local2(aa);
}
return Local(a);
}
static T1 Tgng<T1>(T1 a)
{
T1 Local(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return (T2)(object)a;
}
return Local2(aa);
}
return Local(a);
}
static int Tngg(int a)
{
T1 Local<T1>(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return (T2)(object)a;
}
return Local2(aa);
}
return Local(a);
}
// Three generic
static T1 Tggg<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
return (T3)(object)a;
}
return Local2(aa);
}
return Local(a);
}
static void Main(string[] args)
{
Console.WriteLine(Program.Tgnn(2));
Console.WriteLine(Program.Tngn(2));
Console.WriteLine(Program.Tnng(2));
Console.WriteLine(Program.Tggn(2));
Console.WriteLine(Program.Tgng(2));
Console.WriteLine(Program.Tngg(2));
Console.WriteLine(Program.Tggg(2));
}
}
";
var output = @"
2
2
2
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericTripleNestedNoClosureLambda()
{
var source = @"
using System;
class Program
{
// Name of method is T[outer][middle][inner] where brackets are g=generic n=nongeneric
// One generic
static T1 Tgnn<T1>(T1 a)
{
Func<T1, T1> Local = aa =>
{
Func<T1, T1> Local2 = aaa =>
{
return aaa;
};
return Local2(aa);
};
return Local(a);
}
static int Tngn(int a)
{
T1 Local<T1>(T1 aa)
{
Func<T1, T1> Local2 = aaa =>
{
return aaa;
};
return Local2(aa);
}
return Local(a);
}
static int Tnng(int a)
{
Func<int, int> Local = aa =>
{
T1 Local2<T1>(T1 aaa)
{
return aaa;
}
return Local2(aa);
};
return Local(a);
}
// Two generic
static T1 Tggn<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
Func<T2, T2> Local2 = aaa =>
{
return aaa;
};
return Local2(aa);
}
return Local(a);
}
static T1 Tgng<T1>(T1 a)
{
Func<T1, T1> Local = aa =>
{
T2 Local2<T2>(T2 aaa)
{
return aaa;
}
return Local2(aa);
};
return Local(a);
}
// Tngg and Tggg are impossible with lambdas
static void Main(string[] args)
{
Console.WriteLine(Program.Tgnn(2));
Console.WriteLine(Program.Tngn(2));
Console.WriteLine(Program.Tnng(2));
Console.WriteLine(Program.Tggn(2));
Console.WriteLine(Program.Tgng(2));
}
}
";
var output = @"
2
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericUpperCall()
{
var source = @"
using System;
class Program
{
static T1 InnerToOuter<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
if ((object)aaa == null)
return InnerToOuter((T3)new object());
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static T1 InnerToMiddle<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
if ((object)aaa == null)
return InnerToMiddle((T3)new object());
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static T1 InnerToOuterScoping<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
if ((object)aaa == null)
return (T3)(object)InnerToOuter((T1)new object());
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static T1 M1<T1>(T1 a)
{
T2 M2<T2>(T2 aa)
{
T2 x = aa;
T3 M3<T3>(T3 aaa)
{
T4 M4<T4>(T4 aaaa)
{
return (T4)(object)x;
}
return M4(aaa);
}
return M3(aa);
}
return M2(a);
}
static void Main(string[] args)
{
Console.WriteLine(Program.InnerToOuter((object)null));
Console.WriteLine(Program.InnerToMiddle((object)null));
Console.WriteLine(Program.InnerToOuterScoping((object)null));
Console.WriteLine(Program.M1(2));
}
}
";
var output = @"
System.Object
System.Object
System.Object
2
";
VerifyOutput(source, output);
}
[Fact]
public void CompoundOperatorExecutesOnce()
{
var source = @"
using System;
class Program
{
int _x = 2;
public static void Main()
{
var prog = new Program();
Program SideEffect()
{
Console.Write(prog._x);
return prog;
}
SideEffect()._x += 2;
Console.Write(' ');
SideEffect();
}
}
";
VerifyOutput(source, "2 4");
}
[Fact]
public void ConstValueDoesntMakeClosure()
{
var source = @"
const int x = 2;
void Local()
{
Console.Write(x);
}
Local();
";
// Should be a static method on "Program" itself, not a display class like "Program+<>c__DisplayClass0_0"
var verify = VerifyOutputInMain(source, "2", "System");
var goo = verify.FindLocalFunction("Local");
Assert.True(goo.IsStatic);
Assert.Equal(verify.Compilation.GetTypeByMetadataName("Program"), goo.ContainingType);
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicArgument()
{
var source = @"
using System;
class Program
{
static void Main()
{
int capture1 = 0;
void L1(int x) => Console.Write(x);
void L2(int x)
{
Console.Write(capture1);
Console.Write(x);
}
dynamic L4(int x)
{
Console.Write(capture1);
return x;
}
Action<int> L5(int x)
{
Console.Write(x);
return L1;
}
dynamic val = 2;
Console.WriteLine();
L1(val);
L2(val);
Console.WriteLine();
L2(L4(val));
L5(val)(val);
}
}
";
VerifyOutput(source, output: @"202
00222");
}
[Fact]
[WorkItem(21317, "https://github.com/dotnet/roslyn/issues/21317")]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicGenericArg()
{
var src = @"
void L1<T>(T x)
{
Console.WriteLine($""{x}: {typeof(T)}"");
}
dynamic val = 2;
L1<object>(val);
L1<int>(val);
L1<dynamic>(val);
L1<dynamic>(4);
void L2<T>(int x, T y) => Console.WriteLine($""{x}, {y}: {typeof(T)}"");
L2<float>(val, 3.0f);
List<dynamic> listOfDynamic = new List<dynamic> { 1, 2, 3 };
void L3<T>(List<T> x) => Console.WriteLine($""{string.Join("", "", x)}: {typeof(T)}"");
L3(listOfDynamic);
void L4<T>(T x, params int[] y) => Console.WriteLine($""{x}, {string.Join("", "", y)}: {typeof(T)}"");
L4<dynamic>(val, 3, 4);
L4<int>(val, 3, 4);
L4<int>(1, 3, val);
void L5<T>(int x, params T[] y) => Console.WriteLine($""{x}, {string.Join("", "", y)}: {typeof(T)}"");
L5<int>(val, 3, 4);
L5<int>(1, 3, val);
L5<dynamic>(1, 3, val);
";
var output = @"
2: System.Object
2: System.Int32
2: System.Object
4: System.Object
2, 3: System.Single
1, 2, 3: System.Object
2, 3, 4: System.Object
2, 3, 4: System.Int32
1, 3, 2: System.Int32
2, 3, 4: System.Int32
1, 3, 2: System.Int32
1, 3, 2: System.Object
";
VerifyOutputInMain(src, output, "System", "System.Collections.Generic");
}
[Fact]
[WorkItem(21317, "https://github.com/dotnet/roslyn/issues/21317")]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicGenericClassMethod()
{
var src = @"
using System;
class C1<T1>
{
public static void M1<T2>()
{
void F(int x)
{
Console.WriteLine($""C1<{typeof(T1)}>.M1<{typeof(T2)}>.F({x})"");
}
F((dynamic)2);
}
public static void M2()
{
void F(int x)
{
Console.WriteLine($""C1<{typeof(T1)}>.M2.F({x})"");
}
F((dynamic)2);
}
}
class C2
{
public static void M1<T2>()
{
void F(int x)
{
Console.WriteLine($""C2.M1<{typeof(T2)}>.F({x})"");
}
F((dynamic)2);
}
public static void M2()
{
void F(int x)
{
Console.WriteLine($""C2.M2.F({x})"");
}
F((dynamic)2);
}
}
class Program
{
static void Main()
{
C1<int>.M1<float>();
C1<int>.M2();
C2.M1<float>();
C2.M2();
}
}
";
var output = @"
C1<System.Int32>.M1<System.Single>.F(2)
C1<System.Int32>.M2.F(2)
C2.M1<System.Single>.F(2)
C2.M2.F(2)
";
VerifyOutput(src, output);
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic, CompilerFeature.Params)]
public void DynamicArgsAndParams()
{
var src = @"
int capture1 = 0;
void L1(int x, params int[] ys)
{
Console.Write(capture1);
Console.Write(x);
foreach (var y in ys)
{
Console.Write(y);
}
}
dynamic val = 2;
int val2 = 3;
L1(val, val2);
L1(val);
L1(val, val, val);
";
VerifyOutputInMain(src, "023020222", "System");
}
[Fact]
public void Basic()
{
var source = @"
async Task<int> Local()
{
return await Task.FromResult(2);
}
Console.Write(Local().Result);
";
VerifyOutputInMain(source, "2", "System", "System.Threading.Tasks");
}
[Fact]
public void Param()
{
var source = @"
async Task<int> LocalParam(int x)
{
return await Task.FromResult(x);
}
Console.Write(LocalParam(2).Result);
";
VerifyOutputInMain(source, "2", "System", "System.Threading.Tasks");
}
[Fact]
[CompilerTrait(CompilerFeature.Async)]
public void GenericAsync()
{
var source = @"
async Task<T> LocalGeneric<T>(T x)
{
return await Task.FromResult(x);
}
Console.Write(LocalGeneric(2).Result);
";
VerifyOutputInMain(source, "2", "System", "System.Threading.Tasks");
}
[Fact]
[CompilerTrait(CompilerFeature.Async)]
public void Void()
{
var source = @"
// had bug with parser where 'async [keyword]' didn't parse.
async void LocalVoid()
{
Console.Write(2);
await Task.Yield();
}
LocalVoid();
";
VerifyOutputInMain(source, "2", "System", "System.Threading.Tasks");
}
[Fact]
[CompilerTrait(CompilerFeature.Async)]
public void AwaitAwait()
{
var source = @"
Task<int> Fun(int x)
{
return Task.FromResult(x);
}
async Task<int> AwaitAwait()
{
var a = Fun(2);
await Fun(await a);
return await Fun(await a);
}
Console.WriteLine(AwaitAwait().Result);
";
VerifyOutputInMain(source, "2", "System", "System.Threading.Tasks");
}
[Fact]
[CompilerTrait(CompilerFeature.Async)]
public void Keyword()
{
var source = @"
using System;
struct async
{
public override string ToString() => ""2"";
}
struct await
{
public override string ToString() => ""2"";
}
class Program
{
static string A()
{
async async()
{
return new async();
}
return async().ToString();
}
static string B()
{
string async()
{
return ""2"";
}
return async();
}
static string C()
{
async Goo()
{
return new async();
}
return Goo().ToString();
}
static string D()
{
await Fun(await x)
{
return x;
}
return Fun(new await()).ToString();
}
static void Main(string[] args)
{
Console.WriteLine(A());
Console.WriteLine(B());
Console.WriteLine(C());
Console.WriteLine(D());
}
}
";
var output = @"
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
[CompilerTrait(CompilerFeature.Async)]
public void UnsafeKeyword()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program
{
static string A()
{
async unsafe Task<int> async()
{
return 2;
}
return async().Result.ToString();
}
static string B()
{
unsafe async Task<int> async()
{
return 2;
}
return async().Result.ToString();
}
static void Main(string[] args)
{
Console.WriteLine(A());
Console.WriteLine(B());
}
}
";
var output = @"
2
2
";
VerifyOutput(source, output, TestOptions.ReleaseExe.WithAllowUnsafe(true).WithWarningLevel(0), verify: Verification.Passes);
}
[Fact]
public void UnsafeBasic()
{
var source = @"
using System;
class Program
{
static void A()
{
unsafe void Local()
{
int x = 2;
Console.Write(*&x);
}
Local();
}
static void Main(string[] args)
{
A();
}
}
";
VerifyOutput(source, "2", TestOptions.ReleaseExe.WithAllowUnsafe(true), verify: Verification.Fails);
}
[Fact]
public void UnsafeParameter()
{
var source = @"
using System;
class Program
{
static unsafe void B()
{
int x = 2;
unsafe void Local(int* y)
{
Console.Write(*y);
}
Local(&x);
}
static void Main(string[] args)
{
B();
}
}
";
VerifyOutput(source, "2", TestOptions.ReleaseExe.WithAllowUnsafe(true), verify: Verification.Fails);
}
[Fact]
public void UnsafeClosure()
{
var source = @"
using System;
class Program
{
static unsafe void C()
{
int y = 2;
int* x = &y;
unsafe void Local()
{
Console.Write(*x);
}
Local();
}
static void Main(string[] args)
{
C();
}
}
";
VerifyOutput(source, "2", TestOptions.ReleaseExe.WithAllowUnsafe(true), verify: Verification.Fails);
}
[Fact]
public void UnsafeCalls()
{
var src = @"
using System;
class C
{
public static void Main(string[] args)
{
int x = 2;
int y = 0;
unsafe void Local(ref int x2)
{
fixed (int* ptr = &x2)
{
Local2(ptr);
}
}
unsafe int* Local2(int* ptr)
{
(*ptr)++;
y++;
return null;
}
while (x < 10)
{
Local(ref x);
x++;
}
Console.WriteLine(x);
Console.WriteLine(y);
}
}";
VerifyOutput(src, $"10{Environment.NewLine}4", TestOptions.ReleaseExe.WithAllowUnsafe(true), verify: Verification.Fails);
}
[Fact]
[WorkItem(15322, "https://github.com/dotnet/roslyn/issues/15322")]
public void UseBeforeDeclaration()
{
var src = @"
Assign();
Local();
int x;
void Local() => System.Console.WriteLine(x);
void Assign() { x = 5; }";
VerifyOutputInMain(src, "5");
}
[Fact]
[WorkItem(15558, "https://github.com/dotnet/roslyn/issues/15558")]
public void CapturingSharesVar()
{
var src = @"
int i = 0;
int oldi<T>()
where T : struct
=> (i += @sizeof<T>()) - @sizeof<T>();
int @sizeof<T>()
where T : struct
=> typeof(T).IsAssignableFrom(typeof(long))
? sizeof(long)
: 1;
while (i < 10)
System.Console.WriteLine(oldi<byte>());";
VerifyOutputInMain(src, @"0
1
2
3
4
5
6
7
8
9");
}
[Fact]
[WorkItem(15599, "https://github.com/dotnet/roslyn/issues/15599")]
public void NestedLocalFuncCapture()
{
var src = @"
using System;
public class C {
int instance = 11;
public void M() {
int M() => instance;
{
int local = 11;
bool M2() => local == M();
Console.WriteLine(M2());
}
}
public static void Main() => new C().M();
}";
VerifyOutput(src, "True");
}
[Fact]
[WorkItem(15599, "https://github.com/dotnet/roslyn/issues/15599")]
public void NestedLocalFuncCapture2()
{
var src = @"
using System;
public class C {
int instance = 0b1;
public void M() {
int var1 = 0b10;
int M() => var1 + instance;
{
int local = 0b100;
int M2() => local + M();
Console.WriteLine(M2());
}
}
public static void Main() => new C().M();
}";
VerifyOutput(src, "7");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction()
{
var src = @"
void Local<T>(T t, int count)
{
if (count > 0)
{
Console.Write(t);
Local(t, count - 1);
}
}
Local(""A"", 5);
";
VerifyOutputInMain(src, "AAAAA", "System");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction2()
{
var src = @"
void Local<T>(T t, int count)
{
if (count > 0)
{
Console.Write(t);
var action = new Action<T, int>(Local);
action(t, count - 1);
}
}
Local(""A"", 5);
";
VerifyOutputInMain(src, "AAAAA", "System");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction3()
{
var src = @"
void Local<T>(T t, int count)
{
if (count > 0)
{
Console.Write(t);
var action = (Action<T, int>)Local;
action(t, count - 1);
}
}
Local(""A"", 5);
";
VerifyOutputInMain(src, "AAAAA", "System");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction4()
{
var src = @"
using System;
class C
{
public static void M<T>(T t)
{
void Local<U>(U u, int count)
{
if (count > 0)
{
Console.Write(t);
Console.Write(u);
Local(u, count - 1);
}
}
Local(""A"", 5);
}
public static void Main()
{
C.M(""B"");
}
}";
VerifyOutput(src, "BABABABABA");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction5()
{
var src = @"
using System;
class C<T1>
{
T1 t1;
public C(T1 t1)
{
this.t1 = t1;
}
public void M<T2>(T2 t2)
{
void L1<T3>(T3 t3)
{
void L2<T4>(T4 t4)
{
void L3<U>(U u, int count)
{
if (count > 0)
{
Console.Write(t1);
Console.Write(t2);
Console.Write(t3);
Console.Write(t4);
Console.Write(u);
L3(u, count - 1);
}
}
L3(""A"", 5);
}
L2(""B"");
}
L1(""C"");
}
}
class Program
{
public static void Main()
{
var c = new C<string>(""D"");
c.M(""E"");
}
}";
VerifyOutput(src, "DECBADECBADECBADECBADECBA");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction6()
{
var src = @"
using System;
class C<T1>
{
T1 t1;
public C(T1 t1)
{
this.t1 = t1;
}
public void M<T2>(T2 t2)
{
void L1<T3>(T3 t3)
{
void L2<T4>(T4 t4)
{
void L3<U>(U u, int count)
{
if (count > 0)
{
Console.Write(t1);
Console.Write(t2);
Console.Write(t3);
Console.Write(t4);
Console.Write(u);
var a = new Action<U, int>(L3);
a(u, count - 1);
}
}
var b = new Action<string, int>(L3);
b(""A"", 5);
}
var c = new Action<string>(L2);
c(""B"");
}
var d = new Action<string>(L1);
d(""C"");
}
}
class Program
{
public static void Main()
{
var c = new C<string>(""D"");
c.M(""E"");
}
}";
VerifyOutput(src, "DECBADECBADECBADECBADECBA");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction7()
{
var src = @"
using System;
class C<T1>
{
T1 t1;
public C(T1 t1)
{
this.t1 = t1;
}
public void M<T2>(T2 t2)
{
void L1<T3>(T3 t3)
{
void L2<T4>(T4 t4)
{
void L3<U>(U u, int count)
{
if (count > 0)
{
Console.Write(t1);
Console.Write(t2);
Console.Write(t3);
Console.Write(t4);
Console.Write(u);
var a = (Action<U, int>)(L3);
a(u, count - 1);
}
}
var b = (Action<string, int>)(L3);
b(""A"", 5);
}
var c = (Action<string>)(L2);
c(""B"");
}
var d = (Action<string>)(L1);
d(""C"");
}
}
class Program
{
public static void Main()
{
var c = new C<string>(""D"");
c.M(""E"");
}
}";
VerifyOutput(src, "DECBADECBADECBADECBADECBA");
}
[Fact]
[WorkItem(16038, "https://github.com/dotnet/roslyn/issues/16038")]
public void RecursiveGenericLocalFunction8()
{
var src = @"
using System;
class C<T0>
{
T0 t0;
public C(T0 t0)
{
this.t0 = t0;
}
public void M<T1>(T1 t1)
{
(T0, T1, T2) L1<T2>(T2 t2)
{
(T0, T1, T2, T3) L2<T3>(T3 t3, int count)
{
if (count > 0)
{
Console.Write(t0);
Console.Write(t1);
Console.Write(t2);
Console.Write(t3);
return L2(t3, count - 1);
}
return (t0, t1, t2, t3);
}
var (t4, t5, t6, t7) = L2(""A"", 5);
return (t4, t5, t6);
}
L1(""B"");
}
}
class Program
{
public static void Main()
{
var c = new C<string>(""C"");
c.M(""D"");
}
}";
CompileAndVerify(src, expectedOutput: "CDBACDBACDBACDBACDBA");
}
[Fact]
[WorkItem(19119, "https://github.com/dotnet/roslyn/issues/19119")]
public void StructFrameInitUnnecessary()
{
var c = CompileAndVerify(@"
class Program
{
static void Main(string[] args)
{
int q = 1;
if (q > 0)
{
int w = 2;
if (w > 0)
{
int e = 3;
if (e > 0)
{
void Print() => System.Console.WriteLine(q + w + e);
Print();
}
}
}
}
}", expectedOutput: "6");
//NOTE: the following code should not have "initobj" instructions.
c.VerifyIL("Program.Main", @"
{
// Code size 63 (0x3f)
.maxstack 3
.locals init (Program.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
Program.<>c__DisplayClass0_1 V_1, //CS$<>8__locals1
Program.<>c__DisplayClass0_2 V_2) //CS$<>8__locals2
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: stfld ""int Program.<>c__DisplayClass0_0.q""
IL_0008: ldloc.0
IL_0009: ldfld ""int Program.<>c__DisplayClass0_0.q""
IL_000e: ldc.i4.0
IL_000f: ble.s IL_003e
IL_0011: ldloca.s V_1
IL_0013: ldc.i4.2
IL_0014: stfld ""int Program.<>c__DisplayClass0_1.w""
IL_0019: ldloc.1
IL_001a: ldfld ""int Program.<>c__DisplayClass0_1.w""
IL_001f: ldc.i4.0
IL_0020: ble.s IL_003e
IL_0022: ldloca.s V_2
IL_0024: ldc.i4.3
IL_0025: stfld ""int Program.<>c__DisplayClass0_2.e""
IL_002a: ldloc.2
IL_002b: ldfld ""int Program.<>c__DisplayClass0_2.e""
IL_0030: ldc.i4.0
IL_0031: ble.s IL_003e
IL_0033: ldloca.s V_0
IL_0035: ldloca.s V_1
IL_0037: ldloca.s V_2
IL_0039: call ""void Program.<Main>g__Print|0_0(ref Program.<>c__DisplayClass0_0, ref Program.<>c__DisplayClass0_1, ref Program.<>c__DisplayClass0_2)""
IL_003e: ret
}
");
}
[Fact]
public void LocalFunctionAttribute()
{
var source = @"
class A : System.Attribute { }
class C
{
public void M()
{
[A]
void local1()
{
}
[return: A]
void local2()
{
}
void local3([A] int i)
{
}
void local4<[A] T>()
{
}
}
}
";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal(
expected: new[] { "CompilerGeneratedAttribute", "A" },
actual: GetAttributeNames(attrs1));
var localFn2 = cClass.GetMethod("<M>g__local2|0_1");
var attrs2 = localFn2.GetReturnTypeAttributes();
Assert.Equal("A", attrs2.Single().AttributeClass.Name);
var localFn3 = cClass.GetMethod("<M>g__local3|0_2");
var attrs3 = localFn3.GetParameters().Single().GetAttributes();
Assert.Equal("A", attrs3.Single().AttributeClass.Name);
var localFn4 = cClass.GetMethod("<M>g__local4|0_3");
var attrs4 = localFn4.TypeParameters.Single().GetAttributes();
Assert.Equal("A", attrs4.Single().AttributeClass.Name);
}
}
[Fact]
public void LocalFunctionAttribute_Complex()
{
var source = @"
class A1 : System.Attribute { }
class A2 : System.Attribute { internal A2(int i, string s) { } }
class A3 : System.Attribute { internal A3(params int[] values) { } }
class C
{
public void M()
{
[A1, A2(1, ""hello"")]
[A3(1, 2, 3, 4, 5)]
void local1()
{
}
}
}
";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs = localFn1.GetAttributes();
Assert.Equal(
expected: new[] { "CompilerGeneratedAttribute", "A1", "A2", "A3" },
actual: GetAttributeNames(attrs));
Assert.Empty(attrs[0].ConstructorArguments);
Assert.Empty(attrs[1].ConstructorArguments);
Assert.Equal(new object[] { 1, "hello" }, attrs[2].ConstructorArguments.Select(a => a.Value));
var attr3Args = attrs[3].ConstructorArguments.Single().Values;
Assert.Equal(new object[] { 1, 2, 3, 4, 5 }, attr3Args.Select(a => a.Value));
}
}
[Fact]
public void LocalFunctionAttributeArgument()
{
var source = @"
class A : System.Attribute { internal A(int i) { } }
class C
{
public void M()
{
[A(42)]
void local1()
{
}
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal(
expected: new[] { "CompilerGeneratedAttribute", "A" },
actual: GetAttributeNames(attrs1));
var arg = attrs1[1].ConstructorArguments.Single();
Assert.Equal(42, arg.Value);
}
}
[Fact]
public void LocalFunction_DontEmitNullableAttribute()
{
var source = @"
#nullable enable
class C
{
public void M()
{
string? local1(string? s) => s;
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal("CompilerGeneratedAttribute", attrs1.Single().AttributeClass.Name);
Assert.Empty(localFn1.GetReturnTypeAttributes());
Assert.Equal(NullableAnnotation.Oblivious, localFn1.ReturnTypeWithAnnotations.NullableAnnotation);
var param = localFn1.Parameters.Single();
Assert.Empty(param.GetAttributes());
Assert.Equal(NullableAnnotation.Oblivious, param.TypeWithAnnotations.NullableAnnotation);
}
}
[Fact]
public void LocalFunctionDynamicAttribute()
{
var source = @"
class C
{
public void M()
{
dynamic local1(dynamic d) => d;
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal("CompilerGeneratedAttribute", attrs1.Single().AttributeClass.Name);
Assert.Equal("DynamicAttribute", localFn1.GetReturnTypeAttributes().Single().AttributeClass.Name);
var param = localFn1.Parameters.Single();
Assert.Equal("DynamicAttribute", param.GetAttributes().Single().AttributeClass.Name);
}
}
[Fact]
public void LocalFunctionParamsArray_NoParamArrayAttribute()
{
var source = @"
class C
{
void M()
{
#pragma warning disable 8321
void local1(params int[] arr) { }
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal("CompilerGeneratedAttribute", attrs1.Single().AttributeClass.Name);
Assert.Empty(localFn1.GetReturnTypeAttributes());
var param = localFn1.Parameters.Single();
Assert.Empty(param.GetAttributes());
}
}
[Fact]
public void LocalFunction_ConditionalAttributeDisallowed()
{
var source = @"
using System.Diagnostics;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[Conditional(""DEBUG"")] // 1
void local1() { }
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (9,10): error CS8764: Local function 'local1()' must be 'static' in order to use the Conditional attribute
// [Conditional("DEBUG")] // 1
Diagnostic(ErrorCode.ERR_ConditionalOnLocalFunction, @"Conditional(""DEBUG"")").WithArguments("local1()").WithLocation(9, 10));
}
[Fact]
public void StaticLocalFunction_ConditionalAttribute_Errors()
{
var source = @"
using System.Diagnostics;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[Conditional(""hello world"")] // 1
static void local1() { }
[Conditional(""DEBUG"")] // 2
static int local2()
{
return 42;
}
[Conditional(""DEBUG"")] // 3
static void local3(out string s)
{
s = ""hello"";
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (9,22): error CS0633: The argument to the 'Conditional' attribute must be a valid identifier
// [Conditional("hello world")] // 1
Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""hello world""").WithArguments("Conditional").WithLocation(9, 22),
// (12,10): error CS0578: The Conditional attribute is not valid on 'local2()' because its return type is not void
// [Conditional("DEBUG")] // 2
Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"Conditional(""DEBUG"")").WithArguments("local2()").WithLocation(12, 10),
// (18,10): error CS0685: Conditional member 'local3(out string)' cannot have an out parameter
// [Conditional("DEBUG")] // 3
Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""DEBUG"")").WithArguments("local3(out string)").WithLocation(18, 10));
}
[Fact]
public void StaticLocalFunction_ConditionalAttribute()
{
var source = @"
using System.Diagnostics;
using System;
class C
{
static void Main()
{
local1();
[Conditional(""DEBUG"")]
static void local1()
{
Console.Write(""hello"");
}
}
}
";
CompileAndVerify(
source,
options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9.WithPreprocessorSymbols("DEBUG"),
symbolValidator: validate,
expectedOutput: "hello");
CompileAndVerify(
source,
options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate,
expectedOutput: "");
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<Main>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal(new[] { "CompilerGeneratedAttribute", "ConditionalAttribute" }, GetAttributeNames(attrs1));
}
}
[Fact]
public void StaticLocalFunction_ConditionalAttribute_NoUnreferencedWarning()
{
var source = @"
using System.Diagnostics;
using System;
class C
{
static void Main()
{
local1();
[Conditional(""DEBUG"")]
static void local1()
{
Console.Write(""hello"");
}
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics();
CreateCompilation(source, parseOptions: TestOptions.Regular9.WithPreprocessorSymbols("DEBUG")).VerifyDiagnostics();
}
[Fact]
public void StaticLocalFunction_IfDirective_Unreferenced()
{
var source = @"
using System;
class C
{
static void Main()
{
#if DEBUG
local1();
#endif
static void local1()
{
Console.Write(""hello"");
}
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics(
// (11,21): warning CS8321: The local function 'local1' is declared but never used
// static void local1() // 1
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local1").WithArguments("local1").WithLocation(11, 21));
CreateCompilation(source, parseOptions: TestOptions.Regular9.WithPreprocessorSymbols("DEBUG")).VerifyDiagnostics();
}
[Fact]
public void LocalFunction_AttributeMarkedConditional()
{
var source = @"
using System.Diagnostics;
using System;
[Conditional(""DEBUG"")]
class Attr : Attribute { }
class C
{
void M()
{
#pragma warning disable 8321
[Attr]
[return: Attr]
T local1<[Attr] T>([Attr] T t) => t;
}
}
";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9.WithPreprocessorSymbols("DEBUG"),
symbolValidator: validate1);
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate2);
static void validate1(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal(new[] { "CompilerGeneratedAttribute", "Attr" }, GetAttributeNames(attrs1));
Assert.Equal(new[] { "Attr" }, GetAttributeNames(localFn1.GetReturnTypeAttributes()));
Assert.Equal(new[] { "Attr" }, GetAttributeNames(localFn1.TypeParameters.Single().GetAttributes()));
Assert.Equal(new[] { "Attr" }, GetAttributeNames(localFn1.Parameters.Single().GetAttributes()));
}
static void validate2(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(attrs1));
Assert.Empty(localFn1.GetReturnTypeAttributes());
Assert.Empty(localFn1.TypeParameters.Single().GetAttributes());
Assert.Empty(localFn1.Parameters.Single().GetAttributes());
}
}
[ConditionalFact(typeof(DesktopOnly))]
public void LocalFunctionAttribute_TypeIL()
{
var source = @"
class A : System.Attribute { internal A(int i) { } }
class C
{
public void M()
{
[A(42)]
void local1()
{
}
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9);
verifier.VerifyTypeIL("C", @"
.class private auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig
instance void M () cil managed
{
// Method begins at RVA 0x205a
// Code size 3 (0x3)
.maxstack 8
IL_0000: nop
IL_0001: nop
IL_0002: ret
} // end of method C::M
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x205e
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
.method assembly hidebysig static
void '<M>g__local1|0_0' () cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
.custom instance void A::.ctor(int32) = (
01 00 2a 00 00 00 00 00
)
// Method begins at RVA 0x2067
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method C::'<M>g__local1|0_0'
} // end of class C");
}
[Fact]
public void ExternLocalFunction()
{
var source = @"
using System.Runtime.InteropServices;
class C
{
public void M()
{
local1();
[DllImport(""something.dll"")]
static extern void local1();
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate,
verify: Verification.Skipped);
var comp = verifier.Compilation;
var syntaxTree = comp.SyntaxTrees.Single();
var semanticModel = comp.GetSemanticModel(syntaxTree);
var localFunction = semanticModel
.GetDeclaredSymbol(syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single())
.GetSymbol<LocalFunctionSymbol>();
Assert.Equal(new[] { "DllImportAttribute" }, GetAttributeNames(localFunction.GetAttributes()));
validateLocalFunction(localFunction);
void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes().As<CSharpAttributeData>();
Assert.Equal(
expected: new[] { "CompilerGeneratedAttribute" },
actual: GetAttributeNames(attrs1));
validateLocalFunction(localFn1);
}
static void validateLocalFunction(MethodSymbol localFunction)
{
Assert.True(localFunction.IsExtern);
var importData = localFunction.GetDllImportData();
Assert.NotNull(importData);
Assert.Equal("something.dll", importData.ModuleName);
Assert.Equal("local1", importData.EntryPointName);
Assert.Equal(CharSet.None, importData.CharacterSet);
Assert.False(importData.SetLastError);
Assert.False(importData.ExactSpelling);
Assert.Equal(MethodImplAttributes.PreserveSig, localFunction.ImplementationAttributes);
Assert.Equal(CallingConvention.Winapi, importData.CallingConvention);
Assert.Null(importData.BestFitMapping);
Assert.Null(importData.ThrowOnUnmappableCharacter);
}
}
[Fact]
public void ExternLocalFunction_ComplexDllImport()
{
var source = @"
using System.Runtime.InteropServices;
class C
{
public void M()
{
local1();
[DllImport(
""something.dll"",
EntryPoint = ""a"",
CharSet = CharSet.Ansi,
SetLastError = true,
ExactSpelling = true,
PreserveSig = false,
CallingConvention = CallingConvention.Cdecl,
BestFitMapping = false,
ThrowOnUnmappableChar = true)]
static extern void local1();
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate,
verify: Verification.Skipped);
var comp = verifier.Compilation;
var syntaxTree = comp.SyntaxTrees.Single();
var semanticModel = comp.GetSemanticModel(syntaxTree);
var localFunction = semanticModel
.GetDeclaredSymbol(syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single())
.GetSymbol<LocalFunctionSymbol>();
Assert.Equal(new[] { "DllImportAttribute" }, GetAttributeNames(localFunction.GetAttributes()));
validateLocalFunction(localFunction);
void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes().As<CSharpAttributeData>();
Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(attrs1));
validateLocalFunction(localFn1);
}
static void validateLocalFunction(MethodSymbol localFunction)
{
Assert.True(localFunction.IsExtern);
var importData = localFunction.GetDllImportData();
Assert.NotNull(importData);
Assert.Equal("something.dll", importData.ModuleName);
Assert.Equal("a", importData.EntryPointName);
Assert.Equal(CharSet.Ansi, importData.CharacterSet);
Assert.True(importData.SetLastError);
Assert.True(importData.ExactSpelling);
Assert.Equal(MethodImplAttributes.IL, localFunction.ImplementationAttributes);
Assert.Equal(CallingConvention.Cdecl, importData.CallingConvention);
Assert.False(importData.BestFitMapping);
Assert.True(importData.ThrowOnUnmappableCharacter);
}
}
[Fact]
public void LocalFunction_MethodImpl()
{
var source = @"
using System.Runtime.CompilerServices;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[MethodImpl(MethodImplOptions.ForwardRef)]
static void forwardRef() { System.Console.WriteLine(0); }
[MethodImpl(MethodImplOptions.NoInlining)]
static void noInlining() { System.Console.WriteLine(1); }
[MethodImpl(MethodImplOptions.NoOptimization)]
static void noOptimization() { System.Console.WriteLine(2); }
[MethodImpl(MethodImplOptions.Synchronized)]
static void synchronized() { System.Console.WriteLine(3); }
[MethodImpl(MethodImplOptions.InternalCall)]
extern static void internalCallStatic();
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
assemblyValidator: validateAssembly,
verify: Verification.Skipped);
var comp = verifier.Compilation;
var syntaxTree = comp.SyntaxTrees.Single();
var semanticModel = comp.GetSemanticModel(syntaxTree);
var localFunctions = syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToList();
checkImplAttributes(localFunctions[0], MethodImplAttributes.ForwardRef);
checkImplAttributes(localFunctions[1], MethodImplAttributes.NoInlining);
checkImplAttributes(localFunctions[2], MethodImplAttributes.NoOptimization);
checkImplAttributes(localFunctions[3], MethodImplAttributes.Synchronized);
checkImplAttributes(localFunctions[4], MethodImplAttributes.InternalCall);
void checkImplAttributes(LocalFunctionStatementSyntax localFunctionStatement, MethodImplAttributes expectedFlags)
{
var localFunction = semanticModel.GetDeclaredSymbol(localFunctionStatement).GetSymbol<LocalFunctionSymbol>();
Assert.Equal(expectedFlags, localFunction.ImplementationAttributes);
}
void validateAssembly(PEAssembly assembly)
{
var peReader = assembly.GetMetadataReader();
foreach (var methodHandle in peReader.MethodDefinitions)
{
var methodDef = peReader.GetMethodDefinition(methodHandle);
var actualFlags = methodDef.ImplAttributes;
var methodName = peReader.GetString(methodDef.Name);
var expectedFlags = methodName switch
{
"<M>g__forwardRef|0_0" => MethodImplAttributes.ForwardRef,
"<M>g__noInlining|0_1" => MethodImplAttributes.NoInlining,
"<M>g__noOptimization|0_2" => MethodImplAttributes.NoOptimization,
"<M>g__synchronized|0_3" => MethodImplAttributes.Synchronized,
"<M>g__internalCallStatic|0_4" => MethodImplAttributes.InternalCall,
".ctor" => MethodImplAttributes.IL,
"M" => MethodImplAttributes.IL,
_ => throw TestExceptionUtilities.UnexpectedValue(methodName)
};
Assert.Equal(expectedFlags, actualFlags);
}
}
}
[Fact]
public void LocalFunction_SpecialName()
{
var source = @"
using System.Runtime.CompilerServices;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[SpecialName]
void local1() { }
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
Assert.True(localFn1.HasSpecialName);
}
}
[Fact]
[WorkItem(49599, "https://github.com/dotnet/roslyn/issues/49599")]
public void MultipleLocalFunctionsUsingDynamic_01()
{
var source = @"
public class Program
{
static void Main()
{
Local1<object>();
Local1<object>();
static void Local1<T>()
{
System.Console.Write(Local2(Local3()));
static string Local2(dynamic n) => n.ToString();
}
static int Local3() => (int)(dynamic)4;
}
}
";
CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: "44");
}
[Fact]
[WorkItem(49599, "https://github.com/dotnet/roslyn/issues/49599")]
public void MultipleLocalFunctionsUsingDynamic_02()
{
var source = @"
public class Program
{
static void Main()
{
Local1<object>();
Local1<object>();
static void Local1<T>()
{
System.Console.Write(Local2(Local3<object>()));
static string Local2(dynamic n) => n.ToString();
}
static int Local3<S>() => (int)(dynamic)4;
}
}
";
CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: "44");
}
[Fact]
[WorkItem(49599, "https://github.com/dotnet/roslyn/issues/49599")]
public void MultipleLocalFunctionsUsingDynamic_03()
{
var source = @"
public class Program
{
static void Main()
{
Local1<object>();
Local1<object>();
static void Local1<T>()
{
System.Console.Write(Local2<object>(Local3<object>()));
static string Local2<U>(dynamic n) => n.ToString();
}
static int Local3<S>() => (int)(dynamic)4;
}
}
";
CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: "44");
}
[Fact]
[WorkItem(49599, "https://github.com/dotnet/roslyn/issues/49599")]
public void MultipleLocalFunctionsUsingDynamic_04()
{
var source = @"
public class Program
{
static void Main()
{
Local1<object>();
Local1<object>();
static void Local1<T>()
{
System.Console.Write(Local1<object>(Local3<object>()));
static string Local1<U>(dynamic n) => n.ToString();
}
static int Local3<S>() => (int)(dynamic)4;
}
}
";
CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: "44");
}
[Fact]
[WorkItem(49599, "https://github.com/dotnet/roslyn/issues/49599")]
public void MultipleLocalFunctionsUsingDynamic_05()
{
var source = @"
public class Program
{
static void Main()
{
Local1<object>();
Local1<object>();
static void Local1<T>()
{
System.Console.Write(Local2<object>(Local3<object>()));
static string Local2<U>(dynamic n) => n.ToString();
}
static int Local2<S>() => (int)(dynamic)4;
static int Local3<S>() => (int)(dynamic)4;
}
}
";
CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: "44");
}
internal CompilationVerifier VerifyOutput(string source, string output, CSharpCompilationOptions options, Verification verify = Verification.Passes)
{
var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: options);
return CompileAndVerify(comp, expectedOutput: output, verify: verify).VerifyDiagnostics(); // no diagnostics
}
internal CompilationVerifier VerifyOutput(string source, string output)
{
var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe);
return CompileAndVerify(comp, expectedOutput: output).VerifyDiagnostics(); // no diagnostics
}
internal CompilationVerifier VerifyOutputInMain(string methodBody, string output, params string[] usings)
{
for (var i = 0; i < usings.Length; i++)
{
usings[i] = "using " + usings[i] + ";";
}
var usingBlock = string.Join(Environment.NewLine, usings);
var source = usingBlock + @"
class Program
{
static void Main()
{
" + methodBody + @"
}
}";
return VerifyOutput(source, 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.
#nullable disable
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen
{
public static class LocalFunctionTestsUtil
{
public static IMethodSymbol FindLocalFunction(this CompilationVerifier verifier, string localFunctionName)
{
localFunctionName = (char)GeneratedNameKind.LocalFunction + "__" + localFunctionName;
var methods = verifier.TestData.GetMethodsByName();
IMethodSymbol result = null;
foreach (var kvp in methods)
{
if (kvp.Key.Contains(localFunctionName))
{
Assert.Null(result); // more than one name matched
result = ((MethodSymbol)kvp.Value.Method).GetPublicSymbol();
}
}
Assert.NotNull(result); // no methods matched
return result;
}
}
[CompilerTrait(CompilerFeature.LocalFunctions)]
public class CodeGenLocalFunctionTests : CSharpTestBase
{
[Fact]
[WorkItem(37459, "https://github.com/dotnet/roslyn/pull/37459")]
public void StaticLocalFunctionCaptureConstants()
{
var src = @"
using System;
class C
{
const int X = 1;
void M()
{
const int Y = 5;
local();
return;
static void local()
{
Console.WriteLine(X);
Console.WriteLine(Y);
}
}
public static void Main()
{
(new C()).M();
}
}
";
var verifier = CompileAndVerify(src, expectedOutput: @"
1
5");
verifier.VerifyIL("C.<M>g__local|1_0", @"
{
// Code size 13 (0xd)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ldc.i4.5
IL_0007: call ""void System.Console.WriteLine(int)""
IL_000c: ret
}");
}
[Fact]
[WorkItem(481125, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=481125")]
public void Repro481125()
{
var comp = CreateCompilation(@"
using System;
using System.Linq;
public class C
{
static void Main()
{
var c = new C();
Console.WriteLine(c.M(0).Count());
Console.WriteLine(c.M(1).Count());
}
public IQueryable<E> M(int salesOrderId)
{
using (var uow = new D())
{
return Local();
IQueryable<E> Local() => uow.ES.Where(so => so.Id == salesOrderId);
}
}
}
internal class D : IDisposable
{
public IQueryable<E> ES => new[] { new E() }.AsQueryable();
public void Dispose() { }
}
public class E
{
public int Id;
}", options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: @"1
0");
}
[Fact]
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(24647, "https://github.com/dotnet/roslyn/issues/24647")]
public void Repro24647()
{
var comp = CreateCompilation(@"
class Program
{
static void Main(string[] args)
{
void local() { } => new object();
}
}");
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var localFunction = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single();
var creation = localFunction.DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
var objectCreationOperation = model.GetOperation(creation);
var localFunctionOperation = (ILocalFunctionOperation)model.GetOperation(localFunction);
Assert.NotNull(objectCreationOperation);
comp.VerifyOperationTree(creation, expectedOperationTree:
@"
IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object, IsInvalid) (Syntax: 'new object()')
Arguments(0)
Initializer:
null
");
Assert.Equal(OperationKind.ExpressionStatement, objectCreationOperation.Parent.Kind);
Assert.Equal(OperationKind.Block, objectCreationOperation.Parent.Parent.Kind);
Assert.Same(localFunctionOperation.IgnoredBody, objectCreationOperation.Parent.Parent);
var info = model.GetTypeInfo(creation);
Assert.Equal("System.Object", info.Type.ToTestDisplayString());
Assert.Equal("System.Object", info.ConvertedType.ToTestDisplayString());
}
[Fact]
[WorkItem(22027, "https://github.com/dotnet/roslyn/issues/22027")]
public void Repro22027()
{
CompileAndVerify(@"
class Program
{
static void Main(string[] args)
{
}
public object TestLocalFn(object inp)
{
try
{
var sr = new object();
return sr;
void Local1()
{
var copy = inp;
Local2();
}
void Local2()
{
}
}
catch { throw; }
}
}");
}
[Fact]
[WorkItem(21768, "https://github.com/dotnet/roslyn/issues/21768")]
public void Repro21768()
{
var comp = CreateCompilation(@"
using System;
using System.Linq;
class C
{
void Function(int someField) //necessary to have a parameter
{
using (IInterface db = null) //necessary to have this using statement
{
void LocalFunction() //necessary
{
var results =
db.Query<Class1>() //need to call this method. using a constant array does not reproduce the bug.
.Where(cje => cje.SomeField >= someField) //need expression tree here referencing parameter
;
}
}
}
interface IInterface : IDisposable
{
IQueryable<T> Query<T>();
}
class Class1
{
public int SomeField { get; set; }
}
}");
CompileAndVerify(comp);
}
[Fact]
[WorkItem(21811, "https://github.com/dotnet/roslyn/issues/21811")]
public void Repro21811()
{
var comp = CreateCompilation(@"
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var history = new List<long>();
Enumerable.Range(0, 5)
.Select(i =>
{
history.Insert(0, i);
return Test(i);
bool Test(int v)
{
history.Remove(0);
return Square(v) > 5;
}
int Square(int w)
{
return w * w;
}
});
}
}");
}
[Fact]
[WorkItem(21645, "https://github.com/dotnet/roslyn/issues/21645")]
public void Repro21645()
{
CompileAndVerify(@"
public class Class1
{
private void Test()
{
bool outside = true;
void Inner() //This can also be a lambda (ie. Action action = () => { ... };)
{
void Bar()
{
}
void Foo()
{
Bar();
bool captured = outside;
}
}
}
}");
}
[Fact]
[WorkItem(21543, "https://github.com/dotnet/roslyn/issues/21543")]
public void Repro21543()
{
CompileAndVerify(@"
using System;
class Program
{
static void Method(Action action) { }
static void Main()
{
int value = 0;
Method(() =>
{
local();
void local()
{
Console.WriteLine(value);
Method(() =>
{
local();
});
}
});
}
}");
}
[Fact]
[WorkItem(472056, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=472056")]
public void Repro472056()
{
var comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
var task = WhyYouBreaky(new List<string>());
Console.WriteLine(task.Result);
}
static async Task<string> WhyYouBreaky(List<string> words)
{
await Task.Delay(1);
var word = """"; // moving me before the 'await' will make it work
words.Add(""Oh No!""); // I will crash here :(
return ""Great success!""; // Not so much.
void IDontEvenGetCalled()
{
// commenting out either of these lines will make it work
var a = word;
var b = words[0];
}
}
}
}", options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "Great success!");
}
[Fact]
public void AsyncStructClosure()
{
var comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Threading.Tasks;
class C
{
static void Main() => M().Wait();
static async Task M()
{
int x = 2;
int y = 3;
int L() => x + y;
Console.WriteLine(L());
await Task.FromResult(false);
}
}", options: TestOptions.ReleaseExe);
var verifier = CompileAndVerify(comp, expectedOutput: "5");
// No field captures
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"System.Runtime.CompilerServices.AsyncTaskMethodBuilder <>t__builder",
"System.Runtime.CompilerServices.TaskAwaiter<bool> <>u__1");
comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Threading.Tasks;
class C
{
static void Main() => M().Wait();
static async Task M()
{
int x = 2;
int y = 3;
int L() => x + y;
Console.WriteLine(L());
await Task.FromResult(false);
x++;
Console.WriteLine(x);
}
}", options: TestOptions.ReleaseExe);
verifier = CompileAndVerify(comp, expectedOutput: @"5
3");
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"System.Runtime.CompilerServices.AsyncTaskMethodBuilder <>t__builder",
// Display class capture
"C.<>c__DisplayClass1_0 <>8__1",
"System.Runtime.CompilerServices.TaskAwaiter<bool> <>u__1");
verifier.VerifySynthesizedFields("C.<>c__DisplayClass1_0",
"int x",
"int y");
comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Threading.Tasks;
class C
{
static void Main() => M().Wait();
static async Task M()
{
int x = 2;
int y = 3;
int L() => x + y;
Console.WriteLine(L());
await Task.FromResult(false);
x = 5;
y = 7;
Console.WriteLine(L());
}
}", options: TestOptions.ReleaseExe);
verifier = CompileAndVerify(comp, expectedOutput: @"5
12");
// Nothing captured across await
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"System.Runtime.CompilerServices.AsyncTaskMethodBuilder <>t__builder",
"System.Runtime.CompilerServices.TaskAwaiter<bool> <>u__1");
}
[Fact]
public void IteratorStructClosure()
{
var verifier = CompileAndVerify(@"
using System;
using System.Collections.Generic;
class C
{
static void Main()
{
foreach (var m in M())
{
Console.WriteLine(m);
}
}
static IEnumerable<int> M()
{
int x = 2;
int y = 3;
int L() => x + y;
yield return L();
}
}", expectedOutput: "5");
// No field captures
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"int <>2__current",
"int <>l__initialThreadId");
verifier = CompileAndVerify(@"
using System;
using System.Collections.Generic;
class C
{
static void Main()
{
foreach (var m in M())
{
Console.WriteLine(m);
}
}
static IEnumerable<int> M()
{
int x = 2;
int y = 3;
int L() => x + y;
yield return L();
x++;
yield return x;
}
}", expectedOutput: @"5
3");
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"int <>2__current",
"int <>l__initialThreadId",
// Display class capture
"C.<>c__DisplayClass1_0 <>8__1");
verifier.VerifySynthesizedFields("C.<>c__DisplayClass1_0",
"int x",
"int y");
verifier = CompileAndVerify(@"
using System;
using System.Collections.Generic;
class C
{
static void Main()
{
foreach (var m in M())
{
Console.WriteLine(m);
}
}
static IEnumerable<int> M()
{
int x = 2;
int y = 3;
int L() => x + y;
yield return L();
x = 5;
y = 7;
yield return L();
}
}", expectedOutput: @"5
12");
// No captures
verifier.VerifySynthesizedFields("C.<M>d__1",
"int <>1__state",
"int <>2__current",
"int <>l__initialThreadId");
}
[Fact]
[WorkItem(21409, "https://github.com/dotnet/roslyn/issues/21409")]
public void Repro21409()
{
CompileAndVerify(
@"
using System;
using System.Collections.Generic;
namespace Buggles
{
class Program
{
private static IEnumerable<int> Problem(IEnumerable<int> chunks)
{
var startOfChunk = 0;
var pendingChunks = new List<int>();
int GenerateChunk()
{
if (pendingChunks == null)
{
Console.WriteLine(""impossible in local function"");
return -1;
}
while (pendingChunks.Count > 0)
{
pendingChunks.RemoveAt(0);
}
return startOfChunk;
}
foreach (var chunk in chunks)
{
if (chunk - startOfChunk <= 0)
{
pendingChunks.Insert(0, chunk);
}
else
{
yield return GenerateChunk();
}
startOfChunk = chunk;
if (pendingChunks == null)
{
Console.WriteLine(""impossible in outer function"");
}
else
{
pendingChunks.Insert(0, chunk);
}
}
}
private static void Main()
{
var xs = Problem(new[] { 0, 1, 2, 3 });
foreach (var x in xs)
{
Console.WriteLine(x);
}
}
}
}
", expectedOutput: @"
0
1
2");
}
[Fact]
[WorkItem(294554, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=294554")]
public void ThisOnlyClosureBetweenStructCaptures()
{
CompileAndVerify(@"
using System;
class C
{
int _x = 0;
void M()
{
void L1()
{
int x = 0;
_x++;
void L2()
{
Action a2 = L2;
int y = 0;
L3();
void L3()
{
_x++;
y++;
}
}
L2();
void L5() => x++;
L5();
}
L1();
}
}");
}
[Fact]
public void CaptureThisInDifferentScopes()
{
CompileAndVerify(@"
using System;
class C
{
int _x;
void M()
{
{
int y = 0;
Func<int> f1 = () => _x + y;
}
{
int y = 0;
Func<int> f2 = () => _x + y;
}
}
}");
}
[Fact]
public void CaptureThisInDifferentScopes2()
{
CompileAndVerify(@"
using System;
class C
{
int _x;
void M()
{
{
int y = 0;
int L1() => _x + y;
}
{
int y = 0;
int L2() => _x + y;
}
}
}");
}
[Fact]
public void CaptureFramePointerInDifferentScopes()
{
CompileAndVerify(@"
using System;
class C
{
void M(int x)
{
Func<int> f1 = () => x;
{
int z = 0;
Func<int> f2 = () => x + z;
}
{
int z = 0;
Func<int> f3 = () => x + z;
}
}
}");
}
[Fact]
public void EnvironmentChainContainsStructEnvironment()
{
CompileAndVerify(@"
using System;
class C
{
void M(int x)
{
{
int y = 10;
void L() => Console.WriteLine(y);
{
int z = 5;
Action f2 = () => Console.WriteLine(z + x);
f2();
}
L();
}
}
public static void Main() => new C().M(3);
}", expectedOutput: @"8
10");
}
[Fact]
public void Repro20577()
{
var comp = CreateCompilation(@"
using System.Linq;
public class Program {
public static void Main(string[] args) {
object v;
void AAA() {
object BBB(object v2) {
var a = v;
((object[])v2).Select(i => BBB(i));
return null;
}
}
}
}");
CompileAndVerify(comp);
}
[Fact]
public void Repro19033()
{
CompileAndVerify(@"
using System;
class Program
{
void Q(int n = 0)
{
{
object mc;
string B(object map)
{
Action<int> a = _ => B(new object());
return n.ToString();
}
}
}
}");
}
[Fact]
public void Repro19033_2()
{
CompileAndVerify(@"
using System;
class C
{
static void F(Action a)
{
object x = null;
{
object y = null;
void G(object z)
{
F(() => G(x));
}
}
}
}");
}
[Fact]
[WorkItem(18814, "https://github.com/dotnet/roslyn/issues/18814")]
[WorkItem(18918, "https://github.com/dotnet/roslyn/issues/18918")]
public void IntermediateStructClosures1()
{
var verifier = CompileAndVerify(@"
using System;
class C
{
int _x = 0;
public static void Main() => new C().M();
public void M()
{
int var1 = 0;
void L1()
{
void L2()
{
void L3()
{
void L4()
{
int var2 = 0;
void L5()
{
int L6() => var2 + _x++;
L6();
}
L5();
}
L4();
}
L3();
}
L2();
int L8() => var1;
}
Console.WriteLine(_x);
L1();
Console.WriteLine(_x);
}
}", expectedOutput:
@"0
1");
verifier.VerifyIL("C.M()", @"
{
// Code size 47 (0x2f)
.maxstack 2
.locals init (C.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0
IL_0000: ldloca.s V_0
IL_0002: ldarg.0
IL_0003: stfld ""C C.<>c__DisplayClass2_0.<>4__this""
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.0
IL_000b: stfld ""int C.<>c__DisplayClass2_0.var1""
IL_0010: ldarg.0
IL_0011: ldfld ""int C._x""
IL_0016: call ""void System.Console.WriteLine(int)""
IL_001b: ldarg.0
IL_001c: ldloca.s V_0
IL_001e: call ""void C.<M>g__L1|2_0(ref C.<>c__DisplayClass2_0)""
IL_0023: ldarg.0
IL_0024: ldfld ""int C._x""
IL_0029: call ""void System.Console.WriteLine(int)""
IL_002e: ret
}");
// L1
verifier.VerifyIL("C.<M>g__L1|2_0(ref C.<>c__DisplayClass2_0)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""void C.<M>g__L2|2_1(ref C.<>c__DisplayClass2_0)""
IL_0007: ret
}");
// L2
verifier.VerifyIL("C.<M>g__L2|2_1(ref C.<>c__DisplayClass2_0)", @"
{
// Code size 8 (0x8)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call ""void C.<M>g__L3|2_3(ref C.<>c__DisplayClass2_0)""
IL_0007: ret
}");
// Skip some... L5
verifier.VerifyIL("C.<M>g__L5|2_5(ref C.<>c__DisplayClass2_0, ref C.<>c__DisplayClass2_1)", @"
{
// Code size 10 (0xa)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: call ""int C.<M>g__L6|2_6(ref C.<>c__DisplayClass2_0, ref C.<>c__DisplayClass2_1)""
IL_0008: pop
IL_0009: ret
}");
// L6
verifier.VerifyIL("C.<M>g__L6|2_6(ref C.<>c__DisplayClass2_0, ref C.<>c__DisplayClass2_1)", @"
{
// Code size 25 (0x19)
.maxstack 4
.locals init (int V_0)
IL_0000: ldarg.2
IL_0001: ldfld ""int C.<>c__DisplayClass2_1.var2""
IL_0006: ldarg.0
IL_0007: ldarg.0
IL_0008: ldfld ""int C._x""
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: ldc.i4.1
IL_0010: add
IL_0011: stfld ""int C._x""
IL_0016: ldloc.0
IL_0017: add
IL_0018: ret
}");
}
[Fact]
[WorkItem(18814, "https://github.com/dotnet/roslyn/issues/18814")]
[WorkItem(18918, "https://github.com/dotnet/roslyn/issues/18918")]
public void IntermediateStructClosures2()
{
CompileAndVerify(@"
class C
{
int _x;
void M()
{
int y = 0;
void L1()
{
void L2()
{
int z = 0;
int L3() => z + _x;
}
y++;
}
}
}");
}
[Fact]
[WorkItem(18814, "https://github.com/dotnet/roslyn/issues/18814")]
public void Repro18814()
{
CompileAndVerify(@"
class Program
{
private void ResolvingPackages()
{
string outerScope(int a) => """";
void C1(int cabinetIdx)
{
void modifyState()
{
var no = outerScope(cabinetIdx);
}
modifyState();
}
}
}");
}
[Fact]
[WorkItem(18918, "https://github.com/dotnet/roslyn/issues/18918")]
public void Repro18918()
{
CompileAndVerify(@"
public class Test
{
private int _field;
public void OuterMethod(int outerParam)
{
void InnerMethod1()
{
void InnerInnerMethod(int innerInnerParam)
{
InnerInnerInnerMethod();
bool InnerInnerInnerMethod()
{
return innerInnerParam != _field;
}
}
void InnerMethod2()
{
var temp = outerParam;
}
}
}
}");
}
[Fact]
[WorkItem(17719, "https://github.com/dotnet/roslyn/issues/17719")]
public void Repro17719()
{
var comp = CompileAndVerify(@"
using System;
class C
{
public static void Main()
{
T GetField<T>(string name, T @default = default(T))
{
return @default;
}
Console.WriteLine(GetField<int>(string.Empty));
}
}", expectedOutput: "0");
}
[Fact]
[WorkItem(17890, "https://github.com/dotnet/roslyn/issues/17890")]
public void Repro17890()
{
var comp = CreateCompilationWithMscorlib46(@"
using System;
using System.Collections.Generic;
using System.Linq;
public class Class
{
public class Item
{
public int Id { get; set; }
}
public class ItemsContainer : IDisposable
{
public List<Item> Items { get; set; }
public void Dispose()
{
}
}
public static void CompilerError()
{
using (var itemsContainer = new ItemsContainer())
{
Item item = null;
itemsContainer.Items.Where(x => x.Id == item.Id);
void Local1()
{
itemsContainer.Items = null;
}
void Local2()
{
Local1();
}
}
}
}", references: new[] { LinqAssemblyRef });
CompileAndVerify(comp);
}
[Fact]
[WorkItem(16783, "https://github.com/dotnet/roslyn/issues/16783")]
public void GenericDefaultParams()
{
CompileAndVerify(@"
using System;
class C
{
public void M()
{
void Local<T>(T t = default(T))
{
Console.WriteLine(t);
}
Local<int>();
}
}
class C2
{
public static void Main()
{
new C().M();
}
}", expectedOutput: "0");
}
[Fact]
public void GenericCaptureDefaultParams()
{
CompileAndVerify(@"
using System;
class C<T>
{
public void M()
{
void Local(T t = default(T))
{
Console.WriteLine(t);
}
Local();
}
}
class C2
{
public static void Main()
{
new C<int>().M();
}
}", expectedOutput: "0");
}
[Fact]
public void NameofRecursiveDefaultParameter()
{
var comp = CreateCompilation(@"
using System;
class C
{
public static void Main()
{
void Local(string s = nameof(Local))
{
Console.WriteLine(s);
}
Local();
}
}", options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
comp.DeclarationDiagnostics.Verify();
CompileAndVerify(comp, expectedOutput: "Local");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope()
{
var src = @"
using System;
class C
{
public static void Main()
{
var d = """";
{
int x = 0;
void M()
{
if (d != null)
{
Action a = () => x++;
a();
}
}
M();
Console.WriteLine(x);
}
}
}";
CompileAndVerify(src, expectedOutput: "1");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope2()
{
var src = @"
using System;
class C
{
class D : IDisposable { public void Dispose() {} }
public static void Main()
{
using (var d = new D())
{
int x = 0;
void M()
{
if (d != null)
{
Action a = () => x++;
a();
}
}
M();
Console.WriteLine(x);
}
}
}";
CompileAndVerify(src, expectedOutput: "1");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope3()
{
var src = @"
using System;
class C
{
public static void Main()
{
var d = """";
{
int x = 0;
void M()
{
if (d != null)
{
void Local() => x++;
Action a = Local;
a();
}
}
M();
Console.WriteLine(x);
}
}
}";
CompileAndVerify(src, expectedOutput: "1");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope4()
{
var src = @"
using System;
class C
{
public static void Main()
{
var d = """";
{
int y = 0;
{
int x = 0;
void M()
{
if (d != null)
{
Action a = () => x++;;
a();
}
}
M();
Console.WriteLine(x);
}
y++;
}
}
}";
CompileAndVerify(src, expectedOutput: "1");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope5()
{
var src = @"
using System;
class C
{
public static void Main()
{
int x = 0;
{
int y = 0;
void L()
{
int z = 0;
void L2()
{
if (x == 0 && z == 0)
{
Action a = () => y++;
a();
}
}
L2();
}
L();
Console.WriteLine(y);
}
}
}";
CompileAndVerify(src, expectedOutput: "1");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope6()
{
var src = @"
using System;
class C
{
public static void Main()
{
int x = 0;
{
int y = 0;
void L()
{
int z = 0;
void L2()
{
if (x == 0 && y == 0)
{
Action a = () => z++;
a();
}
y++;
}
L2();
Console.WriteLine(z);
}
L();
Console.WriteLine(y);
}
((Action)(() => x++))();
Console.WriteLine(x);
}
}";
CompileAndVerify(src, expectedOutput: @"1
1
1");
}
[ConditionalFact(typeof(DesktopOnly))]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope7()
{
var src = @"
using System;
using System.Threading.Tasks;
class C
{
public static void Main()
{
int x = 0;
{
int y = 0;
void L()
{
if (x == 0)
{
async Task L2()
{
await Task.Delay(1);
y++;
}
L2().Wait();
}
}
L();
Console.WriteLine(y);
}
Console.WriteLine(x);
}
}";
CompileAndVerify(src,
targetFramework: TargetFramework.Mscorlib46,
expectedOutput: @"1
0");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void CaptureVarNestedLambdaSkipScope8()
{
var src = @"
using System;
using System.Collections.Generic;
class C
{
public static void Main()
{
int x = 0;
{
int y = 0;
void L()
{
if (x == 0)
{
IEnumerable<int> L2()
{
yield return 0;
y++;
}
foreach (var i in L2()) { }
}
}
L();
Console.WriteLine(y);
}
Console.WriteLine(x);
}
}";
CompileAndVerifyWithMscorlib46(src,
expectedOutput: @"1
0");
}
[Fact]
[WorkItem(16895, "https://github.com/dotnet/roslyn/issues/16895")]
public void LocalFunctionCaptureSkipScope()
{
var src = @"
using System;
class C
{
public static void Main(string[] args)
{
{
int uncaptured = 0;
uncaptured++;
{
int x = 0;
bool Local(int y) => x == 0 && args == null && y == 0;
Local(0);
}
}
}
}";
CompileAndVerify(src);
}
[Fact]
[WorkItem(16399, "https://github.com/dotnet/roslyn/issues/16399")]
public void RecursiveGenericLocalFunctionIterator()
{
var src = @"
using System;
using System.Collections.Generic;
using System.Linq;
public static class EnumerableExtensions
{
static void Main(string[] args)
{
GetLeaves<object>(new List<object>(), list => null);
var results = GetLeaves<object>(
new object[] {
new[] { ""a"", ""b""},
new[] { ""c"" },
new[] { new[] { ""d"" } }
}, node => node is string ? null : (IEnumerable<object>)node);
foreach (var i in results)
{
Console.WriteLine(i);
}
}
public static IEnumerable<T> GetLeaves<T>(T root, Func<T, IEnumerable<T>> getChildren)
{
return GetLeaves(root);
IEnumerable<T> GetLeaves(T node)
{
var children = getChildren(node);
if (children == null)
{
return new[] { node };
}
else
{
return children.SelectMany(GetLeaves);
}
}
}
}";
VerifyOutput(src, @"a
b
c
d");
}
[Fact]
[WorkItem(243633, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/243633")]
public void CaptureGenericFieldAndParameter()
{
var src = @"
using System;
using System.Collections.Generic;
class Test<T>
{
T Value;
public bool Goo(IEqualityComparer<T> comparer)
{
bool local(T tmp)
{
return comparer.Equals(tmp, this.Value);
}
return local(this.Value);
}
}
";
var comp = CompileAndVerify(src);
}
[Fact]
public void CaptureGenericField()
{
var src = @"
using System;
class C<T>
{
T Value = default(T);
public void M()
{
void L()
{
Console.WriteLine(Value);
}
var f = (Action)(() => L());
f();
}
}
class C2
{
public static void Main(string[] args) => new C<int>().M();
}
";
VerifyOutput(src, "0");
}
[Fact]
public void CaptureGenericParam()
{
var src = @"
using System;
class C<T>
{
T Value = default(T);
public void M<U>(U val2)
{
void L()
{
Console.WriteLine(Value);
Console.WriteLine(val2);
}
var f = (Action)(() => L());
f();
}
}
class C2
{
public static void Main(string[] args) => new C<int>().M(10);
}
";
VerifyOutput(src, @"0
10");
}
[Fact]
public void CaptureGenericParamInGenericLocalFunc()
{
var src = @"
using System;
class C<T>
{
T Value = default(T);
public void M<U>(U v1)
{
void L<V>(V v2) where V : T
{
Console.WriteLine(Value);
Console.WriteLine(v1);
Console.WriteLine(v2);
}
var f = (Action)(() => L<T>(Value));
f();
}
}
class C2
{
public static void Main(string[] args) => new C<int>().M(10);
}
";
VerifyOutput(src, @"0
10
0");
}
[Fact]
public void DeepNestedLocalFuncsWithDifferentCaptures()
{
var src = @"
using System;
class C
{
int P = 100000;
void M()
{
C Local1() => this;
int capture1 = 1;
Func<int> f1 = () => capture1 + Local1().P;
Console.WriteLine(f1());
{
C Local2() => Local1();
int capture2 = 10;
Func<int> f2 = () => capture2 + Local2().P;
Console.WriteLine(f2());
{
C Local3() => Local2();
int capture3 = 100;
Func<int> f3 = () => capture1 + capture2 + capture3 + Local3().P;
Console.WriteLine(f3());
Console.WriteLine(Local3().P);
}
}
}
public static void Main() => new C().M();
}";
VerifyOutput(src, @"100001
100010
100111
100000");
}
[Fact]
public void LotsOfMutuallyRecursiveLocalFunctions()
{
var src = @"
class C
{
int P = 0;
public void M()
{
int Local1() => this.P;
int Local2() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local3() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local4() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local5() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local6() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local7() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local8() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local9() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local10() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local11() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
int Local12() => Local12() + Local11() + Local10() + Local9() + Local8() + Local7() + Local6() + Local5() + Local4() + Local3() + Local2() + Local1();
Local1();
Local2();
Local3();
Local4();
Local5();
Local6();
Local7();
Local8();
Local9();
Local10();
Local11();
Local12();
}
}
";
var comp = CreateCompilation(src);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void LocalFuncAndLambdaWithDifferentThis()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local(int x) => x + this.P;
int y = 10;
var a = new Func<int>(() => Local(y));
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "11");
}
[Fact]
public void LocalFuncAndLambdaWithDifferentThis2()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local() => 10 + this.P;
int Local2(int x) => x + Local();
int y = 100;
var a = new Func<int>(() => Local2(y));
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "111");
}
[Fact]
public void LocalFuncAndLambdaWithDifferentThis3()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local()
{
if (this.P < 5)
{
return Local2(this.P++);
}
else
{
return 1;
}
}
int Local2(int x) => x + Local();
int y = 100;
var a = new Func<int>(() => Local2(y));
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "111");
}
[Fact]
public void LocalFuncAndLambdaWithDifferentThis4()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local(int x) => x + this.P;
int y = 10;
var a = new Func<int>(() =>
{
var b = (Func<int, int>)Local;
return b(y);
});
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "11");
}
[Fact]
public void LocalFuncAndLambdaWithDifferentThis5()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local(int x) => x + this.P;
int y = 10;
var a = new Func<int>(() =>
{
var b = new Func<int, int>(Local);
return b(y);
});
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "11");
}
[Fact]
public void TwoFrames()
{
var src = @"
using System;
class C
{
private int P = 0;
public void M()
{
int x = 0;
var a = new Func<int>(() =>
{
int Local() => x + this.P;
int z = 0;
int Local3() => z + Local();
return Local3();
});
Console.WriteLine(a());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "0");
}
[Fact]
public void SameFrame()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int x = 10;
int Local() => x + this.P;
int y = 100;
int Local2() => y + Local();
Console.WriteLine(Local2());
}
public static void Main(string[] args)
{
var c = new C();
c.M();
}
}";
VerifyOutput(src, "111");
}
[Fact]
public void MutuallyRecursiveThisCapture()
{
var src = @"
using System;
class C
{
private int P = 1;
public void M()
{
int Local()
{
if (this.P < 5)
{
return Local2(this.P++);
}
else
{
return 1;
}
}
int Local2(int x) => x + Local();
Console.WriteLine(Local());
}
public static void Main() => new C().M();
}";
VerifyOutput(src, "11");
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicParameterLocalFunction()
{
var src = @"
using System;
class C
{
static void Main(string[] args) => M(0);
static void M(int x)
{
dynamic y = x + 1;
Action a;
Action local(dynamic z)
{
Console.Write(z);
Console.Write(y);
return () => Console.Write(y + z + 1);
}
a = local(x);
a();
}
}";
VerifyOutput(src, "012");
}
[Fact]
public void EndToEnd()
{
var source = @"
using System;
class Program
{
static void Main(string[] args)
{
void Local()
{
Console.WriteLine(""Hello, world!"");
}
Local();
}
}
";
VerifyOutput(source, "Hello, world!");
}
[Fact]
[CompilerTrait(CompilerFeature.ExpressionBody)]
public void ExpressionBody()
{
var source = @"
int Local() => 2;
Console.Write(Local());
Console.Write(' ');
void VoidLocal() => Console.Write(2);
VoidLocal();
";
VerifyOutputInMain(source, "2 2", "System");
}
[Fact]
public void EmptyStatementAfter()
{
var source = @"
void Local()
{
Console.Write(2);
};
Local();
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
[CompilerTrait(CompilerFeature.Params)]
public void Params()
{
var source = @"
void Params(params int[] x)
{
Console.WriteLine(string.Join("","", x));
}
Params(2);
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void RefAndOut()
{
var source = @"
void RefOut(ref int x, out int y)
{
y = ++x;
}
int a = 1;
int b;
RefOut(ref a, out b);
Console.Write(a);
Console.Write(' ');
Console.Write(b);
";
VerifyOutputInMain(source, "2 2", "System");
}
[Fact]
public void NamedAndOptional()
{
var source = @"
void NamedOptional(int x = 2)
{
Console.Write(x);
}
NamedOptional(x: 3);
Console.Write(' ');
NamedOptional();
";
VerifyOutputInMain(source, "3 2", "System");
}
[Fact, WorkItem(51518, "https://github.com/dotnet/roslyn/issues/51518")]
public void OptionalParameterCodeGen()
{
var source = @"
public class C
{
public static void Main()
{
LocalFunc();
void LocalFunc(int a = 2) { }
}
}
";
var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedSignatures: new SignatureDescription[]
{
Signature("C", "Main", ".method public hidebysig static System.Void Main() cil managed"),
Signature("C", "<Main>g__LocalFunc|0_0", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] assembly hidebysig static System.Void <Main>g__LocalFunc|0_0([opt] System.Int32 a = 2) cil managed")
});
}
[Fact, WorkItem(53478, "https://github.com/dotnet/roslyn/issues/53478")]
public void OptionalParameterCodeGen_Reflection()
{
VerifyOutputInMain(@"void TestAction(int i = 5) { }
var d = (Action<int>)TestAction;
var p2 = d.Method.GetParameters();
Console.WriteLine(p2[0].HasDefaultValue);
Console.WriteLine(p2[0].DefaultValue);", @"True
5", new[] { "System" });
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicArgShadowing()
{
var src = @"
using System;
class C
{
static void Shadow(int x) => Console.Write(x + 1);
static void Main()
{
void Shadow(int x) => Console.Write(x);
dynamic val = 2;
Shadow(val);
}
}";
VerifyOutput(src, "2");
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicParameter()
{
var source = @"
using System;
class Program
{
static void Main()
{
void Local(dynamic x)
{
Console.Write(x);
}
Local(2);
}
}
";
VerifyOutput(source, "2");
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicReturn()
{
var source = @"
dynamic RetDyn()
{
return 2;
}
Console.Write(RetDyn());
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicDelegate()
{
var source = @"
using System;
class Program
{
static void Main()
{
dynamic Local(dynamic x)
{
return x;
}
dynamic L2(int x)
{
void L2_1(int y)
{
Console.Write(x);
Console.Write(y);
}
dynamic z = x + 1;
void L2_2() => L2_1(z);
return (Action)L2_2;
}
dynamic local = (Func<dynamic, dynamic>)Local;
Console.Write(local(2));
L2(3)();
}
}
";
VerifyOutput(source, "234");
}
[Fact]
public void Nameof()
{
var source = @"
void Local()
{
}
Console.Write(nameof(Local));
";
VerifyOutputInMain(source, "Local", "System");
}
[Fact]
public void ExpressionTreeParameter()
{
var source = @"
Expression<Func<int, int>> Local(Expression<Func<int, int>> f)
{
return f;
}
Console.Write(Local(x => x));
";
VerifyOutputInMain(source, "x => x", "System", "System.Linq.Expressions");
}
[Fact]
public void LinqInLocalFunction()
{
var source = @"
IEnumerable<int> Query(IEnumerable<int> values)
{
return from x in values where x < 5 select x * x;
}
Console.Write(string.Join("","", Query(Enumerable.Range(0, 10))));
";
VerifyOutputInMain(source, "0,1,4,9,16", "System", "System.Linq", "System.Collections.Generic");
}
[Fact]
public void ConstructorWithoutArg()
{
var source = @"
using System;
class Base
{
public int x;
public Base(int x)
{
this.x = x;
}
}
class Program : Base
{
Program() : base(2)
{
void Local()
{
Console.Write(x);
}
Local();
}
public static void Main()
{
new Program();
}
}
";
VerifyOutput(source, "2");
}
[Fact]
public void ConstructorWithArg()
{
var source = @"
using System;
class Base
{
public int x;
public Base(int x)
{
this.x = x;
}
}
class Program : Base
{
Program(int x) : base(x + 2)
{
void Local()
{
Console.Write(x);
Console.Write(' ');
Console.Write(base.x);
}
Local();
}
public static void Main()
{
new Program(2);
}
}
";
VerifyOutput(source, "2 4");
}
[Fact]
public void IfDef()
{
var source = @"
using System;
class Program
{
public static void Main()
{
#if LocalFunc
void Local()
{
Console.Write(2);
Console.Write(' ');
#endif
Console.Write(4);
#if LocalFunc
}
Local();
#endif
}
}
";
VerifyOutput(source, "4");
source = "#define LocalFunc" + source;
VerifyOutput(source, "2 4");
}
[Fact]
public void PragmaWarningDisableEntersLocfunc()
{
var source = @"
#pragma warning disable CS0168
void Local()
{
int x; // unused
Console.Write(2);
}
#pragma warning restore CS0168
Local();
";
// No diagnostics is asserted in VerifyOutput, so if the warning happens, then we'll catch it
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void ObsoleteAttributeRecursion()
{
var source = @"
using System;
class Program
{
[Obsolete]
public void Obs()
{
void Local()
{
Obs(); // shouldn't emit warning
}
Local();
}
public static void Main()
{
Console.Write(2);
}
}
";
VerifyOutput(source, "2");
}
[Fact]
public void MainLocfuncIsntEntry()
{
var source = @"
void Main()
{
Console.Write(4);
}
Console.Write(2);
Console.Write(' ');
Main();
";
VerifyOutputInMain(source, "2 4", "System");
}
[Fact]
public void Shadows()
{
var source = @"
using System;
class Program
{
static void Local()
{
Console.WriteLine(""bad"");
}
static void Main(string[] args)
{
void Local()
{
Console.Write(2);
}
Local();
}
}
";
VerifyOutput(source, "2");
}
[Fact]
public void ExtensionMethodClosure()
{
var source = @"
using System;
static class Program
{
public static void Ext(this int x)
{
void Local()
{
Console.Write(x);
}
Local();
}
public static void Main()
{
2.Ext();
}
}
";
// warning level 0 because extension method generates CS1685 (predefined type multiple definition) for ExtensionAttribute in System.Core and mscorlib
VerifyOutput(source, "2", TestOptions.ReleaseExe.WithWarningLevel(0));
}
[Fact]
public void Scoping()
{
var source = @"
void Local()
{
Console.Write(2);
}
if (true)
{
Local();
}
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void Property()
{
var source = @"
using System;
class Program
{
static int Goo
{
get
{
int Local()
{
return 2;
}
return Local();
}
}
static void Main(string[] args)
{
Console.Write(Goo);
}
}";
VerifyOutput(source, "2");
}
[Fact]
public void PropertyIterator()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
static int Goo
{
get
{
int a = 2;
IEnumerable<int> Local()
{
yield return a;
}
foreach (var x in Local())
{
return x;
}
return 0;
}
}
static void Main(string[] args)
{
Console.Write(Goo);
}
}";
VerifyOutput(source, "2");
}
[Fact]
public void DelegateFunc()
{
var source = @"
int Local(int x) => x;
Func<int, int> local = Local;
Console.Write(local(2));
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void DelegateFuncGenericImplicit()
{
var source = @"
T Local<T>(T x) => x;
Func<int, int> local = Local;
Console.Write(local(2));
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void DelegateFuncGenericExplicit()
{
var source = @"
T Local<T>(T x) => x;
Func<int, int> local = Local<int>;
Console.Write(local(2));
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void DelegateAction()
{
var source = @"
void Local()
{
Console.Write(2);
}
var local = new Action(Local);
local();
Console.Write(' ');
local = (Action)Local;
local();
";
VerifyOutputInMain(source, "2 2", "System");
}
[Fact]
public void InterpolatedString()
{
var source = @"
int x = 1;
int Bar() => ++x;
var str = $@""{((Func<int>)(() => { int Goo() => Bar(); return Goo(); }))()}"";
Console.Write(str + ' ' + x);
";
VerifyOutputInMain(source, "2 2", "System");
}
// StaticNoClosure*() are generic because the reference to the locfunc is constructed, and actual local function is not
// (i.e. testing to make sure we use MethodSymbol.OriginalDefinition in LambdaRewriter.Analysis)
[Fact]
public void StaticNoClosure()
{
var source = @"
T Goo<T>(T x)
{
return x;
}
Console.Write(Goo(2));
";
var verify = VerifyOutputInMain(source, "2", "System");
var goo = verify.FindLocalFunction("Goo");
Assert.True(goo.IsStatic);
Assert.Equal(verify.Compilation.GetTypeByMetadataName("Program"), goo.ContainingType);
}
[Fact]
public void StaticNoClosureDelegate()
{
var source = @"
T Goo<T>(T x)
{
return x;
}
Func<int, int> goo = Goo;
Console.Write(goo(2));
";
var verify = VerifyOutputInMain(source, "2", "System");
var goo = verify.FindLocalFunction("Goo");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.True(goo.IsStatic);
Assert.Equal(program, goo.ContainingType);
}
[Fact]
public void ClosureBasic()
{
var source = @"
using System;
class Program
{
static void Print(int a)
{
Console.Write(' ');
Console.Write(a);
}
static void A(int y)
{
int x = 1;
void Local()
{
Print(x); Print(y);
}
Local();
Print(x); Print(y);
x = 3;
y = 4;
Local();
Print(x); Print(y);
void Local2()
{
Print(x); Print(y);
x += 2;
y += 2;
Print(x); Print(y);
}
Local2();
Print(x); Print(y);
}
static void Main(string[] args)
{
A(2);
}
}
";
VerifyOutput(source, "1 2 1 2 3 4 3 4 3 4 5 6 5 6");
}
[Fact]
public void ClosureThisOnly()
{
var source = @"
using System;
class Program
{
int _a;
static void Print(int a)
{
Console.Write(' ');
Console.Write(a);
}
void B()
{
_a = 2;
void Local()
{
Print(_a);
_a++;
Print(_a);
}
Print(_a);
Local();
Print(_a);
}
static void Main(string[] args)
{
new Program().B();
}
}";
VerifyOutput(source, "2 2 3 3");
}
[Fact]
public void ClosureGeneralThisOnly()
{
var source = @"
var x = 0;
void Outer()
{
if (++x == 2)
{
Console.Write(x);
return;
}
void Inner()
{
Outer();
}
Inner();
}
Outer();
";
var verify = VerifyOutputInMain(source, "2", "System");
var outer = verify.FindLocalFunction("Outer");
var inner = verify.FindLocalFunction("Inner");
Assert.Equal(outer.ContainingType, inner.ContainingType);
}
[Fact]
public void ClosureStaticInInstance()
{
var source = @"
using System;
class Program
{
static int _sa;
static void Print(int a)
{
Console.Write(' ');
Console.Write(a);
}
void C()
{
_sa = 2;
void Local()
{
Print(_sa);
_sa++;
Print(_sa);
}
Print(_sa);
Local();
Print(_sa);
}
static void Main(string[] args)
{
new Program().C();
}
}";
VerifyOutput(source, "2 2 3 3");
}
[Fact]
public void ClosureGeneric()
{
var source = @"
using System;
class Program
{
static void Print(object a)
{
Console.Write(' ');
Console.Write(a);
}
class Gen<T1>
{
T1 t1;
public Gen(T1 t1)
{
this.t1 = t1;
}
public void D<T2>(T2 t2)
{
T2 Local(T1 x)
{
Print(x);
Print(t1);
t1 = (T1)(object)((int)(object)x + 2);
t2 = (T2)(object)x;
return (T2)(object)((int)(object)t2 + 4);
}
Print(t1);
Print(t2);
Print(Local(t1));
Print(t1);
Print(t2);
}
}
static void Main(string[] args)
{
new Gen<int>(2).D<int>(3);
}
}";
VerifyOutput(source, "2 3 2 2 6 4 2");
}
[Fact]
public void ClosureLambdasAndLocfuncs()
{
var source = @"
using System;
class Program
{
static void Print(int a)
{
Console.Write(' ');
Console.Write(a);
}
static void E()
{
int a = 2;
void M1()
{
int b = a;
Action M2 = () =>
{
int c = b;
void M3()
{
int d = c;
Print(d + b);
}
M3();
};
M2();
}
M1();
}
static void Main(string[] args)
{
E();
}
}";
VerifyOutput(source, "4");
}
[Fact]
public void ClosureTripleNested()
{
var source = @"
using System;
class Program
{
static void Print(int a)
{
Console.Write(' ');
Console.Write(a);
}
static void A()
{
int a = 0;
void M1()
{
int b = a;
void M2()
{
int c = b;
void M3()
{
Print(c);
c = 2;
}
Print(b);
M3();
Print(c);
b = 2;
}
Print(a);
M2();
Print(b);
a = 2;
}
M1();
Print(a);
}
static void B()
{
int a = 0;
void M1()
{
int b = a;
void M2()
{
void M3()
{
Print(b);
b = 2;
}
M3();
Print(b);
}
Print(a);
M2();
Print(b);
a = 2;
}
M1();
Print(a);
}
static void C()
{
int a = 0;
void M1()
{
void M2()
{
int c = a;
void M3()
{
Print(c);
c = 2;
}
Print(a);
M3();
Print(c);
a = 2;
}
M2();
Print(a);
}
M1();
Print(a);
}
static void D()
{
void M1()
{
int b = 0;
void M2()
{
int c = b;
void M3()
{
Print(c);
c = 2;
}
Print(b);
M3();
Print(c);
b = 2;
}
M2();
Print(b);
}
M1();
}
static void E()
{
int a = 0;
void M1()
{
void M2()
{
void M3()
{
Print(a);
a = 2;
}
M3();
Print(a);
}
M2();
Print(a);
}
M1();
Print(a);
}
static void F()
{
void M1()
{
int b = 0;
void M2()
{
void M3()
{
Print(b);
b = 2;
}
M3();
Print(b);
}
M2();
Print(b);
}
M1();
}
static void G()
{
void M1()
{
void M2()
{
int c = 0;
void M3()
{
Print(c);
c = 2;
}
M3();
Print(c);
}
M2();
}
M1();
}
static void Main(string[] args)
{
A();
Console.WriteLine();
B();
Console.WriteLine();
C();
Console.WriteLine();
D();
Console.WriteLine();
E();
Console.WriteLine();
F();
Console.WriteLine();
G();
Console.WriteLine();
}
}
";
VerifyOutput(source, @"
0 0 0 2 2 2
0 0 2 2 2
0 0 2 2 2
0 0 2 2
0 2 2 2
0 2 2
0 2
");
}
[Fact]
public void InstanceClosure()
{
var source = @"
using System;
class Program
{
int w;
int A(int y)
{
int x = 1;
int Local1(int z)
{
int Local2()
{
return Local1(x + y + w);
}
return z != -1 ? z : Local2();
}
return Local1(-1);
}
static void Main(string[] args)
{
var prog = new Program();
prog.w = 3;
Console.WriteLine(prog.A(2));
}
}
";
VerifyOutput(source, "6");
}
[Fact]
public void SelfClosure()
{
var source = @"
using System;
class Program
{
static int Test()
{
int x = 2;
int Local1(int y)
{
int Local2()
{
return Local1(x);
}
return y != 0 ? y : Local2();
}
return Local1(0);
}
static void Main(string[] args)
{
Console.WriteLine(Test());
}
}
";
VerifyOutput(source, "2");
}
[Fact]
public void StructClosure()
{
var source = @"
int x = 2;
void Goo()
{
Console.Write(x);
}
Goo();
";
var verify = VerifyOutputInMain(source, "2", "System");
var goo = verify.FindLocalFunction("Goo");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.Equal(program, goo.ContainingType);
Assert.True(goo.IsStatic);
Assert.Equal(RefKind.Ref, goo.Parameters[0].RefKind);
Assert.True(goo.Parameters[0].Type.IsValueType);
}
[Fact]
public void StructClosureGeneric()
{
var source = @"
int x = 2;
void Goo<T1>()
{
int y = x;
void Bar<T2>()
{
Console.Write(x + y);
}
Bar<T1>();
}
Goo<int>();
";
var verify = VerifyOutputInMain(source, "4", "System");
var goo = verify.FindLocalFunction("Goo");
var bar = verify.FindLocalFunction("Bar");
Assert.Equal(1, goo.Parameters.Length);
Assert.Equal(2, bar.Parameters.Length);
Assert.Equal(RefKind.Ref, goo.Parameters[0].RefKind);
Assert.Equal(RefKind.Ref, bar.Parameters[0].RefKind);
Assert.Equal(RefKind.Ref, bar.Parameters[1].RefKind);
Assert.True(goo.Parameters[0].Type.IsValueType);
Assert.True(bar.Parameters[0].Type.IsValueType);
Assert.True(bar.Parameters[1].Type.IsValueType);
Assert.Equal(goo.Parameters[0].Type.OriginalDefinition, bar.Parameters[0].Type.OriginalDefinition);
var gooFrame = (INamedTypeSymbol)goo.Parameters[0].Type;
var barFrame = (INamedTypeSymbol)bar.Parameters[1].Type;
Assert.Equal(0, gooFrame.Arity);
Assert.Equal(1, barFrame.Arity);
}
[Fact]
public void ClosureOfStructClosure()
{
var source = @"
void Outer()
{
int a = 0;
void Middle()
{
int b = 0;
void Inner()
{
a++;
b++;
}
a++;
Inner();
}
Middle();
Console.WriteLine(a);
}
Outer();
";
var verify = VerifyOutputInMain(source, "2", "System");
var inner = verify.FindLocalFunction("Inner");
var middle = verify.FindLocalFunction("Middle");
var outer = verify.FindLocalFunction("Outer");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.Equal(program, inner.ContainingType);
Assert.Equal(program, middle.ContainingType);
Assert.Equal(program, outer.ContainingType);
Assert.True(inner.IsStatic);
Assert.True(middle.IsStatic);
Assert.True(outer.IsStatic);
Assert.Equal(2, inner.Parameters.Length);
Assert.Equal(1, middle.Parameters.Length);
Assert.Equal(0, outer.Parameters.Length);
Assert.Equal(RefKind.Ref, inner.Parameters[0].RefKind);
Assert.Equal(RefKind.Ref, inner.Parameters[1].RefKind);
Assert.Equal(RefKind.Ref, middle.Parameters[0].RefKind);
Assert.True(inner.Parameters[0].Type.IsValueType);
Assert.True(inner.Parameters[1].Type.IsValueType);
Assert.True(middle.Parameters[0].Type.IsValueType);
}
[Fact]
public void ThisClosureCallingOtherClosure()
{
var source = @"
using System;
class Program
{
int _x;
int Test()
{
int First()
{
return ++_x;
}
int Second()
{
return First();
}
return Second();
}
static void Main()
{
Console.Write(new Program() { _x = 1 }.Test());
}
}
";
var verify = VerifyOutput(source, "2");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.Equal(program, verify.FindLocalFunction("First").ContainingType);
Assert.Equal(program, verify.FindLocalFunction("Second").ContainingType);
}
[Fact]
public void RecursiveStructClosure()
{
var source = @"
int x = 0;
void Goo()
{
if (x != 2)
{
x++;
Goo();
}
else
{
Console.Write(x);
}
}
Goo();
";
var verify = VerifyOutputInMain(source, "2", "System");
var goo = verify.FindLocalFunction("Goo");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.Equal(program, goo.ContainingType);
Assert.True(goo.IsStatic);
Assert.Equal(RefKind.Ref, goo.Parameters[0].RefKind);
Assert.True(goo.Parameters[0].Type.IsValueType);
}
[Fact]
public void MutuallyRecursiveStructClosure()
{
var source = @"
int x = 0;
void Goo(int depth)
{
int dummy = 0;
void Bar(int depth2)
{
dummy++;
Goo(depth2);
}
if (depth != 2)
{
x++;
Bar(depth + 1);
}
else
{
Console.Write(x);
}
}
Goo(0);
";
var verify = VerifyOutputInMain(source, "2", "System");
var program = verify.Compilation.GetTypeByMetadataName("Program");
var goo = verify.FindLocalFunction("Goo");
var bar = verify.FindLocalFunction("Bar");
Assert.Equal(program, goo.ContainingType);
Assert.Equal(program, bar.ContainingType);
Assert.True(goo.IsStatic);
Assert.True(bar.IsStatic);
Assert.Equal(2, goo.Parameters.Length);
Assert.Equal(3, bar.Parameters.Length);
Assert.Equal(RefKind.Ref, goo.Parameters[1].RefKind);
Assert.Equal(RefKind.Ref, bar.Parameters[1].RefKind);
Assert.Equal(RefKind.Ref, bar.Parameters[2].RefKind);
Assert.True(goo.Parameters[1].Type.IsValueType);
Assert.True(bar.Parameters[1].Type.IsValueType);
Assert.True(bar.Parameters[2].Type.IsValueType);
}
[Fact]
public void Recursion()
{
var source = @"
void Goo(int depth)
{
if (depth > 10)
{
Console.WriteLine(2);
return;
}
Goo(depth + 1);
}
Goo(0);
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void MutualRecursion()
{
var source = @"
void Goo(int depth)
{
if (depth > 10)
{
Console.WriteLine(2);
return;
}
void Bar(int depth2)
{
Goo(depth2 + 1);
}
Bar(depth + 1);
}
Goo(0);
";
VerifyOutputInMain(source, "2", "System");
}
[Fact]
public void RecursionThisOnlyClosure()
{
var source = @"
using System;
class Program
{
int _x;
void Outer()
{
void Inner()
{
if (_x == 0)
{
return;
}
Console.Write(_x);
Console.Write(' ');
_x = 0;
Inner();
}
Inner();
}
public static void Main()
{
new Program() { _x = 2 }.Outer();
}
}
";
var verify = VerifyOutput(source, "2");
var program = verify.Compilation.GetTypeByMetadataName("Program");
Assert.Equal(program, verify.FindLocalFunction("Inner").ContainingType);
}
[Fact]
public void RecursionFrameCaptureTest()
{
// ensures that referring to a local function in an otherwise noncapturing Inner captures the frame of Outer.
var source = @"
int x = 0;
int Outer(bool isRecursive)
{
if (isRecursive)
{
return x;
}
x++;
int Middle()
{
int Inner()
{
return Outer(true);
}
return Inner();
}
return Middle();
}
Console.Write(Outer(false));
Console.Write(' ');
Console.Write(x);
";
VerifyOutputInMain(source, "1 1", "System");
}
[Fact]
[CompilerTrait(CompilerFeature.Iterator)]
public void IteratorBasic()
{
var source = @"
IEnumerable<int> Local()
{
yield return 2;
}
Console.Write(string.Join("","", Local()));
";
VerifyOutputInMain(source, "2", "System", "System.Collections.Generic");
}
[Fact]
[CompilerTrait(CompilerFeature.Iterator)]
public void IteratorGeneric()
{
var source = @"
IEnumerable<T> LocalGeneric<T>(T val)
{
yield return val;
}
Console.Write(string.Join("","", LocalGeneric(2)));
";
VerifyOutputInMain(source, "2", "System", "System.Collections.Generic");
}
[Fact]
[CompilerTrait(CompilerFeature.Iterator)]
public void IteratorNonGeneric()
{
var source = @"
IEnumerable LocalNongen()
{
yield return 2;
}
foreach (int x in LocalNongen())
{
Console.Write(x);
}
";
VerifyOutputInMain(source, "2", "System", "System.Collections");
}
[Fact]
[CompilerTrait(CompilerFeature.Iterator)]
public void IteratorEnumerator()
{
var source = @"
IEnumerator LocalEnumerator()
{
yield return 2;
}
var y = LocalEnumerator();
y.MoveNext();
Console.Write(y.Current);
";
VerifyOutputInMain(source, "2", "System", "System.Collections");
}
[Fact]
public void Generic()
{
var source = @"
using System;
class Program
{
// No closure. Return 'valu'.
static T A1<T>(T val)
{
T Local(T valu)
{
return valu;
}
return Local(val);
}
static int B1(int val)
{
T Local<T>(T valu)
{
return valu;
}
return Local(val);
}
static T1 C1<T1>(T1 val)
{
T2 Local<T2>(T2 valu)
{
return valu;
}
return Local<T1>(val);
}
// General closure. Return 'val'.
static T A2<T>(T val)
{
T Local(T valu)
{
return val;
}
return Local(val);
}
static int B2(int val)
{
T Local<T>(T valu)
{
return (T)(object)val;
}
return Local(val);
}
static T1 C2<T1>(T1 val)
{
T2 Local<T2>(T2 valu)
{
return (T2)(object)val;
}
return Local<T1>(val);
}
// This-only closure. Return 'field'.
int field = 2;
T A3<T>(T val)
{
T Local(T valu)
{
return (T)(object)field;
}
return Local(val);
}
int B3(int val)
{
T Local<T>(T valu)
{
return (T)(object)field;
}
return Local(val);
}
T1 C3<T1>(T1 val)
{
T2 Local<T2>(T2 valu)
{
return (T2)(object)field;
}
return Local<T1>(val);
}
static void Main(string[] args)
{
var program = new Program();
Console.WriteLine(Program.A1(2));
Console.WriteLine(Program.B1(2));
Console.WriteLine(Program.C1(2));
Console.WriteLine(Program.A2(2));
Console.WriteLine(Program.B2(2));
Console.WriteLine(Program.C2(2));
Console.WriteLine(program.A3(2));
Console.WriteLine(program.B3(2));
Console.WriteLine(program.C3(2));
}
}
";
var output = @"
2
2
2
2
2
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericConstraint()
{
var source = @"
using System;
class Program
{
static T A<T>(T val) where T : struct
{
T Local(T valu)
{
return valu;
}
return Local(val);
}
static int B(int val)
{
T Local<T>(T valu) where T : struct
{
return valu;
}
return Local(val);
}
static T1 C<T1>(T1 val) where T1 : struct
{
T2 Local<T2>(T2 valu) where T2 : struct
{
return valu;
}
return Local(val);
}
static object D(object val)
{
T Local<T>(T valu) where T : class
{
return valu;
}
return Local(val);
}
static void Main(string[] args)
{
Console.WriteLine(A(2));
Console.WriteLine(B(2));
Console.WriteLine(C(2));
Console.WriteLine(D(2));
}
}
";
var output = @"
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericTripleNestedNoClosure()
{
var source = @"
using System;
class Program
{
// Name of method is T[outer][middle][inner] where brackets are g=generic n=nongeneric
// One generic
static T1 Tgnn<T1>(T1 a)
{
T1 Local(T1 aa)
{
T1 Local2(T1 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static int Tngn(int a)
{
T1 Local<T1>(T1 aa)
{
T1 Local2(T1 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static int Tnng(int a)
{
int Local(int aa)
{
T1 Local2<T1>(T1 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
// Two generic
static T1 Tggn<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T2 Local2(T2 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static T1 Tgng<T1>(T1 a)
{
T1 Local(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static int Tngg(int a)
{
T1 Local<T1>(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
// Three generic
static T1 Tggg<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static void Main(string[] args)
{
Console.WriteLine(Program.Tgnn(2));
Console.WriteLine(Program.Tngn(2));
Console.WriteLine(Program.Tnng(2));
Console.WriteLine(Program.Tggn(2));
Console.WriteLine(Program.Tgng(2));
Console.WriteLine(Program.Tngg(2));
Console.WriteLine(Program.Tggg(2));
}
}
";
var output = @"
2
2
2
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericTripleNestedMiddleClosure()
{
var source = @"
using System;
class Program
{
// Name of method is T[outer][middle][inner] where brackets are g=generic n=nongeneric
// One generic
static T1 Tgnn<T1>(T1 a)
{
T1 Local(T1 aa)
{
T1 Local2(T1 aaa)
{
return (T1)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
static int Tngn(int a)
{
T1 Local<T1>(T1 aa)
{
T1 Local2(T1 aaa)
{
return (T1)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
static int Tnng(int a)
{
int Local(int aa)
{
T1 Local2<T1>(T1 aaa)
{
return (T1)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
// Two generic
static T1 Tggn<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T2 Local2(T2 aaa)
{
return (T2)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
static T1 Tgng<T1>(T1 a)
{
T1 Local(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return (T2)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
static int Tngg(int a)
{
T1 Local<T1>(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return (T2)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
// Three generic
static T1 Tggg<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
return (T3)(object)aa;
}
return Local2(aa);
}
return Local(a);
}
static void Main(string[] args)
{
Console.WriteLine(Program.Tgnn(2));
Console.WriteLine(Program.Tngn(2));
Console.WriteLine(Program.Tnng(2));
Console.WriteLine(Program.Tggn(2));
Console.WriteLine(Program.Tgng(2));
Console.WriteLine(Program.Tngg(2));
Console.WriteLine(Program.Tggg(2));
}
}
";
var output = @"
2
2
2
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericTripleNestedOuterClosure()
{
var source = @"
using System;
class Program
{
// Name of method is T[outer][middle][inner] where brackets are g=generic n=nongeneric
// One generic
static T1 Tgnn<T1>(T1 a)
{
T1 Local(T1 aa)
{
T1 Local2(T1 aaa)
{
return (T1)(object)a;
}
return Local2(aa);
}
return Local(a);
}
static int Tngn(int a)
{
T1 Local<T1>(T1 aa)
{
T1 Local2(T1 aaa)
{
return (T1)(object)a;
}
return Local2(aa);
}
return Local(a);
}
static int Tnng(int a)
{
int Local(int aa)
{
T1 Local2<T1>(T1 aaa)
{
return (T1)(object)a;
}
return Local2(aa);
}
return Local(a);
}
// Two generic
static T1 Tggn<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T2 Local2(T2 aaa)
{
return (T2)(object)a;
}
return Local2(aa);
}
return Local(a);
}
static T1 Tgng<T1>(T1 a)
{
T1 Local(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return (T2)(object)a;
}
return Local2(aa);
}
return Local(a);
}
static int Tngg(int a)
{
T1 Local<T1>(T1 aa)
{
T2 Local2<T2>(T2 aaa)
{
return (T2)(object)a;
}
return Local2(aa);
}
return Local(a);
}
// Three generic
static T1 Tggg<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
return (T3)(object)a;
}
return Local2(aa);
}
return Local(a);
}
static void Main(string[] args)
{
Console.WriteLine(Program.Tgnn(2));
Console.WriteLine(Program.Tngn(2));
Console.WriteLine(Program.Tnng(2));
Console.WriteLine(Program.Tggn(2));
Console.WriteLine(Program.Tgng(2));
Console.WriteLine(Program.Tngg(2));
Console.WriteLine(Program.Tggg(2));
}
}
";
var output = @"
2
2
2
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericTripleNestedNoClosureLambda()
{
var source = @"
using System;
class Program
{
// Name of method is T[outer][middle][inner] where brackets are g=generic n=nongeneric
// One generic
static T1 Tgnn<T1>(T1 a)
{
Func<T1, T1> Local = aa =>
{
Func<T1, T1> Local2 = aaa =>
{
return aaa;
};
return Local2(aa);
};
return Local(a);
}
static int Tngn(int a)
{
T1 Local<T1>(T1 aa)
{
Func<T1, T1> Local2 = aaa =>
{
return aaa;
};
return Local2(aa);
}
return Local(a);
}
static int Tnng(int a)
{
Func<int, int> Local = aa =>
{
T1 Local2<T1>(T1 aaa)
{
return aaa;
}
return Local2(aa);
};
return Local(a);
}
// Two generic
static T1 Tggn<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
Func<T2, T2> Local2 = aaa =>
{
return aaa;
};
return Local2(aa);
}
return Local(a);
}
static T1 Tgng<T1>(T1 a)
{
Func<T1, T1> Local = aa =>
{
T2 Local2<T2>(T2 aaa)
{
return aaa;
}
return Local2(aa);
};
return Local(a);
}
// Tngg and Tggg are impossible with lambdas
static void Main(string[] args)
{
Console.WriteLine(Program.Tgnn(2));
Console.WriteLine(Program.Tngn(2));
Console.WriteLine(Program.Tnng(2));
Console.WriteLine(Program.Tggn(2));
Console.WriteLine(Program.Tgng(2));
}
}
";
var output = @"
2
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
public void GenericUpperCall()
{
var source = @"
using System;
class Program
{
static T1 InnerToOuter<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
if ((object)aaa == null)
return InnerToOuter((T3)new object());
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static T1 InnerToMiddle<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
if ((object)aaa == null)
return InnerToMiddle((T3)new object());
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static T1 InnerToOuterScoping<T1>(T1 a)
{
T2 Local<T2>(T2 aa)
{
T3 Local2<T3>(T3 aaa)
{
if ((object)aaa == null)
return (T3)(object)InnerToOuter((T1)new object());
return aaa;
}
return Local2(aa);
}
return Local(a);
}
static T1 M1<T1>(T1 a)
{
T2 M2<T2>(T2 aa)
{
T2 x = aa;
T3 M3<T3>(T3 aaa)
{
T4 M4<T4>(T4 aaaa)
{
return (T4)(object)x;
}
return M4(aaa);
}
return M3(aa);
}
return M2(a);
}
static void Main(string[] args)
{
Console.WriteLine(Program.InnerToOuter((object)null));
Console.WriteLine(Program.InnerToMiddle((object)null));
Console.WriteLine(Program.InnerToOuterScoping((object)null));
Console.WriteLine(Program.M1(2));
}
}
";
var output = @"
System.Object
System.Object
System.Object
2
";
VerifyOutput(source, output);
}
[Fact]
public void CompoundOperatorExecutesOnce()
{
var source = @"
using System;
class Program
{
int _x = 2;
public static void Main()
{
var prog = new Program();
Program SideEffect()
{
Console.Write(prog._x);
return prog;
}
SideEffect()._x += 2;
Console.Write(' ');
SideEffect();
}
}
";
VerifyOutput(source, "2 4");
}
[Fact]
public void ConstValueDoesntMakeClosure()
{
var source = @"
const int x = 2;
void Local()
{
Console.Write(x);
}
Local();
";
// Should be a static method on "Program" itself, not a display class like "Program+<>c__DisplayClass0_0"
var verify = VerifyOutputInMain(source, "2", "System");
var goo = verify.FindLocalFunction("Local");
Assert.True(goo.IsStatic);
Assert.Equal(verify.Compilation.GetTypeByMetadataName("Program"), goo.ContainingType);
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicArgument()
{
var source = @"
using System;
class Program
{
static void Main()
{
int capture1 = 0;
void L1(int x) => Console.Write(x);
void L2(int x)
{
Console.Write(capture1);
Console.Write(x);
}
dynamic L4(int x)
{
Console.Write(capture1);
return x;
}
Action<int> L5(int x)
{
Console.Write(x);
return L1;
}
dynamic val = 2;
Console.WriteLine();
L1(val);
L2(val);
Console.WriteLine();
L2(L4(val));
L5(val)(val);
}
}
";
VerifyOutput(source, output: @"202
00222");
}
[Fact]
[WorkItem(21317, "https://github.com/dotnet/roslyn/issues/21317")]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicGenericArg()
{
var src = @"
void L1<T>(T x)
{
Console.WriteLine($""{x}: {typeof(T)}"");
}
dynamic val = 2;
L1<object>(val);
L1<int>(val);
L1<dynamic>(val);
L1<dynamic>(4);
void L2<T>(int x, T y) => Console.WriteLine($""{x}, {y}: {typeof(T)}"");
L2<float>(val, 3.0f);
List<dynamic> listOfDynamic = new List<dynamic> { 1, 2, 3 };
void L3<T>(List<T> x) => Console.WriteLine($""{string.Join("", "", x)}: {typeof(T)}"");
L3(listOfDynamic);
void L4<T>(T x, params int[] y) => Console.WriteLine($""{x}, {string.Join("", "", y)}: {typeof(T)}"");
L4<dynamic>(val, 3, 4);
L4<int>(val, 3, 4);
L4<int>(1, 3, val);
void L5<T>(int x, params T[] y) => Console.WriteLine($""{x}, {string.Join("", "", y)}: {typeof(T)}"");
L5<int>(val, 3, 4);
L5<int>(1, 3, val);
L5<dynamic>(1, 3, val);
";
var output = @"
2: System.Object
2: System.Int32
2: System.Object
4: System.Object
2, 3: System.Single
1, 2, 3: System.Object
2, 3, 4: System.Object
2, 3, 4: System.Int32
1, 3, 2: System.Int32
2, 3, 4: System.Int32
1, 3, 2: System.Int32
1, 3, 2: System.Object
";
VerifyOutputInMain(src, output, "System", "System.Collections.Generic");
}
[Fact]
[WorkItem(21317, "https://github.com/dotnet/roslyn/issues/21317")]
[CompilerTrait(CompilerFeature.Dynamic)]
public void DynamicGenericClassMethod()
{
var src = @"
using System;
class C1<T1>
{
public static void M1<T2>()
{
void F(int x)
{
Console.WriteLine($""C1<{typeof(T1)}>.M1<{typeof(T2)}>.F({x})"");
}
F((dynamic)2);
}
public static void M2()
{
void F(int x)
{
Console.WriteLine($""C1<{typeof(T1)}>.M2.F({x})"");
}
F((dynamic)2);
}
}
class C2
{
public static void M1<T2>()
{
void F(int x)
{
Console.WriteLine($""C2.M1<{typeof(T2)}>.F({x})"");
}
F((dynamic)2);
}
public static void M2()
{
void F(int x)
{
Console.WriteLine($""C2.M2.F({x})"");
}
F((dynamic)2);
}
}
class Program
{
static void Main()
{
C1<int>.M1<float>();
C1<int>.M2();
C2.M1<float>();
C2.M2();
}
}
";
var output = @"
C1<System.Int32>.M1<System.Single>.F(2)
C1<System.Int32>.M2.F(2)
C2.M1<System.Single>.F(2)
C2.M2.F(2)
";
VerifyOutput(src, output);
}
[Fact]
[CompilerTrait(CompilerFeature.Dynamic, CompilerFeature.Params)]
public void DynamicArgsAndParams()
{
var src = @"
int capture1 = 0;
void L1(int x, params int[] ys)
{
Console.Write(capture1);
Console.Write(x);
foreach (var y in ys)
{
Console.Write(y);
}
}
dynamic val = 2;
int val2 = 3;
L1(val, val2);
L1(val);
L1(val, val, val);
";
VerifyOutputInMain(src, "023020222", "System");
}
[Fact]
public void Basic()
{
var source = @"
async Task<int> Local()
{
return await Task.FromResult(2);
}
Console.Write(Local().Result);
";
VerifyOutputInMain(source, "2", "System", "System.Threading.Tasks");
}
[Fact]
public void Param()
{
var source = @"
async Task<int> LocalParam(int x)
{
return await Task.FromResult(x);
}
Console.Write(LocalParam(2).Result);
";
VerifyOutputInMain(source, "2", "System", "System.Threading.Tasks");
}
[Fact]
[CompilerTrait(CompilerFeature.Async)]
public void GenericAsync()
{
var source = @"
async Task<T> LocalGeneric<T>(T x)
{
return await Task.FromResult(x);
}
Console.Write(LocalGeneric(2).Result);
";
VerifyOutputInMain(source, "2", "System", "System.Threading.Tasks");
}
[Fact]
[CompilerTrait(CompilerFeature.Async)]
public void Void()
{
var source = @"
// had bug with parser where 'async [keyword]' didn't parse.
async void LocalVoid()
{
Console.Write(2);
await Task.Yield();
}
LocalVoid();
";
VerifyOutputInMain(source, "2", "System", "System.Threading.Tasks");
}
[Fact]
[CompilerTrait(CompilerFeature.Async)]
public void AwaitAwait()
{
var source = @"
Task<int> Fun(int x)
{
return Task.FromResult(x);
}
async Task<int> AwaitAwait()
{
var a = Fun(2);
await Fun(await a);
return await Fun(await a);
}
Console.WriteLine(AwaitAwait().Result);
";
VerifyOutputInMain(source, "2", "System", "System.Threading.Tasks");
}
[Fact]
[CompilerTrait(CompilerFeature.Async)]
public void Keyword()
{
var source = @"
using System;
struct async
{
public override string ToString() => ""2"";
}
struct await
{
public override string ToString() => ""2"";
}
class Program
{
static string A()
{
async async()
{
return new async();
}
return async().ToString();
}
static string B()
{
string async()
{
return ""2"";
}
return async();
}
static string C()
{
async Goo()
{
return new async();
}
return Goo().ToString();
}
static string D()
{
await Fun(await x)
{
return x;
}
return Fun(new await()).ToString();
}
static void Main(string[] args)
{
Console.WriteLine(A());
Console.WriteLine(B());
Console.WriteLine(C());
Console.WriteLine(D());
}
}
";
var output = @"
2
2
2
2
";
VerifyOutput(source, output);
}
[Fact]
[CompilerTrait(CompilerFeature.Async)]
public void UnsafeKeyword()
{
var source = @"
using System;
using System.Threading.Tasks;
class Program
{
static string A()
{
async unsafe Task<int> async()
{
return 2;
}
return async().Result.ToString();
}
static string B()
{
unsafe async Task<int> async()
{
return 2;
}
return async().Result.ToString();
}
static void Main(string[] args)
{
Console.WriteLine(A());
Console.WriteLine(B());
}
}
";
var output = @"
2
2
";
VerifyOutput(source, output, TestOptions.ReleaseExe.WithAllowUnsafe(true).WithWarningLevel(0), verify: Verification.Passes);
}
[Fact]
public void UnsafeBasic()
{
var source = @"
using System;
class Program
{
static void A()
{
unsafe void Local()
{
int x = 2;
Console.Write(*&x);
}
Local();
}
static void Main(string[] args)
{
A();
}
}
";
VerifyOutput(source, "2", TestOptions.ReleaseExe.WithAllowUnsafe(true), verify: Verification.Fails);
}
[Fact]
public void UnsafeParameter()
{
var source = @"
using System;
class Program
{
static unsafe void B()
{
int x = 2;
unsafe void Local(int* y)
{
Console.Write(*y);
}
Local(&x);
}
static void Main(string[] args)
{
B();
}
}
";
VerifyOutput(source, "2", TestOptions.ReleaseExe.WithAllowUnsafe(true), verify: Verification.Fails);
}
[Fact]
public void UnsafeClosure()
{
var source = @"
using System;
class Program
{
static unsafe void C()
{
int y = 2;
int* x = &y;
unsafe void Local()
{
Console.Write(*x);
}
Local();
}
static void Main(string[] args)
{
C();
}
}
";
VerifyOutput(source, "2", TestOptions.ReleaseExe.WithAllowUnsafe(true), verify: Verification.Fails);
}
[Fact]
public void UnsafeCalls()
{
var src = @"
using System;
class C
{
public static void Main(string[] args)
{
int x = 2;
int y = 0;
unsafe void Local(ref int x2)
{
fixed (int* ptr = &x2)
{
Local2(ptr);
}
}
unsafe int* Local2(int* ptr)
{
(*ptr)++;
y++;
return null;
}
while (x < 10)
{
Local(ref x);
x++;
}
Console.WriteLine(x);
Console.WriteLine(y);
}
}";
VerifyOutput(src, $"10{Environment.NewLine}4", TestOptions.ReleaseExe.WithAllowUnsafe(true), verify: Verification.Fails);
}
[Fact]
[WorkItem(15322, "https://github.com/dotnet/roslyn/issues/15322")]
public void UseBeforeDeclaration()
{
var src = @"
Assign();
Local();
int x;
void Local() => System.Console.WriteLine(x);
void Assign() { x = 5; }";
VerifyOutputInMain(src, "5");
}
[Fact]
[WorkItem(15558, "https://github.com/dotnet/roslyn/issues/15558")]
public void CapturingSharesVar()
{
var src = @"
int i = 0;
int oldi<T>()
where T : struct
=> (i += @sizeof<T>()) - @sizeof<T>();
int @sizeof<T>()
where T : struct
=> typeof(T).IsAssignableFrom(typeof(long))
? sizeof(long)
: 1;
while (i < 10)
System.Console.WriteLine(oldi<byte>());";
VerifyOutputInMain(src, @"0
1
2
3
4
5
6
7
8
9");
}
[Fact]
[WorkItem(15599, "https://github.com/dotnet/roslyn/issues/15599")]
public void NestedLocalFuncCapture()
{
var src = @"
using System;
public class C {
int instance = 11;
public void M() {
int M() => instance;
{
int local = 11;
bool M2() => local == M();
Console.WriteLine(M2());
}
}
public static void Main() => new C().M();
}";
VerifyOutput(src, "True");
}
[Fact]
[WorkItem(15599, "https://github.com/dotnet/roslyn/issues/15599")]
public void NestedLocalFuncCapture2()
{
var src = @"
using System;
public class C {
int instance = 0b1;
public void M() {
int var1 = 0b10;
int M() => var1 + instance;
{
int local = 0b100;
int M2() => local + M();
Console.WriteLine(M2());
}
}
public static void Main() => new C().M();
}";
VerifyOutput(src, "7");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction()
{
var src = @"
void Local<T>(T t, int count)
{
if (count > 0)
{
Console.Write(t);
Local(t, count - 1);
}
}
Local(""A"", 5);
";
VerifyOutputInMain(src, "AAAAA", "System");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction2()
{
var src = @"
void Local<T>(T t, int count)
{
if (count > 0)
{
Console.Write(t);
var action = new Action<T, int>(Local);
action(t, count - 1);
}
}
Local(""A"", 5);
";
VerifyOutputInMain(src, "AAAAA", "System");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction3()
{
var src = @"
void Local<T>(T t, int count)
{
if (count > 0)
{
Console.Write(t);
var action = (Action<T, int>)Local;
action(t, count - 1);
}
}
Local(""A"", 5);
";
VerifyOutputInMain(src, "AAAAA", "System");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction4()
{
var src = @"
using System;
class C
{
public static void M<T>(T t)
{
void Local<U>(U u, int count)
{
if (count > 0)
{
Console.Write(t);
Console.Write(u);
Local(u, count - 1);
}
}
Local(""A"", 5);
}
public static void Main()
{
C.M(""B"");
}
}";
VerifyOutput(src, "BABABABABA");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction5()
{
var src = @"
using System;
class C<T1>
{
T1 t1;
public C(T1 t1)
{
this.t1 = t1;
}
public void M<T2>(T2 t2)
{
void L1<T3>(T3 t3)
{
void L2<T4>(T4 t4)
{
void L3<U>(U u, int count)
{
if (count > 0)
{
Console.Write(t1);
Console.Write(t2);
Console.Write(t3);
Console.Write(t4);
Console.Write(u);
L3(u, count - 1);
}
}
L3(""A"", 5);
}
L2(""B"");
}
L1(""C"");
}
}
class Program
{
public static void Main()
{
var c = new C<string>(""D"");
c.M(""E"");
}
}";
VerifyOutput(src, "DECBADECBADECBADECBADECBA");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction6()
{
var src = @"
using System;
class C<T1>
{
T1 t1;
public C(T1 t1)
{
this.t1 = t1;
}
public void M<T2>(T2 t2)
{
void L1<T3>(T3 t3)
{
void L2<T4>(T4 t4)
{
void L3<U>(U u, int count)
{
if (count > 0)
{
Console.Write(t1);
Console.Write(t2);
Console.Write(t3);
Console.Write(t4);
Console.Write(u);
var a = new Action<U, int>(L3);
a(u, count - 1);
}
}
var b = new Action<string, int>(L3);
b(""A"", 5);
}
var c = new Action<string>(L2);
c(""B"");
}
var d = new Action<string>(L1);
d(""C"");
}
}
class Program
{
public static void Main()
{
var c = new C<string>(""D"");
c.M(""E"");
}
}";
VerifyOutput(src, "DECBADECBADECBADECBADECBA");
}
[Fact]
[WorkItem(15751, "https://github.com/dotnet/roslyn/issues/15751")]
public void RecursiveGenericLocalFunction7()
{
var src = @"
using System;
class C<T1>
{
T1 t1;
public C(T1 t1)
{
this.t1 = t1;
}
public void M<T2>(T2 t2)
{
void L1<T3>(T3 t3)
{
void L2<T4>(T4 t4)
{
void L3<U>(U u, int count)
{
if (count > 0)
{
Console.Write(t1);
Console.Write(t2);
Console.Write(t3);
Console.Write(t4);
Console.Write(u);
var a = (Action<U, int>)(L3);
a(u, count - 1);
}
}
var b = (Action<string, int>)(L3);
b(""A"", 5);
}
var c = (Action<string>)(L2);
c(""B"");
}
var d = (Action<string>)(L1);
d(""C"");
}
}
class Program
{
public static void Main()
{
var c = new C<string>(""D"");
c.M(""E"");
}
}";
VerifyOutput(src, "DECBADECBADECBADECBADECBA");
}
[Fact]
[WorkItem(16038, "https://github.com/dotnet/roslyn/issues/16038")]
public void RecursiveGenericLocalFunction8()
{
var src = @"
using System;
class C<T0>
{
T0 t0;
public C(T0 t0)
{
this.t0 = t0;
}
public void M<T1>(T1 t1)
{
(T0, T1, T2) L1<T2>(T2 t2)
{
(T0, T1, T2, T3) L2<T3>(T3 t3, int count)
{
if (count > 0)
{
Console.Write(t0);
Console.Write(t1);
Console.Write(t2);
Console.Write(t3);
return L2(t3, count - 1);
}
return (t0, t1, t2, t3);
}
var (t4, t5, t6, t7) = L2(""A"", 5);
return (t4, t5, t6);
}
L1(""B"");
}
}
class Program
{
public static void Main()
{
var c = new C<string>(""C"");
c.M(""D"");
}
}";
CompileAndVerify(src, expectedOutput: "CDBACDBACDBACDBACDBA");
}
[Fact]
[WorkItem(19119, "https://github.com/dotnet/roslyn/issues/19119")]
public void StructFrameInitUnnecessary()
{
var c = CompileAndVerify(@"
class Program
{
static void Main(string[] args)
{
int q = 1;
if (q > 0)
{
int w = 2;
if (w > 0)
{
int e = 3;
if (e > 0)
{
void Print() => System.Console.WriteLine(q + w + e);
Print();
}
}
}
}
}", expectedOutput: "6");
//NOTE: the following code should not have "initobj" instructions.
c.VerifyIL("Program.Main", @"
{
// Code size 63 (0x3f)
.maxstack 3
.locals init (Program.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0
Program.<>c__DisplayClass0_1 V_1, //CS$<>8__locals1
Program.<>c__DisplayClass0_2 V_2) //CS$<>8__locals2
IL_0000: ldloca.s V_0
IL_0002: ldc.i4.1
IL_0003: stfld ""int Program.<>c__DisplayClass0_0.q""
IL_0008: ldloc.0
IL_0009: ldfld ""int Program.<>c__DisplayClass0_0.q""
IL_000e: ldc.i4.0
IL_000f: ble.s IL_003e
IL_0011: ldloca.s V_1
IL_0013: ldc.i4.2
IL_0014: stfld ""int Program.<>c__DisplayClass0_1.w""
IL_0019: ldloc.1
IL_001a: ldfld ""int Program.<>c__DisplayClass0_1.w""
IL_001f: ldc.i4.0
IL_0020: ble.s IL_003e
IL_0022: ldloca.s V_2
IL_0024: ldc.i4.3
IL_0025: stfld ""int Program.<>c__DisplayClass0_2.e""
IL_002a: ldloc.2
IL_002b: ldfld ""int Program.<>c__DisplayClass0_2.e""
IL_0030: ldc.i4.0
IL_0031: ble.s IL_003e
IL_0033: ldloca.s V_0
IL_0035: ldloca.s V_1
IL_0037: ldloca.s V_2
IL_0039: call ""void Program.<Main>g__Print|0_0(ref Program.<>c__DisplayClass0_0, ref Program.<>c__DisplayClass0_1, ref Program.<>c__DisplayClass0_2)""
IL_003e: ret
}
");
}
[Fact]
public void LocalFunctionAttribute()
{
var source = @"
class A : System.Attribute { }
class C
{
public void M()
{
[A]
void local1()
{
}
[return: A]
void local2()
{
}
void local3([A] int i)
{
}
void local4<[A] T>()
{
}
}
}
";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal(
expected: new[] { "CompilerGeneratedAttribute", "A" },
actual: GetAttributeNames(attrs1));
var localFn2 = cClass.GetMethod("<M>g__local2|0_1");
var attrs2 = localFn2.GetReturnTypeAttributes();
Assert.Equal("A", attrs2.Single().AttributeClass.Name);
var localFn3 = cClass.GetMethod("<M>g__local3|0_2");
var attrs3 = localFn3.GetParameters().Single().GetAttributes();
Assert.Equal("A", attrs3.Single().AttributeClass.Name);
var localFn4 = cClass.GetMethod("<M>g__local4|0_3");
var attrs4 = localFn4.TypeParameters.Single().GetAttributes();
Assert.Equal("A", attrs4.Single().AttributeClass.Name);
}
}
[Fact]
public void LocalFunctionAttribute_Complex()
{
var source = @"
class A1 : System.Attribute { }
class A2 : System.Attribute { internal A2(int i, string s) { } }
class A3 : System.Attribute { internal A3(params int[] values) { } }
class C
{
public void M()
{
[A1, A2(1, ""hello"")]
[A3(1, 2, 3, 4, 5)]
void local1()
{
}
}
}
";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs = localFn1.GetAttributes();
Assert.Equal(
expected: new[] { "CompilerGeneratedAttribute", "A1", "A2", "A3" },
actual: GetAttributeNames(attrs));
Assert.Empty(attrs[0].ConstructorArguments);
Assert.Empty(attrs[1].ConstructorArguments);
Assert.Equal(new object[] { 1, "hello" }, attrs[2].ConstructorArguments.Select(a => a.Value));
var attr3Args = attrs[3].ConstructorArguments.Single().Values;
Assert.Equal(new object[] { 1, 2, 3, 4, 5 }, attr3Args.Select(a => a.Value));
}
}
[Fact]
public void LocalFunctionAttributeArgument()
{
var source = @"
class A : System.Attribute { internal A(int i) { } }
class C
{
public void M()
{
[A(42)]
void local1()
{
}
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal(
expected: new[] { "CompilerGeneratedAttribute", "A" },
actual: GetAttributeNames(attrs1));
var arg = attrs1[1].ConstructorArguments.Single();
Assert.Equal(42, arg.Value);
}
}
[Fact]
public void LocalFunction_EmitNullableAttribute()
{
var source = @"
#nullable enable
class C
{
public void M()
{
string? local1(string? s) => s;
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
AssertEx.Equal(new[] { "NullableContextAttribute", "CompilerGeneratedAttribute" }, attrs1.Select(a => a.AttributeClass.Name));
Assert.Empty(localFn1.GetReturnTypeAttributes());
Assert.Equal(NullableAnnotation.Annotated, localFn1.ReturnTypeWithAnnotations.NullableAnnotation);
var param = localFn1.Parameters.Single();
Assert.Empty(param.GetAttributes());
Assert.Equal(NullableAnnotation.Annotated, param.TypeWithAnnotations.NullableAnnotation);
}
}
[Fact]
public void LocalFunctionDynamicAttribute()
{
var source = @"
class C
{
public void M()
{
dynamic local1(dynamic d) => d;
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal("CompilerGeneratedAttribute", attrs1.Single().AttributeClass.Name);
Assert.Equal("DynamicAttribute", localFn1.GetReturnTypeAttributes().Single().AttributeClass.Name);
var param = localFn1.Parameters.Single();
Assert.Equal("DynamicAttribute", param.GetAttributes().Single().AttributeClass.Name);
}
}
[Fact]
public void LocalFunctionParamsArray_NoParamArrayAttribute()
{
var source = @"
class C
{
void M()
{
#pragma warning disable 8321
void local1(params int[] arr) { }
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal("CompilerGeneratedAttribute", attrs1.Single().AttributeClass.Name);
Assert.Empty(localFn1.GetReturnTypeAttributes());
var param = localFn1.Parameters.Single();
Assert.Empty(param.GetAttributes());
}
}
[Fact]
public void LocalFunction_ConditionalAttributeDisallowed()
{
var source = @"
using System.Diagnostics;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[Conditional(""DEBUG"")] // 1
void local1() { }
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (9,10): error CS8764: Local function 'local1()' must be 'static' in order to use the Conditional attribute
// [Conditional("DEBUG")] // 1
Diagnostic(ErrorCode.ERR_ConditionalOnLocalFunction, @"Conditional(""DEBUG"")").WithArguments("local1()").WithLocation(9, 10));
}
[Fact]
public void StaticLocalFunction_ConditionalAttribute_Errors()
{
var source = @"
using System.Diagnostics;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[Conditional(""hello world"")] // 1
static void local1() { }
[Conditional(""DEBUG"")] // 2
static int local2()
{
return 42;
}
[Conditional(""DEBUG"")] // 3
static void local3(out string s)
{
s = ""hello"";
}
}
}
";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (9,22): error CS0633: The argument to the 'Conditional' attribute must be a valid identifier
// [Conditional("hello world")] // 1
Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""hello world""").WithArguments("Conditional").WithLocation(9, 22),
// (12,10): error CS0578: The Conditional attribute is not valid on 'local2()' because its return type is not void
// [Conditional("DEBUG")] // 2
Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"Conditional(""DEBUG"")").WithArguments("local2()").WithLocation(12, 10),
// (18,10): error CS0685: Conditional member 'local3(out string)' cannot have an out parameter
// [Conditional("DEBUG")] // 3
Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""DEBUG"")").WithArguments("local3(out string)").WithLocation(18, 10));
}
[Fact]
public void StaticLocalFunction_ConditionalAttribute()
{
var source = @"
using System.Diagnostics;
using System;
class C
{
static void Main()
{
local1();
[Conditional(""DEBUG"")]
static void local1()
{
Console.Write(""hello"");
}
}
}
";
CompileAndVerify(
source,
options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9.WithPreprocessorSymbols("DEBUG"),
symbolValidator: validate,
expectedOutput: "hello");
CompileAndVerify(
source,
options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate,
expectedOutput: "");
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<Main>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal(new[] { "CompilerGeneratedAttribute", "ConditionalAttribute" }, GetAttributeNames(attrs1));
}
}
[Fact]
public void StaticLocalFunction_ConditionalAttribute_NoUnreferencedWarning()
{
var source = @"
using System.Diagnostics;
using System;
class C
{
static void Main()
{
local1();
[Conditional(""DEBUG"")]
static void local1()
{
Console.Write(""hello"");
}
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics();
CreateCompilation(source, parseOptions: TestOptions.Regular9.WithPreprocessorSymbols("DEBUG")).VerifyDiagnostics();
}
[Fact]
public void StaticLocalFunction_IfDirective_Unreferenced()
{
var source = @"
using System;
class C
{
static void Main()
{
#if DEBUG
local1();
#endif
static void local1()
{
Console.Write(""hello"");
}
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics(
// (11,21): warning CS8321: The local function 'local1' is declared but never used
// static void local1() // 1
Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local1").WithArguments("local1").WithLocation(11, 21));
CreateCompilation(source, parseOptions: TestOptions.Regular9.WithPreprocessorSymbols("DEBUG")).VerifyDiagnostics();
}
[Fact]
public void LocalFunction_AttributeMarkedConditional()
{
var source = @"
using System.Diagnostics;
using System;
[Conditional(""DEBUG"")]
class Attr : Attribute { }
class C
{
void M()
{
#pragma warning disable 8321
[Attr]
[return: Attr]
T local1<[Attr] T>([Attr] T t) => t;
}
}
";
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9.WithPreprocessorSymbols("DEBUG"),
symbolValidator: validate1);
CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate2);
static void validate1(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal(new[] { "CompilerGeneratedAttribute", "Attr" }, GetAttributeNames(attrs1));
Assert.Equal(new[] { "Attr" }, GetAttributeNames(localFn1.GetReturnTypeAttributes()));
Assert.Equal(new[] { "Attr" }, GetAttributeNames(localFn1.TypeParameters.Single().GetAttributes()));
Assert.Equal(new[] { "Attr" }, GetAttributeNames(localFn1.Parameters.Single().GetAttributes()));
}
static void validate2(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes();
Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(attrs1));
Assert.Empty(localFn1.GetReturnTypeAttributes());
Assert.Empty(localFn1.TypeParameters.Single().GetAttributes());
Assert.Empty(localFn1.Parameters.Single().GetAttributes());
}
}
[ConditionalFact(typeof(DesktopOnly))]
public void LocalFunctionAttribute_TypeIL()
{
var source = @"
class A : System.Attribute { internal A(int i) { } }
class C
{
public void M()
{
[A(42)]
void local1()
{
}
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9);
verifier.VerifyTypeIL("C", @"
.class private auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig
instance void M () cil managed
{
// Method begins at RVA 0x205a
// Code size 3 (0x3)
.maxstack 8
IL_0000: nop
IL_0001: nop
IL_0002: ret
} // end of method C::M
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x205e
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: nop
IL_0007: ret
} // end of method C::.ctor
.method assembly hidebysig static
void '<M>g__local1|0_0' () cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
01 00 00 00
)
.custom instance void A::.ctor(int32) = (
01 00 2a 00 00 00 00 00
)
// Method begins at RVA 0x2067
// Code size 2 (0x2)
.maxstack 8
IL_0000: nop
IL_0001: ret
} // end of method C::'<M>g__local1|0_0'
} // end of class C");
}
[Fact]
public void ExternLocalFunction()
{
var source = @"
using System.Runtime.InteropServices;
class C
{
public void M()
{
local1();
[DllImport(""something.dll"")]
static extern void local1();
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate,
verify: Verification.Skipped);
var comp = verifier.Compilation;
var syntaxTree = comp.SyntaxTrees.Single();
var semanticModel = comp.GetSemanticModel(syntaxTree);
var localFunction = semanticModel
.GetDeclaredSymbol(syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single())
.GetSymbol<LocalFunctionSymbol>();
Assert.Equal(new[] { "DllImportAttribute" }, GetAttributeNames(localFunction.GetAttributes()));
validateLocalFunction(localFunction);
void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes().As<CSharpAttributeData>();
Assert.Equal(
expected: new[] { "CompilerGeneratedAttribute" },
actual: GetAttributeNames(attrs1));
validateLocalFunction(localFn1);
}
static void validateLocalFunction(MethodSymbol localFunction)
{
Assert.True(localFunction.IsExtern);
var importData = localFunction.GetDllImportData();
Assert.NotNull(importData);
Assert.Equal("something.dll", importData.ModuleName);
Assert.Equal("local1", importData.EntryPointName);
Assert.Equal(CharSet.None, importData.CharacterSet);
Assert.False(importData.SetLastError);
Assert.False(importData.ExactSpelling);
Assert.Equal(MethodImplAttributes.PreserveSig, localFunction.ImplementationAttributes);
Assert.Equal(CallingConvention.Winapi, importData.CallingConvention);
Assert.Null(importData.BestFitMapping);
Assert.Null(importData.ThrowOnUnmappableCharacter);
}
}
[Fact]
public void ExternLocalFunction_ComplexDllImport()
{
var source = @"
using System.Runtime.InteropServices;
class C
{
public void M()
{
local1();
[DllImport(
""something.dll"",
EntryPoint = ""a"",
CharSet = CharSet.Ansi,
SetLastError = true,
ExactSpelling = true,
PreserveSig = false,
CallingConvention = CallingConvention.Cdecl,
BestFitMapping = false,
ThrowOnUnmappableChar = true)]
static extern void local1();
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate,
verify: Verification.Skipped);
var comp = verifier.Compilation;
var syntaxTree = comp.SyntaxTrees.Single();
var semanticModel = comp.GetSemanticModel(syntaxTree);
var localFunction = semanticModel
.GetDeclaredSymbol(syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single())
.GetSymbol<LocalFunctionSymbol>();
Assert.Equal(new[] { "DllImportAttribute" }, GetAttributeNames(localFunction.GetAttributes()));
validateLocalFunction(localFunction);
void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
var attrs1 = localFn1.GetAttributes().As<CSharpAttributeData>();
Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(attrs1));
validateLocalFunction(localFn1);
}
static void validateLocalFunction(MethodSymbol localFunction)
{
Assert.True(localFunction.IsExtern);
var importData = localFunction.GetDllImportData();
Assert.NotNull(importData);
Assert.Equal("something.dll", importData.ModuleName);
Assert.Equal("a", importData.EntryPointName);
Assert.Equal(CharSet.Ansi, importData.CharacterSet);
Assert.True(importData.SetLastError);
Assert.True(importData.ExactSpelling);
Assert.Equal(MethodImplAttributes.IL, localFunction.ImplementationAttributes);
Assert.Equal(CallingConvention.Cdecl, importData.CallingConvention);
Assert.False(importData.BestFitMapping);
Assert.True(importData.ThrowOnUnmappableCharacter);
}
}
[Fact]
public void LocalFunction_MethodImpl()
{
var source = @"
using System.Runtime.CompilerServices;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[MethodImpl(MethodImplOptions.ForwardRef)]
static void forwardRef() { System.Console.WriteLine(0); }
[MethodImpl(MethodImplOptions.NoInlining)]
static void noInlining() { System.Console.WriteLine(1); }
[MethodImpl(MethodImplOptions.NoOptimization)]
static void noOptimization() { System.Console.WriteLine(2); }
[MethodImpl(MethodImplOptions.Synchronized)]
static void synchronized() { System.Console.WriteLine(3); }
[MethodImpl(MethodImplOptions.InternalCall)]
extern static void internalCallStatic();
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
assemblyValidator: validateAssembly,
verify: Verification.Skipped);
var comp = verifier.Compilation;
var syntaxTree = comp.SyntaxTrees.Single();
var semanticModel = comp.GetSemanticModel(syntaxTree);
var localFunctions = syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToList();
checkImplAttributes(localFunctions[0], MethodImplAttributes.ForwardRef);
checkImplAttributes(localFunctions[1], MethodImplAttributes.NoInlining);
checkImplAttributes(localFunctions[2], MethodImplAttributes.NoOptimization);
checkImplAttributes(localFunctions[3], MethodImplAttributes.Synchronized);
checkImplAttributes(localFunctions[4], MethodImplAttributes.InternalCall);
void checkImplAttributes(LocalFunctionStatementSyntax localFunctionStatement, MethodImplAttributes expectedFlags)
{
var localFunction = semanticModel.GetDeclaredSymbol(localFunctionStatement).GetSymbol<LocalFunctionSymbol>();
Assert.Equal(expectedFlags, localFunction.ImplementationAttributes);
}
void validateAssembly(PEAssembly assembly)
{
var peReader = assembly.GetMetadataReader();
foreach (var methodHandle in peReader.MethodDefinitions)
{
var methodDef = peReader.GetMethodDefinition(methodHandle);
var actualFlags = methodDef.ImplAttributes;
var methodName = peReader.GetString(methodDef.Name);
var expectedFlags = methodName switch
{
"<M>g__forwardRef|0_0" => MethodImplAttributes.ForwardRef,
"<M>g__noInlining|0_1" => MethodImplAttributes.NoInlining,
"<M>g__noOptimization|0_2" => MethodImplAttributes.NoOptimization,
"<M>g__synchronized|0_3" => MethodImplAttributes.Synchronized,
"<M>g__internalCallStatic|0_4" => MethodImplAttributes.InternalCall,
".ctor" => MethodImplAttributes.IL,
"M" => MethodImplAttributes.IL,
_ => throw TestExceptionUtilities.UnexpectedValue(methodName)
};
Assert.Equal(expectedFlags, actualFlags);
}
}
}
[Fact]
public void LocalFunction_SpecialName()
{
var source = @"
using System.Runtime.CompilerServices;
class C
{
void M()
{
#pragma warning disable 8321 // Unreferenced local function
[SpecialName]
void local1() { }
}
}
";
var verifier = CompileAndVerify(
source,
options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All),
parseOptions: TestOptions.Regular9,
symbolValidator: validate);
static void validate(ModuleSymbol module)
{
var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var localFn1 = cClass.GetMethod("<M>g__local1|0_0");
Assert.True(localFn1.HasSpecialName);
}
}
[Fact]
[WorkItem(49599, "https://github.com/dotnet/roslyn/issues/49599")]
public void MultipleLocalFunctionsUsingDynamic_01()
{
var source = @"
public class Program
{
static void Main()
{
Local1<object>();
Local1<object>();
static void Local1<T>()
{
System.Console.Write(Local2(Local3()));
static string Local2(dynamic n) => n.ToString();
}
static int Local3() => (int)(dynamic)4;
}
}
";
CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: "44");
}
[Fact]
[WorkItem(49599, "https://github.com/dotnet/roslyn/issues/49599")]
public void MultipleLocalFunctionsUsingDynamic_02()
{
var source = @"
public class Program
{
static void Main()
{
Local1<object>();
Local1<object>();
static void Local1<T>()
{
System.Console.Write(Local2(Local3<object>()));
static string Local2(dynamic n) => n.ToString();
}
static int Local3<S>() => (int)(dynamic)4;
}
}
";
CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: "44");
}
[Fact]
[WorkItem(49599, "https://github.com/dotnet/roslyn/issues/49599")]
public void MultipleLocalFunctionsUsingDynamic_03()
{
var source = @"
public class Program
{
static void Main()
{
Local1<object>();
Local1<object>();
static void Local1<T>()
{
System.Console.Write(Local2<object>(Local3<object>()));
static string Local2<U>(dynamic n) => n.ToString();
}
static int Local3<S>() => (int)(dynamic)4;
}
}
";
CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: "44");
}
[Fact]
[WorkItem(49599, "https://github.com/dotnet/roslyn/issues/49599")]
public void MultipleLocalFunctionsUsingDynamic_04()
{
var source = @"
public class Program
{
static void Main()
{
Local1<object>();
Local1<object>();
static void Local1<T>()
{
System.Console.Write(Local1<object>(Local3<object>()));
static string Local1<U>(dynamic n) => n.ToString();
}
static int Local3<S>() => (int)(dynamic)4;
}
}
";
CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: "44");
}
[Fact]
[WorkItem(49599, "https://github.com/dotnet/roslyn/issues/49599")]
public void MultipleLocalFunctionsUsingDynamic_05()
{
var source = @"
public class Program
{
static void Main()
{
Local1<object>();
Local1<object>();
static void Local1<T>()
{
System.Console.Write(Local2<object>(Local3<object>()));
static string Local2<U>(dynamic n) => n.ToString();
}
static int Local2<S>() => (int)(dynamic)4;
static int Local3<S>() => (int)(dynamic)4;
}
}
";
CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, expectedOutput: "44");
}
internal CompilationVerifier VerifyOutput(string source, string output, CSharpCompilationOptions options, Verification verify = Verification.Passes)
{
var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: options);
return CompileAndVerify(comp, expectedOutput: output, verify: verify).VerifyDiagnostics(); // no diagnostics
}
internal CompilationVerifier VerifyOutput(string source, string output)
{
var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe);
return CompileAndVerify(comp, expectedOutput: output).VerifyDiagnostics(); // no diagnostics
}
internal CompilationVerifier VerifyOutputInMain(string methodBody, string output, params string[] usings)
{
for (var i = 0; i < usings.Length; i++)
{
usings[i] = "using " + usings[i] + ";";
}
var usingBlock = string.Join(Environment.NewLine, usings);
var source = usingBlock + @"
class Program
{
static void Main()
{
" + methodBody + @"
}
}";
return VerifyOutput(source, output);
}
}
}
| 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/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/EEConstructorSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
/// <summary>
/// Synthesized expression evaluation method.
/// </summary>
internal sealed class EEConstructorSymbol : SynthesizedInstanceConstructor
{
internal EEConstructorSymbol(NamedTypeSymbol containingType)
: base(containingType)
{
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
{
var noLocals = ImmutableArray<LocalSymbol>.Empty;
var initializerInvocation = MethodCompiler.BindImplicitConstructorInitializer(this, diagnostics, compilationState.Compilation);
var syntax = initializerInvocation.Syntax;
compilationState.AddSynthesizedMethod(this,
new BoundBlock(
syntax,
noLocals,
ImmutableArray.Create<BoundStatement>(
new BoundExpressionStatement(syntax, initializerInvocation),
new BoundReturnStatement(syntax, RefKind.None, null))));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
/// <summary>
/// Synthesized expression evaluation method.
/// </summary>
internal sealed class EEConstructorSymbol : SynthesizedInstanceConstructor
{
internal EEConstructorSymbol(NamedTypeSymbol containingType)
: base(containingType)
{
}
internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics)
{
var noLocals = ImmutableArray<LocalSymbol>.Empty;
var initializerInvocation = MethodCompiler.BindImplicitConstructorInitializer(this, diagnostics, compilationState.Compilation);
var syntax = initializerInvocation.Syntax;
compilationState.AddSynthesizedMethod(this,
new BoundBlock(
syntax,
noLocals,
ImmutableArray.Create<BoundStatement>(
new BoundExpressionStatement(syntax, initializerInvocation),
new BoundReturnStatement(syntax, RefKind.None, null))));
}
}
}
| -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/ExtractMethod/VariableStyle.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal class VariableStyle
{
public ParameterStyle ParameterStyle { get; private set; }
public ReturnStyle ReturnStyle { get; private set; }
public static readonly VariableStyle None =
new VariableStyle() { ParameterStyle = ParameterStyle.None, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle InputOnly =
new VariableStyle() { ParameterStyle = ParameterStyle.InputOnly, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle Delete =
new VariableStyle() { ParameterStyle = ParameterStyle.Delete, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle MoveOut =
new VariableStyle() { ParameterStyle = ParameterStyle.MoveOut, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle SplitOut =
new VariableStyle() { ParameterStyle = ParameterStyle.SplitOut, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle MoveIn =
new VariableStyle() { ParameterStyle = ParameterStyle.MoveIn, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle SplitIn =
new VariableStyle() { ParameterStyle = ParameterStyle.SplitIn, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle NotUsed =
new VariableStyle() { ParameterStyle = ParameterStyle.MoveOut, ReturnStyle = ReturnStyle.Initialization };
public static readonly VariableStyle Ref =
new VariableStyle() { ParameterStyle = ParameterStyle.Ref, ReturnStyle = ReturnStyle.AssignmentWithInput };
public static readonly VariableStyle OnlyAsRefParam =
new VariableStyle() { ParameterStyle = ParameterStyle.Ref, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle Out =
new VariableStyle() { ParameterStyle = ParameterStyle.Out, ReturnStyle = ReturnStyle.AssignmentWithNoInput };
public static readonly VariableStyle OutWithErrorInput =
new VariableStyle() { ParameterStyle = ParameterStyle.Out, ReturnStyle = ReturnStyle.AssignmentWithInput };
public static readonly VariableStyle OutWithMoveOut =
new VariableStyle() { ParameterStyle = ParameterStyle.OutWithMoveOut, ReturnStyle = ReturnStyle.Initialization };
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal class VariableStyle
{
public ParameterStyle ParameterStyle { get; private set; }
public ReturnStyle ReturnStyle { get; private set; }
public static readonly VariableStyle None =
new VariableStyle() { ParameterStyle = ParameterStyle.None, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle InputOnly =
new VariableStyle() { ParameterStyle = ParameterStyle.InputOnly, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle Delete =
new VariableStyle() { ParameterStyle = ParameterStyle.Delete, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle MoveOut =
new VariableStyle() { ParameterStyle = ParameterStyle.MoveOut, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle SplitOut =
new VariableStyle() { ParameterStyle = ParameterStyle.SplitOut, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle MoveIn =
new VariableStyle() { ParameterStyle = ParameterStyle.MoveIn, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle SplitIn =
new VariableStyle() { ParameterStyle = ParameterStyle.SplitIn, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle NotUsed =
new VariableStyle() { ParameterStyle = ParameterStyle.MoveOut, ReturnStyle = ReturnStyle.Initialization };
public static readonly VariableStyle Ref =
new VariableStyle() { ParameterStyle = ParameterStyle.Ref, ReturnStyle = ReturnStyle.AssignmentWithInput };
public static readonly VariableStyle OnlyAsRefParam =
new VariableStyle() { ParameterStyle = ParameterStyle.Ref, ReturnStyle = ReturnStyle.None };
public static readonly VariableStyle Out =
new VariableStyle() { ParameterStyle = ParameterStyle.Out, ReturnStyle = ReturnStyle.AssignmentWithNoInput };
public static readonly VariableStyle OutWithErrorInput =
new VariableStyle() { ParameterStyle = ParameterStyle.Out, ReturnStyle = ReturnStyle.AssignmentWithInput };
public static readonly VariableStyle OutWithMoveOut =
new VariableStyle() { ParameterStyle = ParameterStyle.OutWithMoveOut, ReturnStyle = ReturnStyle.Initialization };
}
}
| -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/VenusMargin/ProjectionBufferViewModel.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.ObjectModel;
using Microsoft.VisualStudio.Text;
namespace Roslyn.Hosting.Diagnostics.VenusMargin
{
public class ProjectionBufferViewModel
{
public ObservableCollection<ITextBuffer> SourceBuffers { get; }
public ObservableCollection<SnapshotSpan> SourceSpans { get; }
public ProjectionBufferViewModel()
{
SourceBuffers = new ObservableCollection<ITextBuffer>();
SourceSpans = new ObservableCollection<SnapshotSpan>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.ObjectModel;
using Microsoft.VisualStudio.Text;
namespace Roslyn.Hosting.Diagnostics.VenusMargin
{
public class ProjectionBufferViewModel
{
public ObservableCollection<ITextBuffer> SourceBuffers { get; }
public ObservableCollection<SnapshotSpan> SourceSpans { get; }
public ProjectionBufferViewModel()
{
SourceBuffers = new ObservableCollection<ITextBuffer>();
SourceSpans = new ObservableCollection<SnapshotSpan>();
}
}
}
| -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/EditorAdapter/TextSpanExtensionsTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Roslyn.Test.EditorUtilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorAdapter
{
[UseExportProvider]
public class TextSpanExtensionsTest
{
[Fact]
public void ConvertToSpan()
{
static void del(int start, int length)
{
var textSpan = new TextSpan(start, length);
var span = textSpan.ToSpan();
Assert.Equal(start, span.Start);
Assert.Equal(length, span.Length);
}
del(0, 5);
del(15, 20);
}
[Fact]
public void ConvertToSnapshotSpan1()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var snapshot = EditorFactory.CreateBuffer(exportProvider, new string('a', 10)).CurrentSnapshot;
var textSpan = new TextSpan(0, 5);
var ss = textSpan.ToSnapshotSpan(snapshot);
Assert.Same(snapshot, ss.Snapshot);
Assert.Equal(0, ss.Start);
Assert.Equal(5, ss.Length);
}
[Fact]
public void ConvertToSnapshotSpan2()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var snapshot = EditorFactory.CreateBuffer(exportProvider, new string('a', 10)).CurrentSnapshot;
var textSpan = new TextSpan(0, 10);
var ss = textSpan.ToSnapshotSpan(snapshot);
Assert.Same(snapshot, ss.Snapshot);
Assert.Equal(0, ss.Start);
Assert.Equal(10, ss.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 Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Roslyn.Test.EditorUtilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorAdapter
{
[UseExportProvider]
public class TextSpanExtensionsTest
{
[Fact]
public void ConvertToSpan()
{
static void del(int start, int length)
{
var textSpan = new TextSpan(start, length);
var span = textSpan.ToSpan();
Assert.Equal(start, span.Start);
Assert.Equal(length, span.Length);
}
del(0, 5);
del(15, 20);
}
[Fact]
public void ConvertToSnapshotSpan1()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var snapshot = EditorFactory.CreateBuffer(exportProvider, new string('a', 10)).CurrentSnapshot;
var textSpan = new TextSpan(0, 5);
var ss = textSpan.ToSnapshotSpan(snapshot);
Assert.Same(snapshot, ss.Snapshot);
Assert.Equal(0, ss.Start);
Assert.Equal(5, ss.Length);
}
[Fact]
public void ConvertToSnapshotSpan2()
{
var exportProvider = EditorTestCompositions.EditorFeatures.ExportProviderFactory.CreateExportProvider();
var snapshot = EditorFactory.CreateBuffer(exportProvider, new string('a', 10)).CurrentSnapshot;
var textSpan = new TextSpan(0, 10);
var ss = textSpan.ToSnapshotSpan(snapshot);
Assert.Same(snapshot, ss.Snapshot);
Assert.Equal(0, ss.Start);
Assert.Equal(10, ss.Length);
}
}
}
| -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/Shared/Utilities/ThreadingContextTaskSchedulerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
[ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Editor), Shared]
internal sealed class ThreadingContextTaskSchedulerProvider : ITaskSchedulerProvider
{
public TaskScheduler CurrentContextScheduler { get; }
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ThreadingContextTaskSchedulerProvider(IThreadingContext threadingContext)
{
CurrentContextScheduler = threadingContext.HasMainThread
? new JoinableTaskFactoryTaskScheduler(threadingContext.JoinableTaskFactory)
: TaskScheduler.Default;
}
private sealed class JoinableTaskFactoryTaskScheduler : TaskScheduler
{
private readonly JoinableTaskFactory _joinableTaskFactory;
public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory)
=> _joinableTaskFactory = joinableTaskFactory;
public override int MaximumConcurrencyLevel => 1;
protected override IEnumerable<Task> GetScheduledTasks()
=> SpecializedCollections.EmptyEnumerable<Task>();
protected override void QueueTask(Task task)
{
_joinableTaskFactory.RunAsync(async () =>
{
await _joinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
TryExecuteTask(task);
});
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (_joinableTaskFactory.Context.IsOnMainThread)
{
return TryExecuteTask(task);
}
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.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
[ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Editor), Shared]
internal sealed class ThreadingContextTaskSchedulerProvider : ITaskSchedulerProvider
{
public TaskScheduler CurrentContextScheduler { get; }
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ThreadingContextTaskSchedulerProvider(IThreadingContext threadingContext)
{
CurrentContextScheduler = threadingContext.HasMainThread
? new JoinableTaskFactoryTaskScheduler(threadingContext.JoinableTaskFactory)
: TaskScheduler.Default;
}
private sealed class JoinableTaskFactoryTaskScheduler : TaskScheduler
{
private readonly JoinableTaskFactory _joinableTaskFactory;
public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory)
=> _joinableTaskFactory = joinableTaskFactory;
public override int MaximumConcurrencyLevel => 1;
protected override IEnumerable<Task> GetScheduledTasks()
=> SpecializedCollections.EmptyEnumerable<Task>();
protected override void QueueTask(Task task)
{
_joinableTaskFactory.RunAsync(async () =>
{
await _joinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
TryExecuteTask(task);
});
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (_joinableTaskFactory.Context.IsOnMainThread)
{
return TryExecuteTask(task);
}
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/VisualStudio/Core/Def/Implementation/UnusedReferences/Dialog/UnusedReferencesTableProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.UnusedReferences;
using Microsoft.Internal.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog
{
[Export(typeof(UnusedReferencesTableProvider))]
internal partial class UnusedReferencesTableProvider
{
private readonly ITableManager _tableManager;
private readonly IWpfTableControlProvider _tableControlProvider;
private readonly UnusedReferencesDataSource _dataSource;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UnusedReferencesTableProvider(
ITableManagerProvider tableMangerProvider,
IWpfTableControlProvider tableControlProvider)
{
_tableManager = tableMangerProvider.GetTableManager(UnusedReferencesDataSource.Name);
_tableControlProvider = tableControlProvider;
_dataSource = new UnusedReferencesDataSource();
_tableManager.AddSource(_dataSource, UnusedReferencesColumnDefinitions.ColumnNames);
}
public IWpfTableControl4 CreateTableControl()
{
var tableControl = (IWpfTableControl4)_tableControlProvider.CreateControl(
_tableManager,
autoSubscribe: true,
BuildColumnStates(),
UnusedReferencesColumnDefinitions.ColumnNames.ToArray());
tableControl.ShowGroupingLine = true;
tableControl.DoColumnsAutoAdjust = true;
tableControl.DoSortingAndGroupingWhileUnstable = true;
return tableControl;
static ImmutableArray<ColumnState> BuildColumnStates()
{
return ImmutableArray.Create(
new ColumnState2(UnusedReferencesColumnDefinitions.SolutionName, isVisible: false, width: 200, sortPriority: 0, descendingSort: false, groupingPriority: 1),
new ColumnState2(UnusedReferencesColumnDefinitions.ProjectName, isVisible: false, width: 200, sortPriority: 1, descendingSort: false, groupingPriority: 2),
new ColumnState2(UnusedReferencesColumnDefinitions.ReferenceType, isVisible: false, width: 200, sortPriority: 2, descendingSort: false, groupingPriority: 3),
new ColumnState(UnusedReferencesColumnDefinitions.ReferenceName, isVisible: true, width: 300, sortPriority: 3, descendingSort: false),
new ColumnState(UnusedReferencesColumnDefinitions.UpdateAction, isVisible: true, width: 100, sortPriority: 4, descendingSort: false));
}
}
public void AddTableData(Solution solution, string projectFilePath, ImmutableArray<ReferenceUpdate> referenceUpdates)
{
_dataSource.AddTableData(solution, projectFilePath, referenceUpdates);
}
public void ClearTableData()
{
_dataSource.RemoveAllTableData();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.UnusedReferences;
using Microsoft.Internal.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog
{
[Export(typeof(UnusedReferencesTableProvider))]
internal partial class UnusedReferencesTableProvider
{
private readonly ITableManager _tableManager;
private readonly IWpfTableControlProvider _tableControlProvider;
private readonly UnusedReferencesDataSource _dataSource;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UnusedReferencesTableProvider(
ITableManagerProvider tableMangerProvider,
IWpfTableControlProvider tableControlProvider)
{
_tableManager = tableMangerProvider.GetTableManager(UnusedReferencesDataSource.Name);
_tableControlProvider = tableControlProvider;
_dataSource = new UnusedReferencesDataSource();
_tableManager.AddSource(_dataSource, UnusedReferencesColumnDefinitions.ColumnNames);
}
public IWpfTableControl4 CreateTableControl()
{
var tableControl = (IWpfTableControl4)_tableControlProvider.CreateControl(
_tableManager,
autoSubscribe: true,
BuildColumnStates(),
UnusedReferencesColumnDefinitions.ColumnNames.ToArray());
tableControl.ShowGroupingLine = true;
tableControl.DoColumnsAutoAdjust = true;
tableControl.DoSortingAndGroupingWhileUnstable = true;
return tableControl;
static ImmutableArray<ColumnState> BuildColumnStates()
{
return ImmutableArray.Create(
new ColumnState2(UnusedReferencesColumnDefinitions.SolutionName, isVisible: false, width: 200, sortPriority: 0, descendingSort: false, groupingPriority: 1),
new ColumnState2(UnusedReferencesColumnDefinitions.ProjectName, isVisible: false, width: 200, sortPriority: 1, descendingSort: false, groupingPriority: 2),
new ColumnState2(UnusedReferencesColumnDefinitions.ReferenceType, isVisible: false, width: 200, sortPriority: 2, descendingSort: false, groupingPriority: 3),
new ColumnState(UnusedReferencesColumnDefinitions.ReferenceName, isVisible: true, width: 300, sortPriority: 3, descendingSort: false),
new ColumnState(UnusedReferencesColumnDefinitions.UpdateAction, isVisible: true, width: 100, sortPriority: 4, descendingSort: false));
}
}
public void AddTableData(Solution solution, string projectFilePath, ImmutableArray<ReferenceUpdate> referenceUpdates)
{
_dataSource.AddTableData(solution, projectFilePath, referenceUpdates);
}
public void ClearTableData()
{
_dataSource.RemoveAllTableData();
}
}
}
| -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/Debugging/CSharpProximityExpressionsService_ExpressionTermCollector.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Debugging
{
internal partial class CSharpProximityExpressionsService
{
private static string ConvertToString(ExpressionSyntax expression)
{
var converted = expression.ConvertToSingleLine();
return converted.ToString();
}
private static void AddExpressionTerms(ExpressionSyntax expression, IList<string> terms)
{
// Check here rather than at all the call sites...
if (expression == null)
{
return;
}
// Collect terms from this expression, which returns flags indicating the validity
// of this expression as a whole.
var expressionType = ExpressionType.Invalid;
AddSubExpressionTerms(expression, terms, ref expressionType);
AddIfValidTerm(expression, expressionType, terms);
}
private static void AddIfValidTerm(ExpressionSyntax expression, ExpressionType type, IList<string> terms)
{
if (IsValidTerm(type))
{
// If this expression identified itself as a valid term, add it to the
// term table
terms.Add(ConvertToString(expression));
}
}
private static bool IsValidTerm(ExpressionType type)
=> (type & ExpressionType.ValidTerm) == ExpressionType.ValidTerm;
private static bool IsValidExpression(ExpressionType type)
=> (type & ExpressionType.ValidExpression) == ExpressionType.ValidExpression;
private static void AddSubExpressionTerms(ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType)
{
// Check here rather than at all the call sites...
if (expression == null)
{
return;
}
switch (expression.Kind())
{
case SyntaxKind.ThisExpression:
case SyntaxKind.BaseExpression:
// an op term is ok if it's a "this" or "base" op it allows us to see
// "this.goo" in the autos window note: it's not a VALIDTERM since we don't
// want "this" showing up in the auto's window twice.
expressionType = ExpressionType.ValidExpression;
return;
case SyntaxKind.IdentifierName:
// Name nodes are always valid terms
expressionType = ExpressionType.ValidTerm;
return;
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.NullLiteralExpression:
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
// Constants can make up a valid term, but we don't consider them valid
// terms themselves (since we don't want them to show up in the autos window
// on their own).
expressionType = ExpressionType.ValidExpression;
return;
case SyntaxKind.CastExpression:
AddCastExpressionTerms((CastExpressionSyntax)expression, terms, ref expressionType);
return;
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
AddMemberAccessExpressionTerms((MemberAccessExpressionSyntax)expression, terms, ref expressionType);
return;
case SyntaxKind.ObjectCreationExpression:
AddObjectCreationExpressionTerms((ObjectCreationExpressionSyntax)expression, terms, ref expressionType);
return;
case SyntaxKind.ArrayCreationExpression:
AddArrayCreationExpressionTerms((ArrayCreationExpressionSyntax)expression, terms, ref expressionType);
return;
case SyntaxKind.InvocationExpression:
AddInvocationExpressionTerms((InvocationExpressionSyntax)expression, terms, ref expressionType);
return;
}
// +, -, ++, --, !, etc.
//
// This is a valid expression if it doesn't have obvious side effects (i.e. ++, --)
if (expression is PrefixUnaryExpressionSyntax prefixUnary)
{
AddPrefixUnaryExpressionTerms(prefixUnary, terms, ref expressionType);
return;
}
if (expression is AwaitExpressionSyntax awaitExpression)
{
AddAwaitExpressionTerms(awaitExpression, terms, ref expressionType);
return;
}
if (expression is PostfixUnaryExpressionSyntax postfixExpression)
{
AddPostfixUnaryExpressionTerms(postfixExpression, terms, ref expressionType);
return;
}
if (expression is BinaryExpressionSyntax binaryExpression)
{
AddBinaryExpressionTerms(expression, binaryExpression.Left, binaryExpression.Right, terms, ref expressionType);
return;
}
if (expression is AssignmentExpressionSyntax assignmentExpression)
{
AddBinaryExpressionTerms(expression, assignmentExpression.Left, assignmentExpression.Right, terms, ref expressionType);
return;
}
if (expression is ConditionalExpressionSyntax conditional)
{
AddConditionalExpressionTerms(conditional, terms, ref expressionType);
return;
}
if (expression is ParenthesizedExpressionSyntax parenthesizedExpression)
{
AddSubExpressionTerms(parenthesizedExpression.Expression, terms, ref expressionType);
}
expressionType = ExpressionType.Invalid;
}
private static void AddCastExpressionTerms(CastExpressionSyntax castExpression, IList<string> terms, ref ExpressionType expressionType)
{
// For a cast, just add the nested expression. Note: this is technically
// unsafe as the cast *may* have side effects. However, in practice this is
// extremely rare, so we allow for this since it's ok in the common case.
var flags = ExpressionType.Invalid;
// Ask our subexpression for terms
AddSubExpressionTerms(castExpression.Expression, terms, ref flags);
// Is our expression a valid term?
AddIfValidTerm(castExpression.Expression, flags, terms);
// If the subexpression is a valid term, so is the cast expression
expressionType = flags;
}
private static void AddMemberAccessExpressionTerms(MemberAccessExpressionSyntax memberAccessExpression, IList<string> terms, ref ExpressionType expressionType)
{
var flags = ExpressionType.Invalid;
// These operators always have a RHS of a name node, which we know would
// "claim" to be a valid term, but is not valid without the LHS present.
// So, we don't bother collecting anything from the RHS...
AddSubExpressionTerms(memberAccessExpression.Expression, terms, ref flags);
// If the LHS says it's a valid term, then we add it ONLY if our PARENT
// is NOT another dot/arrow. This allows the expression 'a.b.c.d' to
// add both 'a.b.c.d' and 'a.b.c', but not 'a.b' and 'a'.
if (IsValidTerm(flags) &&
!memberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) &&
!memberAccessExpression.IsParentKind(SyntaxKind.PointerMemberAccessExpression))
{
terms.Add(ConvertToString(memberAccessExpression.Expression));
}
// And this expression itself is a valid term if the LHS is a valid
// expression, and its PARENT is not an invocation.
if (IsValidExpression(flags) &&
!memberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression))
{
expressionType = ExpressionType.ValidTerm;
}
else
{
expressionType = ExpressionType.ValidExpression;
}
}
private static void AddObjectCreationExpressionTerms(ObjectCreationExpressionSyntax objectionCreationExpression, IList<string> terms, ref ExpressionType expressionType)
{
// Object creation can *definitely* cause side effects. So we initially
// mark this as something invalid. We allow it as a valid expr if all
// the sub arguments are valid terms.
expressionType = ExpressionType.Invalid;
if (objectionCreationExpression.ArgumentList != null)
{
var flags = ExpressionType.Invalid;
AddArgumentTerms(objectionCreationExpression.ArgumentList, terms, ref flags);
// If all arguments are terms, then this is possibly a valid expr that can be used
// somewhere higher in the stack.
if (IsValidTerm(flags))
{
expressionType = ExpressionType.ValidExpression;
}
}
}
private static void AddArrayCreationExpressionTerms(
ArrayCreationExpressionSyntax arrayCreationExpression,
IList<string> terms,
ref ExpressionType expressionType)
{
var validTerm = true;
if (arrayCreationExpression.Initializer != null)
{
var flags = ExpressionType.Invalid;
arrayCreationExpression.Initializer.Expressions.Do(e => AddSubExpressionTerms(e, terms, ref flags));
validTerm &= IsValidTerm(flags);
}
if (validTerm)
{
expressionType = ExpressionType.ValidExpression;
}
else
{
expressionType = ExpressionType.Invalid;
}
}
private static void AddInvocationExpressionTerms(InvocationExpressionSyntax invocationExpression, IList<string> terms, ref ExpressionType expressionType)
{
#pragma warning disable IDE0059 // Unnecessary assignment of a value
// Invocations definitely have side effects. So we assume this
// is invalid initially;
expressionType = ExpressionType.Invalid;
#pragma warning restore IDE0059 // Unnecessary assignment of a value
ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid;
AddSubExpressionTerms(invocationExpression.Expression, terms, ref leftFlags);
AddArgumentTerms(invocationExpression.ArgumentList, terms, ref rightFlags);
AddIfValidTerm(invocationExpression.Expression, leftFlags, terms);
// We're valid if both children are...
expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression;
}
private static void AddPrefixUnaryExpressionTerms(PrefixUnaryExpressionSyntax prefixUnaryExpression, IList<string> terms, ref ExpressionType expressionType)
{
expressionType = ExpressionType.Invalid;
var flags = ExpressionType.Invalid;
// Ask our subexpression for terms
AddSubExpressionTerms(prefixUnaryExpression.Operand, terms, ref flags);
// Is our expression a valid term?
AddIfValidTerm(prefixUnaryExpression.Operand, flags, terms);
if (prefixUnaryExpression.IsKind(SyntaxKind.LogicalNotExpression, SyntaxKind.BitwiseNotExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.UnaryPlusExpression))
{
// We're a valid expression if our subexpression is...
expressionType = flags & ExpressionType.ValidExpression;
}
}
private static void AddAwaitExpressionTerms(AwaitExpressionSyntax awaitExpression, IList<string> terms, ref ExpressionType expressionType)
{
expressionType = ExpressionType.Invalid;
var flags = ExpressionType.Invalid;
// Ask our subexpression for terms
AddSubExpressionTerms(awaitExpression.Expression, terms, ref flags);
// Is our expression a valid term?
AddIfValidTerm(awaitExpression.Expression, flags, terms);
}
private static void AddPostfixUnaryExpressionTerms(PostfixUnaryExpressionSyntax postfixUnaryExpression, IList<string> terms, ref ExpressionType expressionType)
{
// ++ and -- are the only postfix operators. Since they always have side
// effects, we never consider this an expression.
expressionType = ExpressionType.Invalid;
var flags = ExpressionType.Invalid;
// Ask our subexpression for terms
AddSubExpressionTerms(postfixUnaryExpression.Operand, terms, ref flags);
// Is our expression a valid term?
AddIfValidTerm(postfixUnaryExpression.Operand, flags, terms);
}
private static void AddConditionalExpressionTerms(ConditionalExpressionSyntax conditionalExpression, IList<string> terms, ref ExpressionType expressionType)
{
ExpressionType conditionFlags = ExpressionType.Invalid, trueFlags = ExpressionType.Invalid, falseFlags = ExpressionType.Invalid;
AddSubExpressionTerms(conditionalExpression.Condition, terms, ref conditionFlags);
AddSubExpressionTerms(conditionalExpression.WhenTrue, terms, ref trueFlags);
AddSubExpressionTerms(conditionalExpression.WhenFalse, terms, ref falseFlags);
AddIfValidTerm(conditionalExpression.Condition, conditionFlags, terms);
AddIfValidTerm(conditionalExpression.WhenTrue, trueFlags, terms);
AddIfValidTerm(conditionalExpression.WhenFalse, falseFlags, terms);
// We're valid if all children are...
expressionType = (conditionFlags & trueFlags & falseFlags) & ExpressionType.ValidExpression;
}
private static void AddBinaryExpressionTerms(ExpressionSyntax binaryExpression, ExpressionSyntax left, ExpressionSyntax right, IList<string> terms, ref ExpressionType expressionType)
{
ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid;
AddSubExpressionTerms(left, terms, ref leftFlags);
AddSubExpressionTerms(right, terms, ref rightFlags);
if (IsValidTerm(leftFlags))
{
terms.Add(ConvertToString(left));
}
if (IsValidTerm(rightFlags))
{
terms.Add(ConvertToString(right));
}
// Many sorts of binops (like +=) will definitely have side effects. We only
// consider this valid if it's a simple expression like +, -, etc.
switch (binaryExpression.Kind())
{
case SyntaxKind.AddExpression:
case SyntaxKind.SubtractExpression:
case SyntaxKind.MultiplyExpression:
case SyntaxKind.DivideExpression:
case SyntaxKind.ModuloExpression:
case SyntaxKind.LeftShiftExpression:
case SyntaxKind.RightShiftExpression:
case SyntaxKind.LogicalOrExpression:
case SyntaxKind.LogicalAndExpression:
case SyntaxKind.BitwiseOrExpression:
case SyntaxKind.BitwiseAndExpression:
case SyntaxKind.ExclusiveOrExpression:
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
case SyntaxKind.LessThanExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.IsExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.CoalesceExpression:
// We're valid if both children are...
expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression;
return;
default:
expressionType = ExpressionType.Invalid;
return;
}
}
private static void AddArgumentTerms(ArgumentListSyntax argumentList, IList<string> terms, ref ExpressionType expressionType)
{
var validExpr = true;
var validTerm = true;
// Process the list of expressions. This is probably a list of
// arguments to a function call(or a list of array index expressions)
foreach (var arg in argumentList.Arguments)
{
var flags = ExpressionType.Invalid;
AddSubExpressionTerms(arg.Expression, terms, ref flags);
if (IsValidTerm(flags))
{
terms.Add(ConvertToString(arg.Expression));
}
validExpr &= IsValidExpression(flags);
validTerm &= IsValidTerm(flags);
}
// We're never a valid term if all arguments were valid terms. If not, we're a valid
// expression if all arguments where. Otherwise, we're just invalid.
expressionType = validTerm
? ExpressionType.ValidTerm
: validExpr
? ExpressionType.ValidExpression : ExpressionType.Invalid;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Debugging
{
internal partial class CSharpProximityExpressionsService
{
private static string ConvertToString(ExpressionSyntax expression)
{
var converted = expression.ConvertToSingleLine();
return converted.ToString();
}
private static void AddExpressionTerms(ExpressionSyntax expression, IList<string> terms)
{
// Check here rather than at all the call sites...
if (expression == null)
{
return;
}
// Collect terms from this expression, which returns flags indicating the validity
// of this expression as a whole.
var expressionType = ExpressionType.Invalid;
AddSubExpressionTerms(expression, terms, ref expressionType);
AddIfValidTerm(expression, expressionType, terms);
}
private static void AddIfValidTerm(ExpressionSyntax expression, ExpressionType type, IList<string> terms)
{
if (IsValidTerm(type))
{
// If this expression identified itself as a valid term, add it to the
// term table
terms.Add(ConvertToString(expression));
}
}
private static bool IsValidTerm(ExpressionType type)
=> (type & ExpressionType.ValidTerm) == ExpressionType.ValidTerm;
private static bool IsValidExpression(ExpressionType type)
=> (type & ExpressionType.ValidExpression) == ExpressionType.ValidExpression;
private static void AddSubExpressionTerms(ExpressionSyntax expression, IList<string> terms, ref ExpressionType expressionType)
{
// Check here rather than at all the call sites...
if (expression == null)
{
return;
}
switch (expression.Kind())
{
case SyntaxKind.ThisExpression:
case SyntaxKind.BaseExpression:
// an op term is ok if it's a "this" or "base" op it allows us to see
// "this.goo" in the autos window note: it's not a VALIDTERM since we don't
// want "this" showing up in the auto's window twice.
expressionType = ExpressionType.ValidExpression;
return;
case SyntaxKind.IdentifierName:
// Name nodes are always valid terms
expressionType = ExpressionType.ValidTerm;
return;
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.NullLiteralExpression:
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
// Constants can make up a valid term, but we don't consider them valid
// terms themselves (since we don't want them to show up in the autos window
// on their own).
expressionType = ExpressionType.ValidExpression;
return;
case SyntaxKind.CastExpression:
AddCastExpressionTerms((CastExpressionSyntax)expression, terms, ref expressionType);
return;
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
AddMemberAccessExpressionTerms((MemberAccessExpressionSyntax)expression, terms, ref expressionType);
return;
case SyntaxKind.ObjectCreationExpression:
AddObjectCreationExpressionTerms((ObjectCreationExpressionSyntax)expression, terms, ref expressionType);
return;
case SyntaxKind.ArrayCreationExpression:
AddArrayCreationExpressionTerms((ArrayCreationExpressionSyntax)expression, terms, ref expressionType);
return;
case SyntaxKind.InvocationExpression:
AddInvocationExpressionTerms((InvocationExpressionSyntax)expression, terms, ref expressionType);
return;
}
// +, -, ++, --, !, etc.
//
// This is a valid expression if it doesn't have obvious side effects (i.e. ++, --)
if (expression is PrefixUnaryExpressionSyntax prefixUnary)
{
AddPrefixUnaryExpressionTerms(prefixUnary, terms, ref expressionType);
return;
}
if (expression is AwaitExpressionSyntax awaitExpression)
{
AddAwaitExpressionTerms(awaitExpression, terms, ref expressionType);
return;
}
if (expression is PostfixUnaryExpressionSyntax postfixExpression)
{
AddPostfixUnaryExpressionTerms(postfixExpression, terms, ref expressionType);
return;
}
if (expression is BinaryExpressionSyntax binaryExpression)
{
AddBinaryExpressionTerms(expression, binaryExpression.Left, binaryExpression.Right, terms, ref expressionType);
return;
}
if (expression is AssignmentExpressionSyntax assignmentExpression)
{
AddBinaryExpressionTerms(expression, assignmentExpression.Left, assignmentExpression.Right, terms, ref expressionType);
return;
}
if (expression is ConditionalExpressionSyntax conditional)
{
AddConditionalExpressionTerms(conditional, terms, ref expressionType);
return;
}
if (expression is ParenthesizedExpressionSyntax parenthesizedExpression)
{
AddSubExpressionTerms(parenthesizedExpression.Expression, terms, ref expressionType);
}
expressionType = ExpressionType.Invalid;
}
private static void AddCastExpressionTerms(CastExpressionSyntax castExpression, IList<string> terms, ref ExpressionType expressionType)
{
// For a cast, just add the nested expression. Note: this is technically
// unsafe as the cast *may* have side effects. However, in practice this is
// extremely rare, so we allow for this since it's ok in the common case.
var flags = ExpressionType.Invalid;
// Ask our subexpression for terms
AddSubExpressionTerms(castExpression.Expression, terms, ref flags);
// Is our expression a valid term?
AddIfValidTerm(castExpression.Expression, flags, terms);
// If the subexpression is a valid term, so is the cast expression
expressionType = flags;
}
private static void AddMemberAccessExpressionTerms(MemberAccessExpressionSyntax memberAccessExpression, IList<string> terms, ref ExpressionType expressionType)
{
var flags = ExpressionType.Invalid;
// These operators always have a RHS of a name node, which we know would
// "claim" to be a valid term, but is not valid without the LHS present.
// So, we don't bother collecting anything from the RHS...
AddSubExpressionTerms(memberAccessExpression.Expression, terms, ref flags);
// If the LHS says it's a valid term, then we add it ONLY if our PARENT
// is NOT another dot/arrow. This allows the expression 'a.b.c.d' to
// add both 'a.b.c.d' and 'a.b.c', but not 'a.b' and 'a'.
if (IsValidTerm(flags) &&
!memberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) &&
!memberAccessExpression.IsParentKind(SyntaxKind.PointerMemberAccessExpression))
{
terms.Add(ConvertToString(memberAccessExpression.Expression));
}
// And this expression itself is a valid term if the LHS is a valid
// expression, and its PARENT is not an invocation.
if (IsValidExpression(flags) &&
!memberAccessExpression.IsParentKind(SyntaxKind.InvocationExpression))
{
expressionType = ExpressionType.ValidTerm;
}
else
{
expressionType = ExpressionType.ValidExpression;
}
}
private static void AddObjectCreationExpressionTerms(ObjectCreationExpressionSyntax objectionCreationExpression, IList<string> terms, ref ExpressionType expressionType)
{
// Object creation can *definitely* cause side effects. So we initially
// mark this as something invalid. We allow it as a valid expr if all
// the sub arguments are valid terms.
expressionType = ExpressionType.Invalid;
if (objectionCreationExpression.ArgumentList != null)
{
var flags = ExpressionType.Invalid;
AddArgumentTerms(objectionCreationExpression.ArgumentList, terms, ref flags);
// If all arguments are terms, then this is possibly a valid expr that can be used
// somewhere higher in the stack.
if (IsValidTerm(flags))
{
expressionType = ExpressionType.ValidExpression;
}
}
}
private static void AddArrayCreationExpressionTerms(
ArrayCreationExpressionSyntax arrayCreationExpression,
IList<string> terms,
ref ExpressionType expressionType)
{
var validTerm = true;
if (arrayCreationExpression.Initializer != null)
{
var flags = ExpressionType.Invalid;
arrayCreationExpression.Initializer.Expressions.Do(e => AddSubExpressionTerms(e, terms, ref flags));
validTerm &= IsValidTerm(flags);
}
if (validTerm)
{
expressionType = ExpressionType.ValidExpression;
}
else
{
expressionType = ExpressionType.Invalid;
}
}
private static void AddInvocationExpressionTerms(InvocationExpressionSyntax invocationExpression, IList<string> terms, ref ExpressionType expressionType)
{
#pragma warning disable IDE0059 // Unnecessary assignment of a value
// Invocations definitely have side effects. So we assume this
// is invalid initially;
expressionType = ExpressionType.Invalid;
#pragma warning restore IDE0059 // Unnecessary assignment of a value
ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid;
AddSubExpressionTerms(invocationExpression.Expression, terms, ref leftFlags);
AddArgumentTerms(invocationExpression.ArgumentList, terms, ref rightFlags);
AddIfValidTerm(invocationExpression.Expression, leftFlags, terms);
// We're valid if both children are...
expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression;
}
private static void AddPrefixUnaryExpressionTerms(PrefixUnaryExpressionSyntax prefixUnaryExpression, IList<string> terms, ref ExpressionType expressionType)
{
expressionType = ExpressionType.Invalid;
var flags = ExpressionType.Invalid;
// Ask our subexpression for terms
AddSubExpressionTerms(prefixUnaryExpression.Operand, terms, ref flags);
// Is our expression a valid term?
AddIfValidTerm(prefixUnaryExpression.Operand, flags, terms);
if (prefixUnaryExpression.IsKind(SyntaxKind.LogicalNotExpression, SyntaxKind.BitwiseNotExpression, SyntaxKind.UnaryMinusExpression, SyntaxKind.UnaryPlusExpression))
{
// We're a valid expression if our subexpression is...
expressionType = flags & ExpressionType.ValidExpression;
}
}
private static void AddAwaitExpressionTerms(AwaitExpressionSyntax awaitExpression, IList<string> terms, ref ExpressionType expressionType)
{
expressionType = ExpressionType.Invalid;
var flags = ExpressionType.Invalid;
// Ask our subexpression for terms
AddSubExpressionTerms(awaitExpression.Expression, terms, ref flags);
// Is our expression a valid term?
AddIfValidTerm(awaitExpression.Expression, flags, terms);
}
private static void AddPostfixUnaryExpressionTerms(PostfixUnaryExpressionSyntax postfixUnaryExpression, IList<string> terms, ref ExpressionType expressionType)
{
// ++ and -- are the only postfix operators. Since they always have side
// effects, we never consider this an expression.
expressionType = ExpressionType.Invalid;
var flags = ExpressionType.Invalid;
// Ask our subexpression for terms
AddSubExpressionTerms(postfixUnaryExpression.Operand, terms, ref flags);
// Is our expression a valid term?
AddIfValidTerm(postfixUnaryExpression.Operand, flags, terms);
}
private static void AddConditionalExpressionTerms(ConditionalExpressionSyntax conditionalExpression, IList<string> terms, ref ExpressionType expressionType)
{
ExpressionType conditionFlags = ExpressionType.Invalid, trueFlags = ExpressionType.Invalid, falseFlags = ExpressionType.Invalid;
AddSubExpressionTerms(conditionalExpression.Condition, terms, ref conditionFlags);
AddSubExpressionTerms(conditionalExpression.WhenTrue, terms, ref trueFlags);
AddSubExpressionTerms(conditionalExpression.WhenFalse, terms, ref falseFlags);
AddIfValidTerm(conditionalExpression.Condition, conditionFlags, terms);
AddIfValidTerm(conditionalExpression.WhenTrue, trueFlags, terms);
AddIfValidTerm(conditionalExpression.WhenFalse, falseFlags, terms);
// We're valid if all children are...
expressionType = (conditionFlags & trueFlags & falseFlags) & ExpressionType.ValidExpression;
}
private static void AddBinaryExpressionTerms(ExpressionSyntax binaryExpression, ExpressionSyntax left, ExpressionSyntax right, IList<string> terms, ref ExpressionType expressionType)
{
ExpressionType leftFlags = ExpressionType.Invalid, rightFlags = ExpressionType.Invalid;
AddSubExpressionTerms(left, terms, ref leftFlags);
AddSubExpressionTerms(right, terms, ref rightFlags);
if (IsValidTerm(leftFlags))
{
terms.Add(ConvertToString(left));
}
if (IsValidTerm(rightFlags))
{
terms.Add(ConvertToString(right));
}
// Many sorts of binops (like +=) will definitely have side effects. We only
// consider this valid if it's a simple expression like +, -, etc.
switch (binaryExpression.Kind())
{
case SyntaxKind.AddExpression:
case SyntaxKind.SubtractExpression:
case SyntaxKind.MultiplyExpression:
case SyntaxKind.DivideExpression:
case SyntaxKind.ModuloExpression:
case SyntaxKind.LeftShiftExpression:
case SyntaxKind.RightShiftExpression:
case SyntaxKind.LogicalOrExpression:
case SyntaxKind.LogicalAndExpression:
case SyntaxKind.BitwiseOrExpression:
case SyntaxKind.BitwiseAndExpression:
case SyntaxKind.ExclusiveOrExpression:
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
case SyntaxKind.LessThanExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.IsExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.CoalesceExpression:
// We're valid if both children are...
expressionType = (leftFlags & rightFlags) & ExpressionType.ValidExpression;
return;
default:
expressionType = ExpressionType.Invalid;
return;
}
}
private static void AddArgumentTerms(ArgumentListSyntax argumentList, IList<string> terms, ref ExpressionType expressionType)
{
var validExpr = true;
var validTerm = true;
// Process the list of expressions. This is probably a list of
// arguments to a function call(or a list of array index expressions)
foreach (var arg in argumentList.Arguments)
{
var flags = ExpressionType.Invalid;
AddSubExpressionTerms(arg.Expression, terms, ref flags);
if (IsValidTerm(flags))
{
terms.Add(ConvertToString(arg.Expression));
}
validExpr &= IsValidExpression(flags);
validTerm &= IsValidTerm(flags);
}
// We're never a valid term if all arguments were valid terms. If not, we're a valid
// expression if all arguments where. Otherwise, we're just invalid.
expressionType = validTerm
? ExpressionType.ValidTerm
: validExpr
? ExpressionType.ValidExpression : ExpressionType.Invalid;
}
}
}
| -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/Lsif/Generator/Writing/LineModeLsifJsonWriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.IO;
using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing
{
/// <summary>
/// An <see cref="ILsifJsonWriter"/> that writes in <see cref="LsifFormat.Line"/>.
/// </summary>
internal sealed partial class LineModeLsifJsonWriter : ILsifJsonWriter
{
private readonly object _writeGate = new object();
private readonly TextWriter _outputWriter;
private readonly JsonSerializerSettings _settings;
public LineModeLsifJsonWriter(TextWriter outputWriter)
{
_settings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.None,
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
TypeNameHandling = TypeNameHandling.None,
Converters = new[] { new LsifConverter() }
};
_outputWriter = outputWriter;
}
public void Write(Element element)
{
var line = JsonConvert.SerializeObject(element, _settings);
lock (_writeGate)
{
_outputWriter.WriteLine(line);
}
}
public void WriteAll(List<Element> elements)
{
var lines = new List<string>();
foreach (var element in elements)
lines.Add(JsonConvert.SerializeObject(element, _settings));
lock (_writeGate)
{
foreach (var line in lines)
_outputWriter.WriteLine(line);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing
{
/// <summary>
/// An <see cref="ILsifJsonWriter"/> that writes in <see cref="LsifFormat.Line"/>.
/// </summary>
internal sealed partial class LineModeLsifJsonWriter : ILsifJsonWriter
{
private readonly object _writeGate = new object();
private readonly TextWriter _outputWriter;
private readonly JsonSerializerSettings _settings;
public LineModeLsifJsonWriter(TextWriter outputWriter)
{
_settings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.None,
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
TypeNameHandling = TypeNameHandling.None,
Converters = new[] { new LsifConverter() }
};
_outputWriter = outputWriter;
}
public void Write(Element element)
{
var line = JsonConvert.SerializeObject(element, _settings);
lock (_writeGate)
{
_outputWriter.WriteLine(line);
}
}
public void WriteAll(List<Element> elements)
{
var lines = new List<string>();
foreach (var element in elements)
lines.Add(JsonConvert.SerializeObject(element, _settings));
lock (_writeGate)
{
foreach (var line in lines)
_outputWriter.WriteLine(line);
}
}
}
}
| -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/Retargeting/RetargetingTypeParameterSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
using System.Globalization;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
/// <summary>
/// Represents a type parameter in a RetargetingModuleSymbol. Essentially this is a wrapper around
/// another TypeParameterSymbol that is responsible for retargeting symbols from one assembly to another.
/// It can retarget symbols for multiple assemblies at the same time.
/// </summary>
internal sealed class RetargetingTypeParameterSymbol
: WrappedTypeParameterSymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
/// <summary>
/// Retargeted custom attributes
/// </summary>
private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes;
public RetargetingTypeParameterSymbol(RetargetingModuleSymbol retargetingModule, TypeParameterSymbol underlyingTypeParameter)
: base(underlyingTypeParameter)
{
Debug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingTypeParameter is RetargetingTypeParameterSymbol));
_retargetingModule = retargetingModule;
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public override Symbol ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.ContainingSymbol);
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingTypeParameter.GetAttributes(), ref _lazyCustomAttributes);
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetConstraintTypes(inProgress));
}
internal override bool? IsNotNullable
{
get
{
return _underlyingTypeParameter.IsNotNullable;
}
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetInterfaces(inProgress));
}
internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetEffectiveBaseClass(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode);
}
internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetDeducedBaseType(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode);
}
internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness
{
get { return null; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
using System.Globalization;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
/// <summary>
/// Represents a type parameter in a RetargetingModuleSymbol. Essentially this is a wrapper around
/// another TypeParameterSymbol that is responsible for retargeting symbols from one assembly to another.
/// It can retarget symbols for multiple assemblies at the same time.
/// </summary>
internal sealed class RetargetingTypeParameterSymbol
: WrappedTypeParameterSymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
/// <summary>
/// Retargeted custom attributes
/// </summary>
private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes;
public RetargetingTypeParameterSymbol(RetargetingModuleSymbol retargetingModule, TypeParameterSymbol underlyingTypeParameter)
: base(underlyingTypeParameter)
{
Debug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingTypeParameter is RetargetingTypeParameterSymbol));
_retargetingModule = retargetingModule;
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public override Symbol ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.ContainingSymbol);
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingTypeParameter.GetAttributes(), ref _lazyCustomAttributes);
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetConstraintTypes(inProgress));
}
internal override bool? IsNotNullable
{
get
{
return _underlyingTypeParameter.IsNotNullable;
}
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetInterfaces(inProgress));
}
internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetEffectiveBaseClass(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode);
}
internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress)
{
return this.RetargetingTranslator.Retarget(_underlyingTypeParameter.GetDeducedBaseType(inProgress), RetargetOptions.RetargetPrimitiveTypesByTypeCode);
}
internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness
{
get { return null; }
}
}
}
| -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/Retargeting/RetargetingNamedTypeSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
/// <summary>
/// Represents a type of a RetargetingModuleSymbol. Essentially this is a wrapper around
/// another NamedTypeSymbol that is responsible for retargeting referenced symbols from one assembly to another.
/// It can retarget symbols for multiple assemblies at the same time.
/// </summary>
internal sealed class RetargetingNamedTypeSymbol : WrappedNamedTypeSymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters;
private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType;
private ImmutableArray<NamedTypeSymbol> _lazyInterfaces = default(ImmutableArray<NamedTypeSymbol>);
private NamedTypeSymbol _lazyDeclaredBaseType = ErrorTypeSymbol.UnknownResultType;
private ImmutableArray<NamedTypeSymbol> _lazyDeclaredInterfaces;
private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes;
private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized;
public RetargetingNamedTypeSymbol(RetargetingModuleSymbol retargetingModule, NamedTypeSymbol underlyingType, TupleExtraData tupleData = null)
: base(underlyingType, tupleData)
{
Debug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingType is RetargetingNamedTypeSymbol));
_retargetingModule = retargetingModule;
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
{
return new RetargetingNamedTypeSymbol(_retargetingModule, _underlyingType, newData);
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get
{
if (_lazyTypeParameters.IsDefault)
{
if (this.Arity == 0)
{
_lazyTypeParameters = ImmutableArray<TypeParameterSymbol>.Empty;
}
else
{
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters,
this.RetargetingTranslator.Retarget(_underlyingType.TypeParameters), default(ImmutableArray<TypeParameterSymbol>));
}
}
return _lazyTypeParameters;
}
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get
{
// This is always the instance type, so the type arguments are the same as the type parameters.
return GetTypeParametersAsTypeArguments();
}
}
public override NamedTypeSymbol ConstructedFrom
{
get
{
return this;
}
}
public override NamedTypeSymbol EnumUnderlyingType
{
get
{
var underlying = _underlyingType.EnumUnderlyingType;
return (object)underlying == null ? null : this.RetargetingTranslator.Retarget(underlying, RetargetOptions.RetargetPrimitiveTypesByTypeCode); // comes from field's signature.
}
}
public override IEnumerable<string> MemberNames
{
get
{
return _underlyingType.MemberNames;
}
}
public override ImmutableArray<Symbol> GetMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembers());
}
internal override ImmutableArray<Symbol> GetMembersUnordered()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembersUnordered());
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembers(name));
}
public override void InitializeTupleFieldDefinitionsToIndexMap()
{
Debug.Assert(this.IsTupleType);
Debug.Assert(this.IsDefinition); // we only store a map for definitions
var retargetedMap = new SmallDictionary<FieldSymbol, int>(ReferenceEqualityComparer.Instance);
foreach ((FieldSymbol field, int index) in _underlyingType.TupleFieldDefinitionsToIndexMap)
{
retargetedMap.Add(this.RetargetingTranslator.Retarget(field), index);
}
this.TupleData!.SetFieldDefinitionsToIndexMap(retargetedMap);
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
foreach (FieldSymbol f in _underlyingType.GetFieldsToEmit())
{
yield return this.RetargetingTranslator.Retarget(f);
}
}
internal override IEnumerable<MethodSymbol> GetMethodsToEmit()
{
bool isInterface = _underlyingType.IsInterfaceType();
foreach (MethodSymbol method in _underlyingType.GetMethodsToEmit())
{
Debug.Assert((object)method != null);
int gapSize = isInterface ? Microsoft.CodeAnalysis.ModuleExtensions.GetVTableGapSize(method.MetadataName) : 0;
if (gapSize > 0)
{
do
{
yield return null;
gapSize--;
}
while (gapSize > 0);
}
else
{
yield return this.RetargetingTranslator.Retarget(method);
}
}
}
internal override IEnumerable<PropertySymbol> GetPropertiesToEmit()
{
foreach (PropertySymbol p in _underlyingType.GetPropertiesToEmit())
{
yield return this.RetargetingTranslator.Retarget(p);
}
}
internal override IEnumerable<EventSymbol> GetEventsToEmit()
{
foreach (EventSymbol e in _underlyingType.GetEventsToEmit())
{
yield return this.RetargetingTranslator.Retarget(e);
}
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetEarlyAttributeDecodingMembers());
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetEarlyAttributeDecodingMembers(name));
}
internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembersUnordered());
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers());
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers(name));
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers(name, arity));
}
public override Symbol ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingType.ContainingSymbol);
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingType.GetAttributes(), ref _lazyCustomAttributes);
}
internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder)
{
return this.RetargetingTranslator.RetargetAttributes(_underlyingType.GetCustomAttributesToEmit(moduleBuilder));
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
internal override NamedTypeSymbol LookupMetadataType(ref MetadataTypeName typeName)
{
return this.RetargetingTranslator.Retarget(_underlyingType.LookupMetadataType(ref typeName), RetargetOptions.RetargetPrimitiveTypesByName);
}
private static ExtendedErrorTypeSymbol CyclicInheritanceError(RetargetingNamedTypeSymbol type, TypeSymbol declaredBase)
{
var info = new CSDiagnosticInfo(ErrorCode.ERR_ImportedCircularBase, declaredBase, type);
return new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable, info, true);
}
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics
{
get
{
if (ReferenceEquals(_lazyBaseType, ErrorTypeSymbol.UnknownResultType))
{
NamedTypeSymbol acyclicBase = GetDeclaredBaseType(null);
if ((object)acyclicBase == null)
{
// if base was not declared, get it from BaseType that should set it to some default
var underlyingBase = _underlyingType.BaseTypeNoUseSiteDiagnostics;
if ((object)underlyingBase != null)
{
acyclicBase = this.RetargetingTranslator.Retarget(underlyingBase, RetargetOptions.RetargetPrimitiveTypesByName);
}
}
if ((object)acyclicBase != null && BaseTypeAnalysis.TypeDependsOn(acyclicBase, this))
{
return CyclicInheritanceError(this, acyclicBase);
}
Interlocked.CompareExchange(ref _lazyBaseType, acyclicBase, ErrorTypeSymbol.UnknownResultType);
}
return _lazyBaseType;
}
}
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
if (_lazyInterfaces.IsDefault)
{
var declaredInterfaces = GetDeclaredInterfaces(basesBeingResolved);
if (!IsInterface)
{
// only interfaces needs to check for inheritance cycles via interfaces.
return declaredInterfaces;
}
ImmutableArray<NamedTypeSymbol> result = declaredInterfaces
.SelectAsArray(t => BaseTypeAnalysis.TypeDependsOn(t, this) ? CyclicInheritanceError(this, t) : t);
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, result, default(ImmutableArray<NamedTypeSymbol>));
}
return _lazyInterfaces;
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetInterfacesToEmit());
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
if (ReferenceEquals(_lazyDeclaredBaseType, ErrorTypeSymbol.UnknownResultType))
{
var underlyingBase = _underlyingType.GetDeclaredBaseType(basesBeingResolved);
var declaredBase = (object)underlyingBase != null ? this.RetargetingTranslator.Retarget(underlyingBase, RetargetOptions.RetargetPrimitiveTypesByName) : null;
Interlocked.CompareExchange(ref _lazyDeclaredBaseType, declaredBase, ErrorTypeSymbol.UnknownResultType);
}
return _lazyDeclaredBaseType;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
if (_lazyDeclaredInterfaces.IsDefault)
{
var underlyingBaseInterfaces = _underlyingType.GetDeclaredInterfaces(basesBeingResolved);
var result = this.RetargetingTranslator.Retarget(underlyingBaseInterfaces);
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyDeclaredInterfaces, result, default(ImmutableArray<NamedTypeSymbol>));
}
return _lazyDeclaredInterfaces;
}
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
if (!_lazyCachedUseSiteInfo.IsInitialized)
{
AssemblySymbol primaryDependency = PrimaryDependency;
_lazyCachedUseSiteInfo.Initialize(primaryDependency, new UseSiteInfo<AssemblySymbol>(primaryDependency).AdjustDiagnosticInfo(CalculateUseSiteDiagnostic()));
}
return _lazyCachedUseSiteInfo.ToUseSiteInfo(PrimaryDependency);
}
internal override NamedTypeSymbol ComImportCoClass
{
get
{
NamedTypeSymbol coClass = _underlyingType.ComImportCoClass;
return (object)coClass == null ? null : this.RetargetingTranslator.Retarget(coClass, RetargetOptions.RetargetPrimitiveTypesByName);
}
}
internal override bool IsComImport
{
get { return _underlyingType.IsComImport; }
}
internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness
{
get { return null; }
}
public sealed override bool AreLocalsZeroed
{
get { throw ExceptionUtilities.Unreachable; }
}
internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null;
internal sealed override bool IsRecord => _underlyingType.IsRecord;
internal sealed override bool IsRecordStruct => _underlyingType.IsRecordStruct;
internal sealed override bool HasPossibleWellKnownCloneMethod() => _underlyingType.HasPossibleWellKnownCloneMethod();
internal override bool HasFieldInitializers() => _underlyingType.HasFieldInitializers();
internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
foreach ((MethodSymbol body, MethodSymbol implemented) in _underlyingType.SynthesizedInterfaceMethodImpls())
{
var newBody = this.RetargetingTranslator.Retarget(body, MemberSignatureComparer.RetargetedExplicitImplementationComparer);
var newImplemented = this.RetargetingTranslator.Retarget(implemented, MemberSignatureComparer.RetargetedExplicitImplementationComparer);
if (newBody is object && newImplemented is object)
{
yield return (newBody, newImplemented);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting
{
/// <summary>
/// Represents a type of a RetargetingModuleSymbol. Essentially this is a wrapper around
/// another NamedTypeSymbol that is responsible for retargeting referenced symbols from one assembly to another.
/// It can retarget symbols for multiple assemblies at the same time.
/// </summary>
internal sealed class RetargetingNamedTypeSymbol : WrappedNamedTypeSymbol
{
/// <summary>
/// Owning RetargetingModuleSymbol.
/// </summary>
private readonly RetargetingModuleSymbol _retargetingModule;
private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters;
private NamedTypeSymbol _lazyBaseType = ErrorTypeSymbol.UnknownResultType;
private ImmutableArray<NamedTypeSymbol> _lazyInterfaces = default(ImmutableArray<NamedTypeSymbol>);
private NamedTypeSymbol _lazyDeclaredBaseType = ErrorTypeSymbol.UnknownResultType;
private ImmutableArray<NamedTypeSymbol> _lazyDeclaredInterfaces;
private ImmutableArray<CSharpAttributeData> _lazyCustomAttributes;
private CachedUseSiteInfo<AssemblySymbol> _lazyCachedUseSiteInfo = CachedUseSiteInfo<AssemblySymbol>.Uninitialized;
public RetargetingNamedTypeSymbol(RetargetingModuleSymbol retargetingModule, NamedTypeSymbol underlyingType, TupleExtraData tupleData = null)
: base(underlyingType, tupleData)
{
Debug.Assert((object)retargetingModule != null);
Debug.Assert(!(underlyingType is RetargetingNamedTypeSymbol));
_retargetingModule = retargetingModule;
}
protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData)
{
return new RetargetingNamedTypeSymbol(_retargetingModule, _underlyingType, newData);
}
private RetargetingModuleSymbol.RetargetingSymbolTranslator RetargetingTranslator
{
get
{
return _retargetingModule.RetargetingTranslator;
}
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get
{
if (_lazyTypeParameters.IsDefault)
{
if (this.Arity == 0)
{
_lazyTypeParameters = ImmutableArray<TypeParameterSymbol>.Empty;
}
else
{
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyTypeParameters,
this.RetargetingTranslator.Retarget(_underlyingType.TypeParameters), default(ImmutableArray<TypeParameterSymbol>));
}
}
return _lazyTypeParameters;
}
}
internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics
{
get
{
// This is always the instance type, so the type arguments are the same as the type parameters.
return GetTypeParametersAsTypeArguments();
}
}
public override NamedTypeSymbol ConstructedFrom
{
get
{
return this;
}
}
public override NamedTypeSymbol EnumUnderlyingType
{
get
{
var underlying = _underlyingType.EnumUnderlyingType;
return (object)underlying == null ? null : this.RetargetingTranslator.Retarget(underlying, RetargetOptions.RetargetPrimitiveTypesByTypeCode); // comes from field's signature.
}
}
public override IEnumerable<string> MemberNames
{
get
{
return _underlyingType.MemberNames;
}
}
public override ImmutableArray<Symbol> GetMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembers());
}
internal override ImmutableArray<Symbol> GetMembersUnordered()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembersUnordered());
}
public override ImmutableArray<Symbol> GetMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetMembers(name));
}
public override void InitializeTupleFieldDefinitionsToIndexMap()
{
Debug.Assert(this.IsTupleType);
Debug.Assert(this.IsDefinition); // we only store a map for definitions
var retargetedMap = new SmallDictionary<FieldSymbol, int>(ReferenceEqualityComparer.Instance);
foreach ((FieldSymbol field, int index) in _underlyingType.TupleFieldDefinitionsToIndexMap)
{
retargetedMap.Add(this.RetargetingTranslator.Retarget(field), index);
}
this.TupleData!.SetFieldDefinitionsToIndexMap(retargetedMap);
}
internal override IEnumerable<FieldSymbol> GetFieldsToEmit()
{
foreach (FieldSymbol f in _underlyingType.GetFieldsToEmit())
{
yield return this.RetargetingTranslator.Retarget(f);
}
}
internal override IEnumerable<MethodSymbol> GetMethodsToEmit()
{
bool isInterface = _underlyingType.IsInterfaceType();
foreach (MethodSymbol method in _underlyingType.GetMethodsToEmit())
{
Debug.Assert((object)method != null);
int gapSize = isInterface ? Microsoft.CodeAnalysis.ModuleExtensions.GetVTableGapSize(method.MetadataName) : 0;
if (gapSize > 0)
{
do
{
yield return null;
gapSize--;
}
while (gapSize > 0);
}
else
{
yield return this.RetargetingTranslator.Retarget(method);
}
}
}
internal override IEnumerable<PropertySymbol> GetPropertiesToEmit()
{
foreach (PropertySymbol p in _underlyingType.GetPropertiesToEmit())
{
yield return this.RetargetingTranslator.Retarget(p);
}
}
internal override IEnumerable<EventSymbol> GetEventsToEmit()
{
foreach (EventSymbol e in _underlyingType.GetEventsToEmit())
{
yield return this.RetargetingTranslator.Retarget(e);
}
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetEarlyAttributeDecodingMembers());
}
internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetEarlyAttributeDecodingMembers(name));
}
internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembersUnordered());
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers());
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers(name));
}
public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity)
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetTypeMembers(name, arity));
}
public override Symbol ContainingSymbol
{
get
{
return this.RetargetingTranslator.Retarget(_underlyingType.ContainingSymbol);
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return this.RetargetingTranslator.GetRetargetedAttributes(_underlyingType.GetAttributes(), ref _lazyCustomAttributes);
}
internal override IEnumerable<CSharpAttributeData> GetCustomAttributesToEmit(PEModuleBuilder moduleBuilder)
{
return this.RetargetingTranslator.RetargetAttributes(_underlyingType.GetCustomAttributesToEmit(moduleBuilder));
}
public override AssemblySymbol ContainingAssembly
{
get
{
return _retargetingModule.ContainingAssembly;
}
}
internal override ModuleSymbol ContainingModule
{
get
{
return _retargetingModule;
}
}
internal override NamedTypeSymbol LookupMetadataType(ref MetadataTypeName typeName)
{
return this.RetargetingTranslator.Retarget(_underlyingType.LookupMetadataType(ref typeName), RetargetOptions.RetargetPrimitiveTypesByName);
}
private static ExtendedErrorTypeSymbol CyclicInheritanceError(RetargetingNamedTypeSymbol type, TypeSymbol declaredBase)
{
var info = new CSDiagnosticInfo(ErrorCode.ERR_ImportedCircularBase, declaredBase, type);
return new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable, info, true);
}
internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics
{
get
{
if (ReferenceEquals(_lazyBaseType, ErrorTypeSymbol.UnknownResultType))
{
NamedTypeSymbol acyclicBase = GetDeclaredBaseType(null);
if ((object)acyclicBase == null)
{
// if base was not declared, get it from BaseType that should set it to some default
var underlyingBase = _underlyingType.BaseTypeNoUseSiteDiagnostics;
if ((object)underlyingBase != null)
{
acyclicBase = this.RetargetingTranslator.Retarget(underlyingBase, RetargetOptions.RetargetPrimitiveTypesByName);
}
}
if ((object)acyclicBase != null && BaseTypeAnalysis.TypeDependsOn(acyclicBase, this))
{
return CyclicInheritanceError(this, acyclicBase);
}
Interlocked.CompareExchange(ref _lazyBaseType, acyclicBase, ErrorTypeSymbol.UnknownResultType);
}
return _lazyBaseType;
}
}
internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved)
{
if (_lazyInterfaces.IsDefault)
{
var declaredInterfaces = GetDeclaredInterfaces(basesBeingResolved);
if (!IsInterface)
{
// only interfaces needs to check for inheritance cycles via interfaces.
return declaredInterfaces;
}
ImmutableArray<NamedTypeSymbol> result = declaredInterfaces
.SelectAsArray(t => BaseTypeAnalysis.TypeDependsOn(t, this) ? CyclicInheritanceError(this, t) : t);
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyInterfaces, result, default(ImmutableArray<NamedTypeSymbol>));
}
return _lazyInterfaces;
}
internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit()
{
return this.RetargetingTranslator.Retarget(_underlyingType.GetInterfacesToEmit());
}
internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved)
{
if (ReferenceEquals(_lazyDeclaredBaseType, ErrorTypeSymbol.UnknownResultType))
{
var underlyingBase = _underlyingType.GetDeclaredBaseType(basesBeingResolved);
var declaredBase = (object)underlyingBase != null ? this.RetargetingTranslator.Retarget(underlyingBase, RetargetOptions.RetargetPrimitiveTypesByName) : null;
Interlocked.CompareExchange(ref _lazyDeclaredBaseType, declaredBase, ErrorTypeSymbol.UnknownResultType);
}
return _lazyDeclaredBaseType;
}
internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved)
{
if (_lazyDeclaredInterfaces.IsDefault)
{
var underlyingBaseInterfaces = _underlyingType.GetDeclaredInterfaces(basesBeingResolved);
var result = this.RetargetingTranslator.Retarget(underlyingBaseInterfaces);
ImmutableInterlocked.InterlockedCompareExchange(ref _lazyDeclaredInterfaces, result, default(ImmutableArray<NamedTypeSymbol>));
}
return _lazyDeclaredInterfaces;
}
internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo()
{
if (!_lazyCachedUseSiteInfo.IsInitialized)
{
AssemblySymbol primaryDependency = PrimaryDependency;
_lazyCachedUseSiteInfo.Initialize(primaryDependency, new UseSiteInfo<AssemblySymbol>(primaryDependency).AdjustDiagnosticInfo(CalculateUseSiteDiagnostic()));
}
return _lazyCachedUseSiteInfo.ToUseSiteInfo(PrimaryDependency);
}
internal override NamedTypeSymbol ComImportCoClass
{
get
{
NamedTypeSymbol coClass = _underlyingType.ComImportCoClass;
return (object)coClass == null ? null : this.RetargetingTranslator.Retarget(coClass, RetargetOptions.RetargetPrimitiveTypesByName);
}
}
internal override bool IsComImport
{
get { return _underlyingType.IsComImport; }
}
internal sealed override CSharpCompilation DeclaringCompilation // perf, not correctness
{
get { return null; }
}
public sealed override bool AreLocalsZeroed
{
get { throw ExceptionUtilities.Unreachable; }
}
internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable;
internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null;
internal sealed override bool IsRecord => _underlyingType.IsRecord;
internal sealed override bool IsRecordStruct => _underlyingType.IsRecordStruct;
internal sealed override bool HasPossibleWellKnownCloneMethod() => _underlyingType.HasPossibleWellKnownCloneMethod();
internal override bool HasFieldInitializers() => _underlyingType.HasFieldInitializers();
internal override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls()
{
foreach ((MethodSymbol body, MethodSymbol implemented) in _underlyingType.SynthesizedInterfaceMethodImpls())
{
var newBody = this.RetargetingTranslator.Retarget(body, MemberSignatureComparer.RetargetedExplicitImplementationComparer);
var newImplemented = this.RetargetingTranslator.Retarget(implemented, MemberSignatureComparer.RetargetedExplicitImplementationComparer);
if (newBody is object && newImplemented is object)
{
yield return (newBody, newImplemented);
}
}
}
}
}
| -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/Syntax/SyntaxNode.Iterators.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
public abstract partial class SyntaxNode
{
private IEnumerable<SyntaxNode> DescendantNodesImpl(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren, bool descendIntoTrivia, bool includeSelf)
{
return descendIntoTrivia
? DescendantNodesAndTokensImpl(span, descendIntoChildren, true, includeSelf).Where(e => e.IsNode).Select(e => e.AsNode()!)
: DescendantNodesOnly(span, descendIntoChildren, includeSelf);
}
private IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensImpl(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren, bool descendIntoTrivia, bool includeSelf)
{
return descendIntoTrivia
? DescendantNodesAndTokensIntoTrivia(span, descendIntoChildren, includeSelf)
: DescendantNodesAndTokensOnly(span, descendIntoChildren, includeSelf);
}
private IEnumerable<SyntaxTrivia> DescendantTriviaImpl(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return descendIntoTrivia
? DescendantTriviaIntoTrivia(span, descendIntoChildren)
: DescendantTriviaOnly(span, descendIntoChildren);
}
private static bool IsInSpan(in TextSpan span, TextSpan childSpan)
{
return span.OverlapsWith(childSpan)
// special case for zero-width tokens (OverlapsWith never returns true for these)
|| (childSpan.Length == 0 && span.IntersectsWith(childSpan));
}
private struct ChildSyntaxListEnumeratorStack : IDisposable
{
private static readonly ObjectPool<ChildSyntaxList.Enumerator[]> s_stackPool = new ObjectPool<ChildSyntaxList.Enumerator[]>(() => new ChildSyntaxList.Enumerator[16]);
private ChildSyntaxList.Enumerator[]? _stack;
private int _stackPtr;
public ChildSyntaxListEnumeratorStack(SyntaxNode startingNode, Func<SyntaxNode, bool>? descendIntoChildren)
{
if (descendIntoChildren == null || descendIntoChildren(startingNode))
{
_stack = s_stackPool.Allocate();
_stackPtr = 0;
_stack[0].InitializeFrom(startingNode);
}
else
{
_stack = null;
_stackPtr = -1;
}
}
public bool IsNotEmpty { get { return _stackPtr >= 0; } }
public bool TryGetNextInSpan(in TextSpan span, out SyntaxNodeOrToken value)
{
Debug.Assert(_stack is object);
while (_stack[_stackPtr].TryMoveNextAndGetCurrent(out value))
{
if (IsInSpan(in span, value.FullSpan))
{
return true;
}
}
_stackPtr--;
return false;
}
public SyntaxNode? TryGetNextAsNodeInSpan(in TextSpan span)
{
Debug.Assert(_stack is object);
SyntaxNode? nodeValue;
while ((nodeValue = _stack[_stackPtr].TryMoveNextAndGetCurrentAsNode()) != null)
{
if (IsInSpan(in span, nodeValue.FullSpan))
{
return nodeValue;
}
}
_stackPtr--;
return null;
}
public void PushChildren(SyntaxNode node)
{
Debug.Assert(_stack is object);
if (++_stackPtr >= _stack.Length)
{
// Geometric growth
Array.Resize(ref _stack, checked(_stackPtr * 2));
}
_stack[_stackPtr].InitializeFrom(node);
}
public void PushChildren(SyntaxNode node, Func<SyntaxNode, bool>? descendIntoChildren)
{
if (descendIntoChildren == null || descendIntoChildren(node))
{
PushChildren(node);
}
}
public void Dispose()
{
// Return only reasonably-sized stacks to the pool.
if (_stack?.Length < 256)
{
Array.Clear(_stack, 0, _stack.Length);
s_stackPool.Free(_stack);
}
}
}
private struct TriviaListEnumeratorStack : IDisposable
{
private static readonly ObjectPool<SyntaxTriviaList.Enumerator[]> s_stackPool = new ObjectPool<SyntaxTriviaList.Enumerator[]>(() => new SyntaxTriviaList.Enumerator[16]);
private SyntaxTriviaList.Enumerator[] _stack;
private int _stackPtr;
public bool TryGetNext(out SyntaxTrivia value)
{
if (_stack[_stackPtr].TryMoveNextAndGetCurrent(out value))
{
return true;
}
_stackPtr--;
return false;
}
public void PushLeadingTrivia(in SyntaxToken token)
{
Grow();
_stack[_stackPtr].InitializeFromLeadingTrivia(in token);
}
public void PushTrailingTrivia(in SyntaxToken token)
{
Grow();
_stack[_stackPtr].InitializeFromTrailingTrivia(in token);
}
private void Grow()
{
if (_stack == null)
{
_stack = s_stackPool.Allocate();
_stackPtr = -1;
}
if (++_stackPtr >= _stack.Length)
{
// Geometric growth
Array.Resize(ref _stack, checked(_stackPtr * 2));
}
}
public void Dispose()
{
// Return only reasonably-sized stacks to the pool.
if (_stack?.Length < 256)
{
Array.Clear(_stack, 0, _stack.Length);
s_stackPool.Free(_stack);
}
}
}
private struct TwoEnumeratorListStack : IDisposable
{
public enum Which : byte
{
Node,
Trivia
}
private ChildSyntaxListEnumeratorStack _nodeStack;
private TriviaListEnumeratorStack _triviaStack;
private readonly ArrayBuilder<Which>? _discriminatorStack;
public TwoEnumeratorListStack(SyntaxNode startingNode, Func<SyntaxNode, bool>? descendIntoChildren)
{
_nodeStack = new ChildSyntaxListEnumeratorStack(startingNode, descendIntoChildren);
_triviaStack = new TriviaListEnumeratorStack();
if (_nodeStack.IsNotEmpty)
{
_discriminatorStack = ArrayBuilder<Which>.GetInstance();
_discriminatorStack.Push(Which.Node);
}
else
{
_discriminatorStack = null;
}
}
public bool IsNotEmpty { get { return _discriminatorStack?.Count > 0; } }
public Which PeekNext()
{
Debug.Assert(_discriminatorStack is object);
return _discriminatorStack.Peek();
}
public bool TryGetNextInSpan(in TextSpan span, out SyntaxNodeOrToken value)
{
if (_nodeStack.TryGetNextInSpan(in span, out value))
{
return true;
}
Debug.Assert(_discriminatorStack is object);
_discriminatorStack.Pop();
return false;
}
public bool TryGetNext(out SyntaxTrivia value)
{
if (_triviaStack.TryGetNext(out value))
{
return true;
}
Debug.Assert(_discriminatorStack is object);
_discriminatorStack.Pop();
return false;
}
public void PushChildren(SyntaxNode node, Func<SyntaxNode, bool>? descendIntoChildren)
{
if (descendIntoChildren == null || descendIntoChildren(node))
{
Debug.Assert(_discriminatorStack is object);
_nodeStack.PushChildren(node);
_discriminatorStack.Push(Which.Node);
}
}
public void PushLeadingTrivia(in SyntaxToken token)
{
Debug.Assert(_discriminatorStack is object);
_triviaStack.PushLeadingTrivia(in token);
_discriminatorStack.Push(Which.Trivia);
}
public void PushTrailingTrivia(in SyntaxToken token)
{
Debug.Assert(_discriminatorStack is object);
_triviaStack.PushTrailingTrivia(in token);
_discriminatorStack.Push(Which.Trivia);
}
public void Dispose()
{
_nodeStack.Dispose();
_triviaStack.Dispose();
_discriminatorStack?.Free();
}
}
private struct ThreeEnumeratorListStack : IDisposable
{
public enum Which : byte
{
Node,
Trivia,
Token
}
private ChildSyntaxListEnumeratorStack _nodeStack;
private TriviaListEnumeratorStack _triviaStack;
private readonly ArrayBuilder<SyntaxNodeOrToken>? _tokenStack;
private readonly ArrayBuilder<Which>? _discriminatorStack;
public ThreeEnumeratorListStack(SyntaxNode startingNode, Func<SyntaxNode, bool>? descendIntoChildren)
{
_nodeStack = new ChildSyntaxListEnumeratorStack(startingNode, descendIntoChildren);
_triviaStack = new TriviaListEnumeratorStack();
if (_nodeStack.IsNotEmpty)
{
_tokenStack = ArrayBuilder<SyntaxNodeOrToken>.GetInstance();
_discriminatorStack = ArrayBuilder<Which>.GetInstance();
_discriminatorStack.Push(Which.Node);
}
else
{
_tokenStack = null;
_discriminatorStack = null;
}
}
public bool IsNotEmpty { get { return _discriminatorStack?.Count > 0; } }
public Which PeekNext()
{
Debug.Assert(_discriminatorStack is object);
return _discriminatorStack.Peek();
}
public bool TryGetNextInSpan(in TextSpan span, out SyntaxNodeOrToken value)
{
if (_nodeStack.TryGetNextInSpan(in span, out value))
{
return true;
}
Debug.Assert(_discriminatorStack is object);
_discriminatorStack.Pop();
return false;
}
public bool TryGetNext(out SyntaxTrivia value)
{
if (_triviaStack.TryGetNext(out value))
{
return true;
}
Debug.Assert(_discriminatorStack is object);
_discriminatorStack.Pop();
return false;
}
public SyntaxNodeOrToken PopToken()
{
Debug.Assert(_discriminatorStack is object);
Debug.Assert(_tokenStack is object);
_discriminatorStack.Pop();
return _tokenStack.Pop();
}
public void PushChildren(SyntaxNode node, Func<SyntaxNode, bool>? descendIntoChildren)
{
if (descendIntoChildren == null || descendIntoChildren(node))
{
Debug.Assert(_discriminatorStack is object);
_nodeStack.PushChildren(node);
_discriminatorStack.Push(Which.Node);
}
}
public void PushLeadingTrivia(in SyntaxToken token)
{
Debug.Assert(_discriminatorStack is object);
_triviaStack.PushLeadingTrivia(in token);
_discriminatorStack.Push(Which.Trivia);
}
public void PushTrailingTrivia(in SyntaxToken token)
{
Debug.Assert(_discriminatorStack is object);
_triviaStack.PushTrailingTrivia(in token);
_discriminatorStack.Push(Which.Trivia);
}
public void PushToken(in SyntaxNodeOrToken value)
{
Debug.Assert(_discriminatorStack is object);
Debug.Assert(_tokenStack is object);
_tokenStack.Push(value);
_discriminatorStack.Push(Which.Token);
}
public void Dispose()
{
_nodeStack.Dispose();
_triviaStack.Dispose();
_tokenStack?.Free();
_discriminatorStack?.Free();
}
}
private IEnumerable<SyntaxNode> DescendantNodesOnly(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren, bool includeSelf)
{
if (includeSelf && IsInSpan(in span, this.FullSpan))
{
yield return this;
}
using (var stack = new ChildSyntaxListEnumeratorStack(this, descendIntoChildren))
{
while (stack.IsNotEmpty)
{
SyntaxNode? nodeValue = stack.TryGetNextAsNodeInSpan(in span);
if (nodeValue != null)
{
// PERF: Push before yield return so that "nodeValue" is 'dead' after the yield
// and therefore doesn't need to be stored in the iterator state machine. This
// saves a field.
stack.PushChildren(nodeValue, descendIntoChildren);
yield return nodeValue;
}
}
}
}
private IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensOnly(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren, bool includeSelf)
{
if (includeSelf && IsInSpan(in span, this.FullSpan))
{
yield return this;
}
using (var stack = new ChildSyntaxListEnumeratorStack(this, descendIntoChildren))
{
while (stack.IsNotEmpty)
{
SyntaxNodeOrToken value;
if (stack.TryGetNextInSpan(in span, out value))
{
// PERF: Push before yield return so that "value" is 'dead' after the yield
// and therefore doesn't need to be stored in the iterator state machine. This
// saves a field.
var nodeValue = value.AsNode();
if (nodeValue != null)
{
stack.PushChildren(nodeValue, descendIntoChildren);
}
yield return value;
}
}
}
}
private IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensIntoTrivia(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren, bool includeSelf)
{
if (includeSelf && IsInSpan(in span, this.FullSpan))
{
yield return this;
}
using (var stack = new ThreeEnumeratorListStack(this, descendIntoChildren))
{
while (stack.IsNotEmpty)
{
switch (stack.PeekNext())
{
case ThreeEnumeratorListStack.Which.Node:
SyntaxNodeOrToken value;
if (stack.TryGetNextInSpan(in span, out value))
{
// PERF: The following code has an unusual structure (note the 'break' out of
// the case statement from inside an if body) in order to convince the compiler
// that it can save a field in the iterator machinery.
if (value.IsNode)
{
// parent nodes come before children (prefix document order)
stack.PushChildren(value.AsNode()!, descendIntoChildren);
}
else if (value.IsToken)
{
var token = value.AsToken();
// only look through trivia if this node has structured trivia
if (token.HasStructuredTrivia)
{
// trailing trivia comes last
if (token.HasTrailingTrivia)
{
stack.PushTrailingTrivia(in token);
}
// tokens come between leading and trailing trivia
stack.PushToken(in value);
// leading trivia comes first
if (token.HasLeadingTrivia)
{
stack.PushLeadingTrivia(in token);
}
// Exit the case block without yielding (see PERF note above)
break;
}
// no structure trivia, so just yield this token now
}
// PERF: Yield here (rather than inside the if bodies above) so that it's
// obvious to the compiler that 'value' is not used beyond this point and,
// therefore, doesn't need to be kept in a field.
yield return value;
}
break;
case ThreeEnumeratorListStack.Which.Trivia:
// yield structure nodes and enumerate their children
SyntaxTrivia trivia;
if (stack.TryGetNext(out trivia))
{
if (trivia.TryGetStructure(out var structureNode) && IsInSpan(in span, trivia.FullSpan))
{
// parent nodes come before children (prefix document order)
// PERF: Push before yield return so that "structureNode" is 'dead' after the yield
// and therefore doesn't need to be stored in the iterator state machine. This
// saves a field.
stack.PushChildren(structureNode, descendIntoChildren);
yield return structureNode;
}
}
break;
case ThreeEnumeratorListStack.Which.Token:
yield return stack.PopToken();
break;
}
}
}
}
private IEnumerable<SyntaxTrivia> DescendantTriviaOnly(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren)
{
using (var stack = new ChildSyntaxListEnumeratorStack(this, descendIntoChildren))
{
while (stack.IsNotEmpty)
{
SyntaxNodeOrToken value;
if (stack.TryGetNextInSpan(in span, out value))
{
if (value.AsNode(out var nodeValue))
{
stack.PushChildren(nodeValue, descendIntoChildren);
}
else if (value.IsToken)
{
var token = value.AsToken();
foreach (var trivia in token.LeadingTrivia)
{
if (IsInSpan(in span, trivia.FullSpan))
{
yield return trivia;
}
}
foreach (var trivia in token.TrailingTrivia)
{
if (IsInSpan(in span, trivia.FullSpan))
{
yield return trivia;
}
}
}
}
}
}
}
private IEnumerable<SyntaxTrivia> DescendantTriviaIntoTrivia(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren)
{
using (var stack = new TwoEnumeratorListStack(this, descendIntoChildren))
{
while (stack.IsNotEmpty)
{
switch (stack.PeekNext())
{
case TwoEnumeratorListStack.Which.Node:
SyntaxNodeOrToken value;
if (stack.TryGetNextInSpan(in span, out value))
{
if (value.AsNode(out var nodeValue))
{
stack.PushChildren(nodeValue, descendIntoChildren);
}
else if (value.IsToken)
{
var token = value.AsToken();
if (token.HasTrailingTrivia)
{
stack.PushTrailingTrivia(in token);
}
if (token.HasLeadingTrivia)
{
stack.PushLeadingTrivia(in token);
}
}
}
break;
case TwoEnumeratorListStack.Which.Trivia:
// yield structure nodes and enumerate their children
SyntaxTrivia trivia;
if (stack.TryGetNext(out trivia))
{
// PERF: Push before yield return so that "trivia" is 'dead' after the yield
// and therefore doesn't need to be stored in the iterator state machine. This
// saves a field.
if (trivia.TryGetStructure(out var structureNode))
{
stack.PushChildren(structureNode, descendIntoChildren);
}
if (IsInSpan(in span, trivia.FullSpan))
{
yield return trivia;
}
}
break;
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
public abstract partial class SyntaxNode
{
private IEnumerable<SyntaxNode> DescendantNodesImpl(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren, bool descendIntoTrivia, bool includeSelf)
{
return descendIntoTrivia
? DescendantNodesAndTokensImpl(span, descendIntoChildren, true, includeSelf).Where(e => e.IsNode).Select(e => e.AsNode()!)
: DescendantNodesOnly(span, descendIntoChildren, includeSelf);
}
private IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensImpl(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren, bool descendIntoTrivia, bool includeSelf)
{
return descendIntoTrivia
? DescendantNodesAndTokensIntoTrivia(span, descendIntoChildren, includeSelf)
: DescendantNodesAndTokensOnly(span, descendIntoChildren, includeSelf);
}
private IEnumerable<SyntaxTrivia> DescendantTriviaImpl(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren = null, bool descendIntoTrivia = false)
{
return descendIntoTrivia
? DescendantTriviaIntoTrivia(span, descendIntoChildren)
: DescendantTriviaOnly(span, descendIntoChildren);
}
private static bool IsInSpan(in TextSpan span, TextSpan childSpan)
{
return span.OverlapsWith(childSpan)
// special case for zero-width tokens (OverlapsWith never returns true for these)
|| (childSpan.Length == 0 && span.IntersectsWith(childSpan));
}
private struct ChildSyntaxListEnumeratorStack : IDisposable
{
private static readonly ObjectPool<ChildSyntaxList.Enumerator[]> s_stackPool = new ObjectPool<ChildSyntaxList.Enumerator[]>(() => new ChildSyntaxList.Enumerator[16]);
private ChildSyntaxList.Enumerator[]? _stack;
private int _stackPtr;
public ChildSyntaxListEnumeratorStack(SyntaxNode startingNode, Func<SyntaxNode, bool>? descendIntoChildren)
{
if (descendIntoChildren == null || descendIntoChildren(startingNode))
{
_stack = s_stackPool.Allocate();
_stackPtr = 0;
_stack[0].InitializeFrom(startingNode);
}
else
{
_stack = null;
_stackPtr = -1;
}
}
public bool IsNotEmpty { get { return _stackPtr >= 0; } }
public bool TryGetNextInSpan(in TextSpan span, out SyntaxNodeOrToken value)
{
Debug.Assert(_stack is object);
while (_stack[_stackPtr].TryMoveNextAndGetCurrent(out value))
{
if (IsInSpan(in span, value.FullSpan))
{
return true;
}
}
_stackPtr--;
return false;
}
public SyntaxNode? TryGetNextAsNodeInSpan(in TextSpan span)
{
Debug.Assert(_stack is object);
SyntaxNode? nodeValue;
while ((nodeValue = _stack[_stackPtr].TryMoveNextAndGetCurrentAsNode()) != null)
{
if (IsInSpan(in span, nodeValue.FullSpan))
{
return nodeValue;
}
}
_stackPtr--;
return null;
}
public void PushChildren(SyntaxNode node)
{
Debug.Assert(_stack is object);
if (++_stackPtr >= _stack.Length)
{
// Geometric growth
Array.Resize(ref _stack, checked(_stackPtr * 2));
}
_stack[_stackPtr].InitializeFrom(node);
}
public void PushChildren(SyntaxNode node, Func<SyntaxNode, bool>? descendIntoChildren)
{
if (descendIntoChildren == null || descendIntoChildren(node))
{
PushChildren(node);
}
}
public void Dispose()
{
// Return only reasonably-sized stacks to the pool.
if (_stack?.Length < 256)
{
Array.Clear(_stack, 0, _stack.Length);
s_stackPool.Free(_stack);
}
}
}
private struct TriviaListEnumeratorStack : IDisposable
{
private static readonly ObjectPool<SyntaxTriviaList.Enumerator[]> s_stackPool = new ObjectPool<SyntaxTriviaList.Enumerator[]>(() => new SyntaxTriviaList.Enumerator[16]);
private SyntaxTriviaList.Enumerator[] _stack;
private int _stackPtr;
public bool TryGetNext(out SyntaxTrivia value)
{
if (_stack[_stackPtr].TryMoveNextAndGetCurrent(out value))
{
return true;
}
_stackPtr--;
return false;
}
public void PushLeadingTrivia(in SyntaxToken token)
{
Grow();
_stack[_stackPtr].InitializeFromLeadingTrivia(in token);
}
public void PushTrailingTrivia(in SyntaxToken token)
{
Grow();
_stack[_stackPtr].InitializeFromTrailingTrivia(in token);
}
private void Grow()
{
if (_stack == null)
{
_stack = s_stackPool.Allocate();
_stackPtr = -1;
}
if (++_stackPtr >= _stack.Length)
{
// Geometric growth
Array.Resize(ref _stack, checked(_stackPtr * 2));
}
}
public void Dispose()
{
// Return only reasonably-sized stacks to the pool.
if (_stack?.Length < 256)
{
Array.Clear(_stack, 0, _stack.Length);
s_stackPool.Free(_stack);
}
}
}
private struct TwoEnumeratorListStack : IDisposable
{
public enum Which : byte
{
Node,
Trivia
}
private ChildSyntaxListEnumeratorStack _nodeStack;
private TriviaListEnumeratorStack _triviaStack;
private readonly ArrayBuilder<Which>? _discriminatorStack;
public TwoEnumeratorListStack(SyntaxNode startingNode, Func<SyntaxNode, bool>? descendIntoChildren)
{
_nodeStack = new ChildSyntaxListEnumeratorStack(startingNode, descendIntoChildren);
_triviaStack = new TriviaListEnumeratorStack();
if (_nodeStack.IsNotEmpty)
{
_discriminatorStack = ArrayBuilder<Which>.GetInstance();
_discriminatorStack.Push(Which.Node);
}
else
{
_discriminatorStack = null;
}
}
public bool IsNotEmpty { get { return _discriminatorStack?.Count > 0; } }
public Which PeekNext()
{
Debug.Assert(_discriminatorStack is object);
return _discriminatorStack.Peek();
}
public bool TryGetNextInSpan(in TextSpan span, out SyntaxNodeOrToken value)
{
if (_nodeStack.TryGetNextInSpan(in span, out value))
{
return true;
}
Debug.Assert(_discriminatorStack is object);
_discriminatorStack.Pop();
return false;
}
public bool TryGetNext(out SyntaxTrivia value)
{
if (_triviaStack.TryGetNext(out value))
{
return true;
}
Debug.Assert(_discriminatorStack is object);
_discriminatorStack.Pop();
return false;
}
public void PushChildren(SyntaxNode node, Func<SyntaxNode, bool>? descendIntoChildren)
{
if (descendIntoChildren == null || descendIntoChildren(node))
{
Debug.Assert(_discriminatorStack is object);
_nodeStack.PushChildren(node);
_discriminatorStack.Push(Which.Node);
}
}
public void PushLeadingTrivia(in SyntaxToken token)
{
Debug.Assert(_discriminatorStack is object);
_triviaStack.PushLeadingTrivia(in token);
_discriminatorStack.Push(Which.Trivia);
}
public void PushTrailingTrivia(in SyntaxToken token)
{
Debug.Assert(_discriminatorStack is object);
_triviaStack.PushTrailingTrivia(in token);
_discriminatorStack.Push(Which.Trivia);
}
public void Dispose()
{
_nodeStack.Dispose();
_triviaStack.Dispose();
_discriminatorStack?.Free();
}
}
private struct ThreeEnumeratorListStack : IDisposable
{
public enum Which : byte
{
Node,
Trivia,
Token
}
private ChildSyntaxListEnumeratorStack _nodeStack;
private TriviaListEnumeratorStack _triviaStack;
private readonly ArrayBuilder<SyntaxNodeOrToken>? _tokenStack;
private readonly ArrayBuilder<Which>? _discriminatorStack;
public ThreeEnumeratorListStack(SyntaxNode startingNode, Func<SyntaxNode, bool>? descendIntoChildren)
{
_nodeStack = new ChildSyntaxListEnumeratorStack(startingNode, descendIntoChildren);
_triviaStack = new TriviaListEnumeratorStack();
if (_nodeStack.IsNotEmpty)
{
_tokenStack = ArrayBuilder<SyntaxNodeOrToken>.GetInstance();
_discriminatorStack = ArrayBuilder<Which>.GetInstance();
_discriminatorStack.Push(Which.Node);
}
else
{
_tokenStack = null;
_discriminatorStack = null;
}
}
public bool IsNotEmpty { get { return _discriminatorStack?.Count > 0; } }
public Which PeekNext()
{
Debug.Assert(_discriminatorStack is object);
return _discriminatorStack.Peek();
}
public bool TryGetNextInSpan(in TextSpan span, out SyntaxNodeOrToken value)
{
if (_nodeStack.TryGetNextInSpan(in span, out value))
{
return true;
}
Debug.Assert(_discriminatorStack is object);
_discriminatorStack.Pop();
return false;
}
public bool TryGetNext(out SyntaxTrivia value)
{
if (_triviaStack.TryGetNext(out value))
{
return true;
}
Debug.Assert(_discriminatorStack is object);
_discriminatorStack.Pop();
return false;
}
public SyntaxNodeOrToken PopToken()
{
Debug.Assert(_discriminatorStack is object);
Debug.Assert(_tokenStack is object);
_discriminatorStack.Pop();
return _tokenStack.Pop();
}
public void PushChildren(SyntaxNode node, Func<SyntaxNode, bool>? descendIntoChildren)
{
if (descendIntoChildren == null || descendIntoChildren(node))
{
Debug.Assert(_discriminatorStack is object);
_nodeStack.PushChildren(node);
_discriminatorStack.Push(Which.Node);
}
}
public void PushLeadingTrivia(in SyntaxToken token)
{
Debug.Assert(_discriminatorStack is object);
_triviaStack.PushLeadingTrivia(in token);
_discriminatorStack.Push(Which.Trivia);
}
public void PushTrailingTrivia(in SyntaxToken token)
{
Debug.Assert(_discriminatorStack is object);
_triviaStack.PushTrailingTrivia(in token);
_discriminatorStack.Push(Which.Trivia);
}
public void PushToken(in SyntaxNodeOrToken value)
{
Debug.Assert(_discriminatorStack is object);
Debug.Assert(_tokenStack is object);
_tokenStack.Push(value);
_discriminatorStack.Push(Which.Token);
}
public void Dispose()
{
_nodeStack.Dispose();
_triviaStack.Dispose();
_tokenStack?.Free();
_discriminatorStack?.Free();
}
}
private IEnumerable<SyntaxNode> DescendantNodesOnly(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren, bool includeSelf)
{
if (includeSelf && IsInSpan(in span, this.FullSpan))
{
yield return this;
}
using (var stack = new ChildSyntaxListEnumeratorStack(this, descendIntoChildren))
{
while (stack.IsNotEmpty)
{
SyntaxNode? nodeValue = stack.TryGetNextAsNodeInSpan(in span);
if (nodeValue != null)
{
// PERF: Push before yield return so that "nodeValue" is 'dead' after the yield
// and therefore doesn't need to be stored in the iterator state machine. This
// saves a field.
stack.PushChildren(nodeValue, descendIntoChildren);
yield return nodeValue;
}
}
}
}
private IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensOnly(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren, bool includeSelf)
{
if (includeSelf && IsInSpan(in span, this.FullSpan))
{
yield return this;
}
using (var stack = new ChildSyntaxListEnumeratorStack(this, descendIntoChildren))
{
while (stack.IsNotEmpty)
{
SyntaxNodeOrToken value;
if (stack.TryGetNextInSpan(in span, out value))
{
// PERF: Push before yield return so that "value" is 'dead' after the yield
// and therefore doesn't need to be stored in the iterator state machine. This
// saves a field.
var nodeValue = value.AsNode();
if (nodeValue != null)
{
stack.PushChildren(nodeValue, descendIntoChildren);
}
yield return value;
}
}
}
}
private IEnumerable<SyntaxNodeOrToken> DescendantNodesAndTokensIntoTrivia(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren, bool includeSelf)
{
if (includeSelf && IsInSpan(in span, this.FullSpan))
{
yield return this;
}
using (var stack = new ThreeEnumeratorListStack(this, descendIntoChildren))
{
while (stack.IsNotEmpty)
{
switch (stack.PeekNext())
{
case ThreeEnumeratorListStack.Which.Node:
SyntaxNodeOrToken value;
if (stack.TryGetNextInSpan(in span, out value))
{
// PERF: The following code has an unusual structure (note the 'break' out of
// the case statement from inside an if body) in order to convince the compiler
// that it can save a field in the iterator machinery.
if (value.IsNode)
{
// parent nodes come before children (prefix document order)
stack.PushChildren(value.AsNode()!, descendIntoChildren);
}
else if (value.IsToken)
{
var token = value.AsToken();
// only look through trivia if this node has structured trivia
if (token.HasStructuredTrivia)
{
// trailing trivia comes last
if (token.HasTrailingTrivia)
{
stack.PushTrailingTrivia(in token);
}
// tokens come between leading and trailing trivia
stack.PushToken(in value);
// leading trivia comes first
if (token.HasLeadingTrivia)
{
stack.PushLeadingTrivia(in token);
}
// Exit the case block without yielding (see PERF note above)
break;
}
// no structure trivia, so just yield this token now
}
// PERF: Yield here (rather than inside the if bodies above) so that it's
// obvious to the compiler that 'value' is not used beyond this point and,
// therefore, doesn't need to be kept in a field.
yield return value;
}
break;
case ThreeEnumeratorListStack.Which.Trivia:
// yield structure nodes and enumerate their children
SyntaxTrivia trivia;
if (stack.TryGetNext(out trivia))
{
if (trivia.TryGetStructure(out var structureNode) && IsInSpan(in span, trivia.FullSpan))
{
// parent nodes come before children (prefix document order)
// PERF: Push before yield return so that "structureNode" is 'dead' after the yield
// and therefore doesn't need to be stored in the iterator state machine. This
// saves a field.
stack.PushChildren(structureNode, descendIntoChildren);
yield return structureNode;
}
}
break;
case ThreeEnumeratorListStack.Which.Token:
yield return stack.PopToken();
break;
}
}
}
}
private IEnumerable<SyntaxTrivia> DescendantTriviaOnly(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren)
{
using (var stack = new ChildSyntaxListEnumeratorStack(this, descendIntoChildren))
{
while (stack.IsNotEmpty)
{
SyntaxNodeOrToken value;
if (stack.TryGetNextInSpan(in span, out value))
{
if (value.AsNode(out var nodeValue))
{
stack.PushChildren(nodeValue, descendIntoChildren);
}
else if (value.IsToken)
{
var token = value.AsToken();
foreach (var trivia in token.LeadingTrivia)
{
if (IsInSpan(in span, trivia.FullSpan))
{
yield return trivia;
}
}
foreach (var trivia in token.TrailingTrivia)
{
if (IsInSpan(in span, trivia.FullSpan))
{
yield return trivia;
}
}
}
}
}
}
}
private IEnumerable<SyntaxTrivia> DescendantTriviaIntoTrivia(TextSpan span, Func<SyntaxNode, bool>? descendIntoChildren)
{
using (var stack = new TwoEnumeratorListStack(this, descendIntoChildren))
{
while (stack.IsNotEmpty)
{
switch (stack.PeekNext())
{
case TwoEnumeratorListStack.Which.Node:
SyntaxNodeOrToken value;
if (stack.TryGetNextInSpan(in span, out value))
{
if (value.AsNode(out var nodeValue))
{
stack.PushChildren(nodeValue, descendIntoChildren);
}
else if (value.IsToken)
{
var token = value.AsToken();
if (token.HasTrailingTrivia)
{
stack.PushTrailingTrivia(in token);
}
if (token.HasLeadingTrivia)
{
stack.PushLeadingTrivia(in token);
}
}
}
break;
case TwoEnumeratorListStack.Which.Trivia:
// yield structure nodes and enumerate their children
SyntaxTrivia trivia;
if (stack.TryGetNext(out trivia))
{
// PERF: Push before yield return so that "trivia" is 'dead' after the yield
// and therefore doesn't need to be stored in the iterator state machine. This
// saves a field.
if (trivia.TryGetStructure(out var structureNode))
{
stack.PushChildren(structureNode, descendIntoChildren);
}
if (IsInSpan(in span, trivia.FullSpan))
{
yield return trivia;
}
}
break;
}
}
}
}
}
}
| -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/Core/Impl/CodeModel/ParentHandle.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal struct ParentHandle<T>
{
private readonly ComHandle<object, object> _comHandle;
public ParentHandle(T parent)
=> _comHandle = new ComHandle<object, object>(parent);
public T Value
{
get { return (T)_comHandle.Object; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal struct ParentHandle<T>
{
private readonly ComHandle<object, object> _comHandle;
public ParentHandle(T parent)
=> _comHandle = new ComHandle<object, object>(parent);
public T Value
{
get { return (T)_comHandle.Object; }
}
}
}
| -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/CSharpTest/Wrapping/ParameterWrappingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.Wrapping;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping
{
public class ParameterWrappingTests : AbstractWrappingTests
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpWrappingCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSyntaxError()
{
await TestMissingAsync(
@"class C {
void Goo([||]int i, int j {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSelection()
{
await TestMissingAsync(
@"class C {
void Goo([|int|] i, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingInBody()
{
await TestMissingAsync(
@"class C {
void Goo(int i, int j) {[||]
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingInAttributes()
{
await TestMissingAsync(
@"class C {
[||][Attr]
void Goo(int i, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithOpenTokenTrailingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]/**/int i, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithItemLeadingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]
/**/int i, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithItemTrailingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]
int i/**/, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithCommaTrailingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]
int i,/**/int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithLastItemTrailingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]
int i, int j/**/
) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithCloseTokenLeadingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]
int i, int j
/**/) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestWithOpenTokenLeadingComment()
{
await TestInRegularAndScript1Async(
@"class C {
void Goo/**/([||]int i, int j) {
}
}",
@"class C {
void Goo/**/(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestWithCloseTokenTrailingComment()
{
await TestInRegularAndScript1Async(
@"class C {
void Goo([||]int i, int j)/**/ {
}
}",
@"class C {
void Goo(int i,
int j)/**/ {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSingleParameter()
{
await TestMissingAsync(
@"class C {
void Goo([||]int i) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithMultiLineParameter()
{
await TestMissingAsync(
@"class C {
void Goo([||]int i, int j =
initializer) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInHeader1()
{
await TestInRegularAndScript1Async(
@"class C {
[||]void Goo(int i, int j) {
}
}",
@"class C {
void Goo(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInHeader2()
{
await TestInRegularAndScript1Async(
@"class C {
void [||]Goo(int i, int j) {
}
}",
@"class C {
void Goo(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInHeader3()
{
await TestInRegularAndScript1Async(
@"class C {
[||]public void Goo(int i, int j) {
}
}",
@"class C {
public void Goo(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInHeader4()
{
await TestInRegularAndScript1Async(
@"class C {
public void Goo(int i, int j)[||] {
}
}",
@"class C {
public void Goo(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestTwoParamWrappingCases()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]int i, int j) {
}
}",
@"class C {
void Goo(int i,
int j) {
}
}",
@"class C {
void Goo(
int i,
int j) {
}
}",
@"class C {
void Goo(int i,
int j) {
}
}",
@"class C {
void Goo(
int i, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestThreeParamWrappingCases()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]int i, int j, int k) {
}
}",
@"class C {
void Goo(int i,
int j,
int k) {
}
}",
@"class C {
void Goo(
int i,
int j,
int k) {
}
}",
@"class C {
void Goo(int i,
int j,
int k) {
}
}",
@"class C {
void Goo(
int i, int j, int k) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_AllOptions_NoInitialMatches()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int i,
int j,
int k) {
}
}",
@"class C {
void Goo(int i,
int j,
int k) {
}
}",
@"class C {
void Goo(
int i,
int j,
int k) {
}
}",
@"class C {
void Goo(int i,
int j,
int k) {
}
}",
@"class C {
void Goo(int i, int j, int k) {
}
}",
@"class C {
void Goo(
int i, int j, int k) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_LongWrapping_ShortIds()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int i, int j, int k, int l, int m,
int n) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(int i,
int j,
int k,
int l,
int m,
int n) {
}
}",
@"class C {
void Goo(
int i,
int j,
int k,
int l,
int m,
int n) {
}
}",
@"class C {
void Goo(int i,
int j,
int k,
int l,
int m,
int n) {
}
}",
@"class C {
void Goo(int i, int j, int k, int l, int m, int n) {
}
}",
@"class C {
void Goo(
int i, int j, int k, int l, int m, int n) {
}
}",
@"class C {
void Goo(int i, int j,
int k, int l,
int m, int n) {
}
}",
@"class C {
void Goo(
int i, int j, int k,
int l, int m, int n) {
}
}",
@"class C {
void Goo(int i, int j,
int k, int l, int m,
int n) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_LongWrapping_VariadicLengthIds()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(int i,
int jj,
int kkkk,
int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(
int i,
int jj,
int kkkk,
int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(int i,
int jj,
int kkkk,
int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(
int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk,
int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(
int i, int jj,
int kkkk, int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm,
int nnnnn) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(
int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) {
}
}",
@"class C {
void Goo(
int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) {
}
}",
@"class C {
void Goo(
int iiiii, int jjjjj,
int kkkkk, int lllll,
int mmmmm, int nnnnn) {
}
}",
@"class C {
void Goo(int iiiii,
int jjjjj, int kkkkk,
int lllll, int mmmmm,
int nnnnn) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm,
int nnnnn) {
}
}",
GetIndentionColumn(20),
@"class C {
void Goo(int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(
int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) {
}
}",
@"class C {
void Goo(
int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_LongWrapping_VariadicLengthIds2()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int i, int jj, int kkkk, int lll, int mm,
int n) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(
int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferExistingOption1()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(
int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferExistingOption2()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInConstructor()
{
await TestInRegularAndScript1Async(
@"class C {
public [||]C(int i, int j) {
}
}",
@"class C {
public C(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIndexer()
{
await TestInRegularAndScript1Async(
@"class C {
public int [||]this[int i, int j] => 0;
}",
@"class C {
public int this[int i,
int j] => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInOperator()
{
await TestInRegularAndScript1Async(
@"class C {
public shared int operator [||]+(C c1, C c2) => 0;
}",
@"class C {
public shared int operator +(C c1,
C c2) => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInDelegate()
{
await TestInRegularAndScript1Async(
@"class C {
public delegate int [||]D(C c1, C c2);
}",
@"class C {
public delegate int D(C c1,
C c2);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInParenthesizedLambda()
{
await TestInRegularAndScript1Async(
@"class C {
void Goo()
{
var v = ([||]C c, C d) => {
};
}
}",
@"class C {
void Goo()
{
var v = (C c,
C d) => {
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInParenthesizedLambda2()
{
await TestInRegularAndScript1Async(
@"class C {
void Goo()
{
var v = ([||]c, d) => {
};
}
}",
@"class C {
void Goo()
{
var v = (c,
d) => {
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestNotOnSimpleLambda()
{
await TestMissingAsync(
@"class C {
void Goo()
{
var v = [||]c => {
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestLocalFunction()
{
await TestInRegularAndScript1Async(
@"class C {
void Goo()
{
void Local([||]C c, C d) {
}
}
}",
@"class C {
void Goo()
{
void Local(C c,
C d) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestRecord_Semicolon()
{
await TestInRegularAndScript1Async(
"record R([||]int I, string S);",
@"record R(int I,
string S);");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestRecord_Braces()
{
await TestInRegularAndScript1Async(
"record R([||]int I, string S) { }",
@"record R(int I,
string S) { }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestRecordStruct_Semicolon()
{
await TestInRegularAndScript1Async(
"record struct R([||]int I, string S);",
@"record struct R(int I,
string S);", new TestParameters(TestOptions.RegularPreview));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestRecordStruct_Braces()
{
await TestInRegularAndScript1Async(
"record struct R([||]int I, string S) { }",
@"record struct R(int I,
string S) { }", new TestParameters(TestOptions.RegularPreview));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.Wrapping;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Wrapping
{
public class ParameterWrappingTests : AbstractWrappingTests
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new CSharpWrappingCodeRefactoringProvider();
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSyntaxError()
{
await TestMissingAsync(
@"class C {
void Goo([||]int i, int j {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSelection()
{
await TestMissingAsync(
@"class C {
void Goo([|int|] i, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingInBody()
{
await TestMissingAsync(
@"class C {
void Goo(int i, int j) {[||]
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingInAttributes()
{
await TestMissingAsync(
@"class C {
[||][Attr]
void Goo(int i, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithOpenTokenTrailingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]/**/int i, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithItemLeadingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]
/**/int i, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithItemTrailingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]
int i/**/, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithCommaTrailingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]
int i,/**/int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithLastItemTrailingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]
int i, int j/**/
) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithCloseTokenLeadingComment()
{
await TestMissingAsync(
@"class C {
void Goo([||]
int i, int j
/**/) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestWithOpenTokenLeadingComment()
{
await TestInRegularAndScript1Async(
@"class C {
void Goo/**/([||]int i, int j) {
}
}",
@"class C {
void Goo/**/(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestWithCloseTokenTrailingComment()
{
await TestInRegularAndScript1Async(
@"class C {
void Goo([||]int i, int j)/**/ {
}
}",
@"class C {
void Goo(int i,
int j)/**/ {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithSingleParameter()
{
await TestMissingAsync(
@"class C {
void Goo([||]int i) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestMissingWithMultiLineParameter()
{
await TestMissingAsync(
@"class C {
void Goo([||]int i, int j =
initializer) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInHeader1()
{
await TestInRegularAndScript1Async(
@"class C {
[||]void Goo(int i, int j) {
}
}",
@"class C {
void Goo(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInHeader2()
{
await TestInRegularAndScript1Async(
@"class C {
void [||]Goo(int i, int j) {
}
}",
@"class C {
void Goo(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInHeader3()
{
await TestInRegularAndScript1Async(
@"class C {
[||]public void Goo(int i, int j) {
}
}",
@"class C {
public void Goo(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInHeader4()
{
await TestInRegularAndScript1Async(
@"class C {
public void Goo(int i, int j)[||] {
}
}",
@"class C {
public void Goo(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestTwoParamWrappingCases()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]int i, int j) {
}
}",
@"class C {
void Goo(int i,
int j) {
}
}",
@"class C {
void Goo(
int i,
int j) {
}
}",
@"class C {
void Goo(int i,
int j) {
}
}",
@"class C {
void Goo(
int i, int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestThreeParamWrappingCases()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]int i, int j, int k) {
}
}",
@"class C {
void Goo(int i,
int j,
int k) {
}
}",
@"class C {
void Goo(
int i,
int j,
int k) {
}
}",
@"class C {
void Goo(int i,
int j,
int k) {
}
}",
@"class C {
void Goo(
int i, int j, int k) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_AllOptions_NoInitialMatches()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int i,
int j,
int k) {
}
}",
@"class C {
void Goo(int i,
int j,
int k) {
}
}",
@"class C {
void Goo(
int i,
int j,
int k) {
}
}",
@"class C {
void Goo(int i,
int j,
int k) {
}
}",
@"class C {
void Goo(int i, int j, int k) {
}
}",
@"class C {
void Goo(
int i, int j, int k) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_LongWrapping_ShortIds()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int i, int j, int k, int l, int m,
int n) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(int i,
int j,
int k,
int l,
int m,
int n) {
}
}",
@"class C {
void Goo(
int i,
int j,
int k,
int l,
int m,
int n) {
}
}",
@"class C {
void Goo(int i,
int j,
int k,
int l,
int m,
int n) {
}
}",
@"class C {
void Goo(int i, int j, int k, int l, int m, int n) {
}
}",
@"class C {
void Goo(
int i, int j, int k, int l, int m, int n) {
}
}",
@"class C {
void Goo(int i, int j,
int k, int l,
int m, int n) {
}
}",
@"class C {
void Goo(
int i, int j, int k,
int l, int m, int n) {
}
}",
@"class C {
void Goo(int i, int j,
int k, int l, int m,
int n) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_LongWrapping_VariadicLengthIds()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(int i,
int jj,
int kkkk,
int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(
int i,
int jj,
int kkkk,
int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(int i,
int jj,
int kkkk,
int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(
int i, int jj, int kkkk, int llllllll, int mmmmmmmmmmmmmmmm, int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk,
int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(
int i, int jj,
int kkkk, int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int llllllll,
int mmmmmmmmmmmmmmmm,
int nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferLongWrappingOptionThatAlreadyAppeared()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm,
int nnnnn) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(
int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) {
}
}",
@"class C {
void Goo(
int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) {
}
}",
@"class C {
void Goo(
int iiiii, int jjjjj,
int kkkkk, int lllll,
int mmmmm, int nnnnn) {
}
}",
@"class C {
void Goo(int iiiii,
int jjjjj, int kkkkk,
int lllll, int mmmmm,
int nnnnn) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferAllLongWrappingOptionThatAlreadyAppeared()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm,
int nnnnn) {
}
}",
GetIndentionColumn(20),
@"class C {
void Goo(int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(
int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(int iiiii,
int jjjjj,
int kkkkk,
int lllll,
int mmmmm,
int nnnnn) {
}
}",
@"class C {
void Goo(int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) {
}
}",
@"class C {
void Goo(
int iiiii, int jjjjj, int kkkkk, int lllll, int mmmmm, int nnnnn) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_LongWrapping_VariadicLengthIds2()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int i, int jj, int kkkk, int lll, int mm,
int n) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(
int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferExistingOption1()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(
int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task Test_DoNotOfferExistingOption2()
{
await TestAllWrappingCasesAsync(
@"class C {
void Goo([||]
int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
GetIndentionColumn(30),
@"class C {
void Goo(int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i,
int jj,
int kkkk,
int lll,
int mm,
int n) {
}
}",
@"class C {
void Goo(int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj, int kkkk, int lll, int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(
int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}",
@"class C {
void Goo(int i, int jj,
int kkkk, int lll,
int mm, int n) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInConstructor()
{
await TestInRegularAndScript1Async(
@"class C {
public [||]C(int i, int j) {
}
}",
@"class C {
public C(int i,
int j) {
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInIndexer()
{
await TestInRegularAndScript1Async(
@"class C {
public int [||]this[int i, int j] => 0;
}",
@"class C {
public int this[int i,
int j] => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInOperator()
{
await TestInRegularAndScript1Async(
@"class C {
public shared int operator [||]+(C c1, C c2) => 0;
}",
@"class C {
public shared int operator +(C c1,
C c2) => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInDelegate()
{
await TestInRegularAndScript1Async(
@"class C {
public delegate int [||]D(C c1, C c2);
}",
@"class C {
public delegate int D(C c1,
C c2);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInParenthesizedLambda()
{
await TestInRegularAndScript1Async(
@"class C {
void Goo()
{
var v = ([||]C c, C d) => {
};
}
}",
@"class C {
void Goo()
{
var v = (C c,
C d) => {
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestInParenthesizedLambda2()
{
await TestInRegularAndScript1Async(
@"class C {
void Goo()
{
var v = ([||]c, d) => {
};
}
}",
@"class C {
void Goo()
{
var v = (c,
d) => {
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestNotOnSimpleLambda()
{
await TestMissingAsync(
@"class C {
void Goo()
{
var v = [||]c => {
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestLocalFunction()
{
await TestInRegularAndScript1Async(
@"class C {
void Goo()
{
void Local([||]C c, C d) {
}
}
}",
@"class C {
void Goo()
{
void Local(C c,
C d) {
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestRecord_Semicolon()
{
await TestInRegularAndScript1Async(
"record R([||]int I, string S);",
@"record R(int I,
string S);");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestRecord_Braces()
{
await TestInRegularAndScript1Async(
"record R([||]int I, string S) { }",
@"record R(int I,
string S) { }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestRecordStruct_Semicolon()
{
await TestInRegularAndScript1Async(
"record struct R([||]int I, string S);",
@"record struct R(int I,
string S);", new TestParameters(TestOptions.RegularPreview));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)]
public async Task TestRecordStruct_Braces()
{
await TestInRegularAndScript1Async(
"record struct R([||]int I, string S) { }",
@"record struct R(int I,
string S) { }", new TestParameters(TestOptions.RegularPreview));
}
}
}
| -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/Operations/ControlFlowBranch.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
/// <summary>
/// Represents a control flow branch from a <see cref="Source"/> basic block to a <see cref="Destination"/>
/// basic block in a <see cref="ControlFlowGraph"/>.
/// </summary>
public sealed class ControlFlowBranch
{
private ImmutableArray<ControlFlowRegion> _lazyLeavingRegions;
private ImmutableArray<ControlFlowRegion> _lazyFinallyRegions;
private ImmutableArray<ControlFlowRegion> _lazyEnteringRegions;
internal ControlFlowBranch(
BasicBlock source,
BasicBlock? destination,
ControlFlowBranchSemantics semantics,
bool isConditionalSuccessor)
{
Source = source;
Destination = destination;
Semantics = semantics;
IsConditionalSuccessor = isConditionalSuccessor;
}
/// <summary>
/// Source basic block of this branch.
/// </summary>
public BasicBlock Source { get; }
/// <summary>
/// Destination basic block of this branch.
/// </summary>
public BasicBlock? Destination { get; }
/// <summary>
/// Semantics associated with this branch (such as "regular", "return", "throw", etc).
/// </summary>
public ControlFlowBranchSemantics Semantics { get; }
/// <summary>
/// Indicates if this branch represents <see cref="BasicBlock.ConditionalSuccessor"/> of the <see cref="Source"/> basic block.
/// </summary>
public bool IsConditionalSuccessor { get; }
/// <summary>
/// Regions exited if this branch is taken.
/// Ordered from the innermost region to the outermost region.
/// </summary>
public ImmutableArray<ControlFlowRegion> LeavingRegions
{
get
{
if (_lazyLeavingRegions.IsDefault)
{
ImmutableArray<ControlFlowRegion> result;
if (Destination == null)
{
result = ImmutableArray<ControlFlowRegion>.Empty;
}
else
{
result = CollectRegions(Destination.Ordinal, Source.EnclosingRegion).ToImmutableAndFree();
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyLeavingRegions, result);
}
return _lazyLeavingRegions;
}
}
private static ArrayBuilder<ControlFlowRegion> CollectRegions(int destinationOrdinal, ControlFlowRegion source)
{
var builder = ArrayBuilder<ControlFlowRegion>.GetInstance();
while (!source.ContainsBlock(destinationOrdinal))
{
Debug.Assert(source.Kind != ControlFlowRegionKind.Root);
Debug.Assert(source.EnclosingRegion != null);
builder.Add(source);
source = source.EnclosingRegion;
}
return builder;
}
/// <summary>
/// Regions entered if this branch is taken.
/// Ordered from the outermost region to the innermost region.
/// </summary>
public ImmutableArray<ControlFlowRegion> EnteringRegions
{
get
{
if (_lazyEnteringRegions.IsDefault)
{
ImmutableArray<ControlFlowRegion> result;
if (Destination == null)
{
result = ImmutableArray<ControlFlowRegion>.Empty;
}
else
{
ArrayBuilder<ControlFlowRegion> builder = CollectRegions(Source.Ordinal, Destination.EnclosingRegion);
builder.ReverseContents();
result = builder.ToImmutableAndFree();
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyEnteringRegions, result);
}
return _lazyEnteringRegions;
}
}
/// <summary>
/// The finally regions the control goes through if this branch is taken.
/// Ordered in the sequence by which the finally regions are executed.
/// </summary>
public ImmutableArray<ControlFlowRegion> FinallyRegions
{
get
{
if (_lazyFinallyRegions.IsDefault)
{
ArrayBuilder<ControlFlowRegion>? builder = null;
ImmutableArray<ControlFlowRegion> leavingRegions = LeavingRegions;
int stopAt = leavingRegions.Length - 1;
for (int i = 0; i < stopAt; i++)
{
if (leavingRegions[i].Kind == ControlFlowRegionKind.Try && leavingRegions[i + 1].Kind == ControlFlowRegionKind.TryAndFinally)
{
if (builder == null)
{
builder = ArrayBuilder<ControlFlowRegion>.GetInstance();
}
builder.Add(leavingRegions[i + 1].NestedRegions.Last());
Debug.Assert(builder.Last().Kind == ControlFlowRegionKind.Finally);
}
}
var result = builder == null ? ImmutableArray<ControlFlowRegion>.Empty : builder.ToImmutableAndFree();
ImmutableInterlocked.InterlockedInitialize(ref _lazyFinallyRegions, result);
}
return _lazyFinallyRegions;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
/// <summary>
/// Represents a control flow branch from a <see cref="Source"/> basic block to a <see cref="Destination"/>
/// basic block in a <see cref="ControlFlowGraph"/>.
/// </summary>
public sealed class ControlFlowBranch
{
private ImmutableArray<ControlFlowRegion> _lazyLeavingRegions;
private ImmutableArray<ControlFlowRegion> _lazyFinallyRegions;
private ImmutableArray<ControlFlowRegion> _lazyEnteringRegions;
internal ControlFlowBranch(
BasicBlock source,
BasicBlock? destination,
ControlFlowBranchSemantics semantics,
bool isConditionalSuccessor)
{
Source = source;
Destination = destination;
Semantics = semantics;
IsConditionalSuccessor = isConditionalSuccessor;
}
/// <summary>
/// Source basic block of this branch.
/// </summary>
public BasicBlock Source { get; }
/// <summary>
/// Destination basic block of this branch.
/// </summary>
public BasicBlock? Destination { get; }
/// <summary>
/// Semantics associated with this branch (such as "regular", "return", "throw", etc).
/// </summary>
public ControlFlowBranchSemantics Semantics { get; }
/// <summary>
/// Indicates if this branch represents <see cref="BasicBlock.ConditionalSuccessor"/> of the <see cref="Source"/> basic block.
/// </summary>
public bool IsConditionalSuccessor { get; }
/// <summary>
/// Regions exited if this branch is taken.
/// Ordered from the innermost region to the outermost region.
/// </summary>
public ImmutableArray<ControlFlowRegion> LeavingRegions
{
get
{
if (_lazyLeavingRegions.IsDefault)
{
ImmutableArray<ControlFlowRegion> result;
if (Destination == null)
{
result = ImmutableArray<ControlFlowRegion>.Empty;
}
else
{
result = CollectRegions(Destination.Ordinal, Source.EnclosingRegion).ToImmutableAndFree();
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyLeavingRegions, result);
}
return _lazyLeavingRegions;
}
}
private static ArrayBuilder<ControlFlowRegion> CollectRegions(int destinationOrdinal, ControlFlowRegion source)
{
var builder = ArrayBuilder<ControlFlowRegion>.GetInstance();
while (!source.ContainsBlock(destinationOrdinal))
{
Debug.Assert(source.Kind != ControlFlowRegionKind.Root);
Debug.Assert(source.EnclosingRegion != null);
builder.Add(source);
source = source.EnclosingRegion;
}
return builder;
}
/// <summary>
/// Regions entered if this branch is taken.
/// Ordered from the outermost region to the innermost region.
/// </summary>
public ImmutableArray<ControlFlowRegion> EnteringRegions
{
get
{
if (_lazyEnteringRegions.IsDefault)
{
ImmutableArray<ControlFlowRegion> result;
if (Destination == null)
{
result = ImmutableArray<ControlFlowRegion>.Empty;
}
else
{
ArrayBuilder<ControlFlowRegion> builder = CollectRegions(Source.Ordinal, Destination.EnclosingRegion);
builder.ReverseContents();
result = builder.ToImmutableAndFree();
}
ImmutableInterlocked.InterlockedInitialize(ref _lazyEnteringRegions, result);
}
return _lazyEnteringRegions;
}
}
/// <summary>
/// The finally regions the control goes through if this branch is taken.
/// Ordered in the sequence by which the finally regions are executed.
/// </summary>
public ImmutableArray<ControlFlowRegion> FinallyRegions
{
get
{
if (_lazyFinallyRegions.IsDefault)
{
ArrayBuilder<ControlFlowRegion>? builder = null;
ImmutableArray<ControlFlowRegion> leavingRegions = LeavingRegions;
int stopAt = leavingRegions.Length - 1;
for (int i = 0; i < stopAt; i++)
{
if (leavingRegions[i].Kind == ControlFlowRegionKind.Try && leavingRegions[i + 1].Kind == ControlFlowRegionKind.TryAndFinally)
{
if (builder == null)
{
builder = ArrayBuilder<ControlFlowRegion>.GetInstance();
}
builder.Add(leavingRegions[i + 1].NestedRegions.Last());
Debug.Assert(builder.Last().Kind == ControlFlowRegionKind.Finally);
}
}
var result = builder == null ? ImmutableArray<ControlFlowRegion>.Empty : builder.ToImmutableAndFree();
ImmutableInterlocked.InterlockedInitialize(ref _lazyFinallyRegions, result);
}
return _lazyFinallyRegions;
}
}
}
}
| -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/Formatting/CoreFormatterTestsBase.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.Formatting;
using Microsoft.CodeAnalysis.Editor.Implementation.SmartIndent;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
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.Projection;
using Moq;
using Roslyn.Test.EditorUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Formatting
{
public abstract class CoreFormatterTestsBase
{
private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(TestFormattingRuleFactoryServiceFactory));
private readonly ITestOutputHelper _output;
protected CoreFormatterTestsBase(ITestOutputHelper output)
=> _output = output;
protected abstract string GetLanguageName();
protected abstract SyntaxNode ParseCompilationUnit(string expected);
protected static void TestIndentation(
int point, int? expectedIndentation, ITextView textView, TestHostDocument subjectDocument)
{
var textUndoHistory = new Mock<ITextUndoHistoryRegistry>();
var editorOperationsFactory = new Mock<IEditorOperationsFactoryService>();
var editorOperations = new Mock<IEditorOperations>();
editorOperationsFactory.Setup(x => x.GetEditorOperations(textView)).Returns(editorOperations.Object);
var snapshot = subjectDocument.GetTextBuffer().CurrentSnapshot;
var indentationLineFromBuffer = snapshot.GetLineFromPosition(point);
var provider = new SmartIndent(textView);
var actualIndentation = provider.GetDesiredIndentation(indentationLineFromBuffer);
Assert.Equal(expectedIndentation, actualIndentation.Value);
}
protected static void TestIndentation(TestWorkspace workspace, int indentationLine, int? expectedIndentation)
{
var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot;
var bufferGraph = new Mock<IBufferGraph>(MockBehavior.Strict);
bufferGraph.Setup(x => x.MapUpToSnapshot(It.IsAny<SnapshotPoint>(),
It.IsAny<PointTrackingMode>(),
It.IsAny<PositionAffinity>(),
It.IsAny<ITextSnapshot>()))
.Returns<SnapshotPoint, PointTrackingMode, PositionAffinity, ITextSnapshot>((p, m, a, s) =>
{
if (workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>() is TestFormattingRuleFactoryServiceFactory.Factory factory && factory.BaseIndentation != 0 && factory.TextSpan.Contains(p.Position))
{
var line = p.GetContainingLine();
var projectedOffset = line.GetFirstNonWhitespaceOffset().Value - factory.BaseIndentation;
return new SnapshotPoint(p.Snapshot, p.Position - projectedOffset);
}
return p;
});
var projectionBuffer = new Mock<ITextBuffer>(MockBehavior.Strict);
projectionBuffer.Setup(x => x.ContentType.DisplayName).Returns("None");
var textView = new Mock<ITextView>(MockBehavior.Strict);
textView.Setup(x => x.Options).Returns(TestEditorOptions.Instance);
textView.Setup(x => x.BufferGraph).Returns(bufferGraph.Object);
textView.SetupGet(x => x.TextSnapshot.TextBuffer).Returns(projectionBuffer.Object);
var provider = new SmartIndent(textView.Object);
var indentationLineFromBuffer = snapshot.GetLineFromLineNumber(indentationLine);
var actualIndentation = provider.GetDesiredIndentation(indentationLineFromBuffer);
Assert.Equal(expectedIndentation, actualIndentation);
}
private protected void AssertFormatWithView(string expectedWithMarker, string codeWithMarker, params (PerLanguageOption2<bool> option, bool enabled)[] options)
{
using var workspace = CreateWorkspace(codeWithMarker);
if (options != null)
{
var optionSet = workspace.Options;
foreach (var option in options)
{
optionSet = optionSet.WithChangedOption(option.option, GetLanguageName(), option.enabled);
}
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet));
}
// set up caret position
var testDocument = workspace.Documents.Single();
var view = testDocument.GetTextView();
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
// get original buffer
var buffer = workspace.Documents.First().GetTextBuffer();
var commandHandler = workspace.GetService<FormatCommandHandler>();
var commandArgs = new FormatDocumentCommandArgs(view, view.TextBuffer);
commandHandler.ExecuteCommand(commandArgs, TestCommandExecutionContext.Create());
MarkupTestFile.GetPosition(expectedWithMarker, out var expected, out int expectedPosition);
Assert.Equal(expected, view.TextSnapshot.GetText());
var caretPosition = view.Caret.Position.BufferPosition.Position;
Assert.True(expectedPosition == caretPosition,
string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition));
}
private TestWorkspace CreateWorkspace(string codeWithMarker)
=> this.GetLanguageName() == LanguageNames.CSharp
? TestWorkspace.CreateCSharp(codeWithMarker, composition: s_composition)
: TestWorkspace.CreateVisualBasic(codeWithMarker, composition: s_composition);
internal void AssertFormatWithTransformation(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, SyntaxNode root)
{
var newRootNode = Formatter.Format(root, SpecializedCollections.SingletonEnumerable(root.FullSpan), workspace, optionSet, rules, CancellationToken.None);
Assert.Equal(expected, newRootNode.ToFullString());
// test doesn't use parsing option. add one if needed later
var newRootNodeFromString = ParseCompilationUnit(expected);
// simple check to see whether two nodes are equivalent each other.
Assert.True(newRootNodeFromString.IsEquivalentTo(newRootNode));
}
internal static void AssertFormat(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, ITextBuffer clonedBuffer, SyntaxNode root)
{
var changes = Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(root.FullSpan), workspace, optionSet, rules, CancellationToken.None);
var actual = ApplyResultAndGetFormattedText(clonedBuffer, changes);
Assert.Equal(expected, actual);
}
private static string ApplyResultAndGetFormattedText(ITextBuffer buffer, IList<TextChange> changes)
{
using (var edit = buffer.CreateEdit())
{
foreach (var change in changes)
{
edit.Replace(change.Span.ToSpan(), change.NewText);
}
edit.Apply();
}
return buffer.CurrentSnapshot.GetText();
}
protected async Task AssertFormatAsync(string expected, string code, IEnumerable<TextSpan> spans, Dictionary<OptionKey, object> changedOptionSet = null, int? baseIndentation = null)
{
using var workspace = CreateWorkspace(code);
var hostdoc = workspace.Documents.First();
var buffer = hostdoc.GetTextBuffer();
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var syntaxTree = await document.GetSyntaxTreeAsync();
// create new buffer with cloned content
var clonedBuffer = EditorFactory.CreateBuffer(
workspace.ExportProvider,
buffer.ContentType,
buffer.CurrentSnapshot.GetText());
var formattingRuleProvider = workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>();
if (baseIndentation.HasValue)
{
var factory = (TestFormattingRuleFactoryServiceFactory.Factory)formattingRuleProvider;
factory.BaseIndentation = baseIndentation.Value;
factory.TextSpan = spans.First();
}
var options = workspace.Options;
if (changedOptionSet != null)
{
foreach (var entry in changedOptionSet)
{
options = options.WithChangedOption(entry.Key, entry.Value);
}
}
var root = await syntaxTree.GetRootAsync();
var rules = formattingRuleProvider.CreateRule(workspace.CurrentSolution.GetDocument(syntaxTree), 0).Concat(Formatter.GetDefaultFormattingRules(workspace, root.Language));
AssertFormat(workspace, expected, options, rules, clonedBuffer, root, spans);
// format with node and transform
AssertFormatWithTransformation(workspace, expected, options, rules, root, spans);
}
internal void AssertFormatWithTransformation(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, SyntaxNode root, IEnumerable<TextSpan> spans)
{
var newRootNode = Formatter.Format(root, spans, workspace, optionSet, rules, CancellationToken.None);
Assert.Equal(expected, newRootNode.ToFullString());
// test doesn't use parsing option. add one if needed later
var newRootNodeFromString = ParseCompilationUnit(expected);
// simple check to see whether two nodes are equivalent each other.
Assert.True(newRootNodeFromString.IsEquivalentTo(newRootNode));
}
internal void AssertFormat(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, ITextBuffer clonedBuffer, SyntaxNode root, IEnumerable<TextSpan> spans)
{
var result = Formatter.GetFormattedTextChanges(root, spans, workspace, optionSet, rules, CancellationToken.None);
var actual = ApplyResultAndGetFormattedText(clonedBuffer, result);
if (actual != expected)
{
_output.WriteLine(actual);
Assert.Equal(expected, actual);
}
}
protected void AssertFormatWithPasteOrReturn(string expectedWithMarker, string codeWithMarker, bool allowDocumentChanges, bool isPaste = true)
{
using var workspace = CreateWorkspace(codeWithMarker);
workspace.CanApplyChangeDocument = allowDocumentChanges;
// set up caret position
var testDocument = workspace.Documents.Single();
var view = testDocument.GetTextView();
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
// get original buffer
var buffer = workspace.Documents.First().GetTextBuffer();
if (isPaste)
{
var commandHandler = workspace.GetService<FormatCommandHandler>();
var commandArgs = new PasteCommandArgs(view, view.TextBuffer);
commandHandler.ExecuteCommand(commandArgs, () => { }, TestCommandExecutionContext.Create());
}
else
{
// Return Key Command
var commandHandler = workspace.GetService<FormatCommandHandler>();
var commandArgs = new ReturnKeyCommandArgs(view, view.TextBuffer);
commandHandler.ExecuteCommand(commandArgs, () => { }, TestCommandExecutionContext.Create());
}
MarkupTestFile.GetPosition(expectedWithMarker, out var expected, out int expectedPosition);
Assert.Equal(expected, view.TextSnapshot.GetText());
var caretPosition = view.Caret.Position.BufferPosition.Position;
Assert.True(expectedPosition == caretPosition,
string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition));
}
protected async Task AssertFormatWithBaseIndentAsync(
string expected, string markupCode, int baseIndentation,
Dictionary<OptionKey, object> options = null)
{
MarkupTestFile.GetSpan(markupCode, out var code, out var span);
await AssertFormatAsync(
expected,
code,
new List<TextSpan> { span },
changedOptionSet: options,
baseIndentation: baseIndentation);
}
/// <summary>
/// Asserts formatting on an arbitrary <see cref="SyntaxNode"/> that is not part of a <see cref="SyntaxTree"/>
/// </summary>
/// <param name="node">the <see cref="SyntaxNode"/> to format.</param>
/// <remarks>uses an <see cref="AdhocWorkspace"/> for formatting context, since the <paramref name="node"/> is not associated with a <see cref="SyntaxTree"/> </remarks>
protected static void AssertFormatOnArbitraryNode(SyntaxNode node, string expected)
{
var result = Formatter.Format(node, new AdhocWorkspace());
var actual = result.GetText().ToString();
Assert.Equal(expected, actual);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.Formatting;
using Microsoft.CodeAnalysis.Editor.Implementation.SmartIndent;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
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.Projection;
using Moq;
using Roslyn.Test.EditorUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Formatting
{
public abstract class CoreFormatterTestsBase
{
private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(TestFormattingRuleFactoryServiceFactory));
private readonly ITestOutputHelper _output;
protected CoreFormatterTestsBase(ITestOutputHelper output)
=> _output = output;
protected abstract string GetLanguageName();
protected abstract SyntaxNode ParseCompilationUnit(string expected);
protected static void TestIndentation(
int point, int? expectedIndentation, ITextView textView, TestHostDocument subjectDocument)
{
var textUndoHistory = new Mock<ITextUndoHistoryRegistry>();
var editorOperationsFactory = new Mock<IEditorOperationsFactoryService>();
var editorOperations = new Mock<IEditorOperations>();
editorOperationsFactory.Setup(x => x.GetEditorOperations(textView)).Returns(editorOperations.Object);
var snapshot = subjectDocument.GetTextBuffer().CurrentSnapshot;
var indentationLineFromBuffer = snapshot.GetLineFromPosition(point);
var provider = new SmartIndent(textView);
var actualIndentation = provider.GetDesiredIndentation(indentationLineFromBuffer);
Assert.Equal(expectedIndentation, actualIndentation.Value);
}
protected static void TestIndentation(TestWorkspace workspace, int indentationLine, int? expectedIndentation)
{
var snapshot = workspace.Documents.First().GetTextBuffer().CurrentSnapshot;
var bufferGraph = new Mock<IBufferGraph>(MockBehavior.Strict);
bufferGraph.Setup(x => x.MapUpToSnapshot(It.IsAny<SnapshotPoint>(),
It.IsAny<PointTrackingMode>(),
It.IsAny<PositionAffinity>(),
It.IsAny<ITextSnapshot>()))
.Returns<SnapshotPoint, PointTrackingMode, PositionAffinity, ITextSnapshot>((p, m, a, s) =>
{
if (workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>() is TestFormattingRuleFactoryServiceFactory.Factory factory && factory.BaseIndentation != 0 && factory.TextSpan.Contains(p.Position))
{
var line = p.GetContainingLine();
var projectedOffset = line.GetFirstNonWhitespaceOffset().Value - factory.BaseIndentation;
return new SnapshotPoint(p.Snapshot, p.Position - projectedOffset);
}
return p;
});
var projectionBuffer = new Mock<ITextBuffer>(MockBehavior.Strict);
projectionBuffer.Setup(x => x.ContentType.DisplayName).Returns("None");
var textView = new Mock<ITextView>(MockBehavior.Strict);
textView.Setup(x => x.Options).Returns(TestEditorOptions.Instance);
textView.Setup(x => x.BufferGraph).Returns(bufferGraph.Object);
textView.SetupGet(x => x.TextSnapshot.TextBuffer).Returns(projectionBuffer.Object);
var provider = new SmartIndent(textView.Object);
var indentationLineFromBuffer = snapshot.GetLineFromLineNumber(indentationLine);
var actualIndentation = provider.GetDesiredIndentation(indentationLineFromBuffer);
Assert.Equal(expectedIndentation, actualIndentation);
}
private protected void AssertFormatWithView(string expectedWithMarker, string codeWithMarker, params (PerLanguageOption2<bool> option, bool enabled)[] options)
{
using var workspace = CreateWorkspace(codeWithMarker);
if (options != null)
{
var optionSet = workspace.Options;
foreach (var option in options)
{
optionSet = optionSet.WithChangedOption(option.option, GetLanguageName(), option.enabled);
}
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet));
}
// set up caret position
var testDocument = workspace.Documents.Single();
var view = testDocument.GetTextView();
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
// get original buffer
var buffer = workspace.Documents.First().GetTextBuffer();
var commandHandler = workspace.GetService<FormatCommandHandler>();
var commandArgs = new FormatDocumentCommandArgs(view, view.TextBuffer);
commandHandler.ExecuteCommand(commandArgs, TestCommandExecutionContext.Create());
MarkupTestFile.GetPosition(expectedWithMarker, out var expected, out int expectedPosition);
Assert.Equal(expected, view.TextSnapshot.GetText());
var caretPosition = view.Caret.Position.BufferPosition.Position;
Assert.True(expectedPosition == caretPosition,
string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition));
}
private TestWorkspace CreateWorkspace(string codeWithMarker)
=> this.GetLanguageName() == LanguageNames.CSharp
? TestWorkspace.CreateCSharp(codeWithMarker, composition: s_composition)
: TestWorkspace.CreateVisualBasic(codeWithMarker, composition: s_composition);
internal void AssertFormatWithTransformation(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, SyntaxNode root)
{
var newRootNode = Formatter.Format(root, SpecializedCollections.SingletonEnumerable(root.FullSpan), workspace, optionSet, rules, CancellationToken.None);
Assert.Equal(expected, newRootNode.ToFullString());
// test doesn't use parsing option. add one if needed later
var newRootNodeFromString = ParseCompilationUnit(expected);
// simple check to see whether two nodes are equivalent each other.
Assert.True(newRootNodeFromString.IsEquivalentTo(newRootNode));
}
internal static void AssertFormat(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, ITextBuffer clonedBuffer, SyntaxNode root)
{
var changes = Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(root.FullSpan), workspace, optionSet, rules, CancellationToken.None);
var actual = ApplyResultAndGetFormattedText(clonedBuffer, changes);
Assert.Equal(expected, actual);
}
private static string ApplyResultAndGetFormattedText(ITextBuffer buffer, IList<TextChange> changes)
{
using (var edit = buffer.CreateEdit())
{
foreach (var change in changes)
{
edit.Replace(change.Span.ToSpan(), change.NewText);
}
edit.Apply();
}
return buffer.CurrentSnapshot.GetText();
}
protected async Task AssertFormatAsync(string expected, string code, IEnumerable<TextSpan> spans, Dictionary<OptionKey, object> changedOptionSet = null, int? baseIndentation = null)
{
using var workspace = CreateWorkspace(code);
var hostdoc = workspace.Documents.First();
var buffer = hostdoc.GetTextBuffer();
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var syntaxTree = await document.GetSyntaxTreeAsync();
// create new buffer with cloned content
var clonedBuffer = EditorFactory.CreateBuffer(
workspace.ExportProvider,
buffer.ContentType,
buffer.CurrentSnapshot.GetText());
var formattingRuleProvider = workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>();
if (baseIndentation.HasValue)
{
var factory = (TestFormattingRuleFactoryServiceFactory.Factory)formattingRuleProvider;
factory.BaseIndentation = baseIndentation.Value;
factory.TextSpan = spans.First();
}
var options = workspace.Options;
if (changedOptionSet != null)
{
foreach (var entry in changedOptionSet)
{
options = options.WithChangedOption(entry.Key, entry.Value);
}
}
var root = await syntaxTree.GetRootAsync();
var rules = formattingRuleProvider.CreateRule(workspace.CurrentSolution.GetDocument(syntaxTree), 0).Concat(Formatter.GetDefaultFormattingRules(workspace, root.Language));
AssertFormat(workspace, expected, options, rules, clonedBuffer, root, spans);
// format with node and transform
AssertFormatWithTransformation(workspace, expected, options, rules, root, spans);
}
internal void AssertFormatWithTransformation(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, SyntaxNode root, IEnumerable<TextSpan> spans)
{
var newRootNode = Formatter.Format(root, spans, workspace, optionSet, rules, CancellationToken.None);
Assert.Equal(expected, newRootNode.ToFullString());
// test doesn't use parsing option. add one if needed later
var newRootNodeFromString = ParseCompilationUnit(expected);
// simple check to see whether two nodes are equivalent each other.
Assert.True(newRootNodeFromString.IsEquivalentTo(newRootNode));
}
internal void AssertFormat(Workspace workspace, string expected, OptionSet optionSet, IEnumerable<AbstractFormattingRule> rules, ITextBuffer clonedBuffer, SyntaxNode root, IEnumerable<TextSpan> spans)
{
var result = Formatter.GetFormattedTextChanges(root, spans, workspace, optionSet, rules, CancellationToken.None);
var actual = ApplyResultAndGetFormattedText(clonedBuffer, result);
if (actual != expected)
{
_output.WriteLine(actual);
Assert.Equal(expected, actual);
}
}
protected void AssertFormatWithPasteOrReturn(string expectedWithMarker, string codeWithMarker, bool allowDocumentChanges, bool isPaste = true)
{
using var workspace = CreateWorkspace(codeWithMarker);
workspace.CanApplyChangeDocument = allowDocumentChanges;
// set up caret position
var testDocument = workspace.Documents.Single();
var view = testDocument.GetTextView();
view.Caret.MoveTo(new SnapshotPoint(view.TextSnapshot, testDocument.CursorPosition.Value));
// get original buffer
var buffer = workspace.Documents.First().GetTextBuffer();
if (isPaste)
{
var commandHandler = workspace.GetService<FormatCommandHandler>();
var commandArgs = new PasteCommandArgs(view, view.TextBuffer);
commandHandler.ExecuteCommand(commandArgs, () => { }, TestCommandExecutionContext.Create());
}
else
{
// Return Key Command
var commandHandler = workspace.GetService<FormatCommandHandler>();
var commandArgs = new ReturnKeyCommandArgs(view, view.TextBuffer);
commandHandler.ExecuteCommand(commandArgs, () => { }, TestCommandExecutionContext.Create());
}
MarkupTestFile.GetPosition(expectedWithMarker, out var expected, out int expectedPosition);
Assert.Equal(expected, view.TextSnapshot.GetText());
var caretPosition = view.Caret.Position.BufferPosition.Position;
Assert.True(expectedPosition == caretPosition,
string.Format("Caret positioned incorrectly. Should have been {0}, but was {1}.", expectedPosition, caretPosition));
}
protected async Task AssertFormatWithBaseIndentAsync(
string expected, string markupCode, int baseIndentation,
Dictionary<OptionKey, object> options = null)
{
MarkupTestFile.GetSpan(markupCode, out var code, out var span);
await AssertFormatAsync(
expected,
code,
new List<TextSpan> { span },
changedOptionSet: options,
baseIndentation: baseIndentation);
}
/// <summary>
/// Asserts formatting on an arbitrary <see cref="SyntaxNode"/> that is not part of a <see cref="SyntaxTree"/>
/// </summary>
/// <param name="node">the <see cref="SyntaxNode"/> to format.</param>
/// <remarks>uses an <see cref="AdhocWorkspace"/> for formatting context, since the <paramref name="node"/> is not associated with a <see cref="SyntaxTree"/> </remarks>
protected static void AssertFormatOnArbitraryNode(SyntaxNode node, string expected)
{
var result = Formatter.Format(node, new AdhocWorkspace());
var actual = result.GetText().ToString();
Assert.Equal(expected, actual);
}
}
}
| -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/Core/Portable/Shared/Extensions/INamespaceSymbolExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class INamespaceSymbolExtensions
{
private static readonly ConditionalWeakTable<INamespaceSymbol, List<string>> s_namespaceToNameMap =
new();
public static readonly Comparison<INamespaceSymbol> CompareNamespaces = CompareTo;
public static readonly IEqualityComparer<INamespaceSymbol> EqualityComparer = new Comparer();
private static List<string> GetNameParts(INamespaceSymbol? namespaceSymbol)
{
var result = new List<string>();
GetNameParts(namespaceSymbol, result);
return result;
}
private static void GetNameParts(INamespaceSymbol? namespaceSymbol, List<string> result)
{
if (namespaceSymbol == null || namespaceSymbol.IsGlobalNamespace)
{
return;
}
GetNameParts(namespaceSymbol.ContainingNamespace, result);
result.Add(namespaceSymbol.Name);
}
public static int CompareTo(this INamespaceSymbol n1, INamespaceSymbol n2)
{
var names1 = s_namespaceToNameMap.GetValue(n1, GetNameParts);
var names2 = s_namespaceToNameMap.GetValue(n2, GetNameParts);
for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++)
{
var comp = names1[i].CompareTo(names2[i]);
if (comp != 0)
{
return comp;
}
}
return names1.Count - names2.Count;
}
public static IEnumerable<INamespaceOrTypeSymbol> GetAllNamespacesAndTypes(
this INamespaceSymbol namespaceSymbol,
CancellationToken cancellationToken)
{
var stack = new Stack<INamespaceOrTypeSymbol>();
stack.Push(namespaceSymbol);
while (stack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Pop();
if (current is INamespaceSymbol childNamespace)
{
stack.Push(childNamespace.GetMembers().AsEnumerable());
yield return childNamespace;
}
else
{
var child = (INamedTypeSymbol)current;
stack.Push(child.GetTypeMembers());
yield return child;
}
}
}
public static IEnumerable<INamespaceSymbol> GetAllNamespaces(
this INamespaceSymbol namespaceSymbol,
CancellationToken cancellationToken)
{
var stack = new Stack<INamespaceSymbol>();
stack.Push(namespaceSymbol);
while (stack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Pop();
if (current is INamespaceSymbol childNamespace)
{
stack.Push(childNamespace.GetNamespaceMembers());
yield return childNamespace;
}
}
}
public static IEnumerable<INamedTypeSymbol> GetAllTypes(
this IEnumerable<INamespaceSymbol> namespaceSymbols,
CancellationToken cancellationToken)
{
return namespaceSymbols.SelectMany(n => n.GetAllTypes(cancellationToken));
}
/// <summary>
/// Searches the namespace for namespaces with the provided name.
/// </summary>
public static IEnumerable<INamespaceSymbol> FindNamespaces(
this INamespaceSymbol namespaceSymbol,
string namespaceName,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var stack = new Stack<INamespaceSymbol>();
stack.Push(namespaceSymbol);
while (stack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Pop();
var matchingChildren = current.GetMembers(namespaceName).OfType<INamespaceSymbol>();
foreach (var child in matchingChildren)
{
yield return child;
}
stack.Push(current.GetNamespaceMembers());
}
}
public static bool ContainsAccessibleTypesOrNamespaces(
this INamespaceSymbol namespaceSymbol,
IAssemblySymbol assembly)
{
using var namespaceQueue = SharedPools.Default<Queue<INamespaceOrTypeSymbol>>().GetPooledObject();
return ContainsAccessibleTypesOrNamespacesWorker(namespaceSymbol, assembly, namespaceQueue.Object);
}
public static INamespaceSymbol? GetQualifiedNamespace(
this INamespaceSymbol globalNamespace,
string namespaceName)
{
var namespaceSymbol = globalNamespace;
foreach (var name in namespaceName.Split('.'))
{
var members = namespaceSymbol.GetMembers(name);
namespaceSymbol = members.Count() == 1
? members.First() as INamespaceSymbol
: null;
if (namespaceSymbol is null)
{
break;
}
}
return namespaceSymbol;
}
private static bool ContainsAccessibleTypesOrNamespacesWorker(
this INamespaceSymbol namespaceSymbol,
IAssemblySymbol assembly,
Queue<INamespaceOrTypeSymbol> namespaceQueue)
{
// Note: we only store INamespaceSymbols in here, even though we type it as
// INamespaceOrTypeSymbol. This is because when we call GetMembers below we
// want it to return an ImmutableArray so we don't incur any costs to iterate
// over it.
foreach (var constituent in namespaceSymbol.ConstituentNamespaces)
{
// Assume that any namespace in our own assembly is accessible to us. This saves a
// lot of cpu time checking namespaces.
if (Equals(constituent.ContainingAssembly, assembly))
{
return true;
}
namespaceQueue.Enqueue(constituent);
}
while (namespaceQueue.Count > 0)
{
var ns = namespaceQueue.Dequeue();
// Upcast so we call the 'GetMembers' method that returns an ImmutableArray.
var members = ns.GetMembers();
foreach (var namespaceOrType in members)
{
if (namespaceOrType.Kind == SymbolKind.NamedType)
{
if (namespaceOrType.IsAccessibleWithin(assembly))
{
return true;
}
}
else
{
namespaceQueue.Enqueue((INamespaceSymbol)namespaceOrType);
}
}
}
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.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class INamespaceSymbolExtensions
{
private static readonly ConditionalWeakTable<INamespaceSymbol, List<string>> s_namespaceToNameMap =
new();
public static readonly Comparison<INamespaceSymbol> CompareNamespaces = CompareTo;
public static readonly IEqualityComparer<INamespaceSymbol> EqualityComparer = new Comparer();
private static List<string> GetNameParts(INamespaceSymbol? namespaceSymbol)
{
var result = new List<string>();
GetNameParts(namespaceSymbol, result);
return result;
}
private static void GetNameParts(INamespaceSymbol? namespaceSymbol, List<string> result)
{
if (namespaceSymbol == null || namespaceSymbol.IsGlobalNamespace)
{
return;
}
GetNameParts(namespaceSymbol.ContainingNamespace, result);
result.Add(namespaceSymbol.Name);
}
public static int CompareTo(this INamespaceSymbol n1, INamespaceSymbol n2)
{
var names1 = s_namespaceToNameMap.GetValue(n1, GetNameParts);
var names2 = s_namespaceToNameMap.GetValue(n2, GetNameParts);
for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++)
{
var comp = names1[i].CompareTo(names2[i]);
if (comp != 0)
{
return comp;
}
}
return names1.Count - names2.Count;
}
public static IEnumerable<INamespaceOrTypeSymbol> GetAllNamespacesAndTypes(
this INamespaceSymbol namespaceSymbol,
CancellationToken cancellationToken)
{
var stack = new Stack<INamespaceOrTypeSymbol>();
stack.Push(namespaceSymbol);
while (stack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Pop();
if (current is INamespaceSymbol childNamespace)
{
stack.Push(childNamespace.GetMembers().AsEnumerable());
yield return childNamespace;
}
else
{
var child = (INamedTypeSymbol)current;
stack.Push(child.GetTypeMembers());
yield return child;
}
}
}
public static IEnumerable<INamespaceSymbol> GetAllNamespaces(
this INamespaceSymbol namespaceSymbol,
CancellationToken cancellationToken)
{
var stack = new Stack<INamespaceSymbol>();
stack.Push(namespaceSymbol);
while (stack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Pop();
if (current is INamespaceSymbol childNamespace)
{
stack.Push(childNamespace.GetNamespaceMembers());
yield return childNamespace;
}
}
}
public static IEnumerable<INamedTypeSymbol> GetAllTypes(
this IEnumerable<INamespaceSymbol> namespaceSymbols,
CancellationToken cancellationToken)
{
return namespaceSymbols.SelectMany(n => n.GetAllTypes(cancellationToken));
}
/// <summary>
/// Searches the namespace for namespaces with the provided name.
/// </summary>
public static IEnumerable<INamespaceSymbol> FindNamespaces(
this INamespaceSymbol namespaceSymbol,
string namespaceName,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var stack = new Stack<INamespaceSymbol>();
stack.Push(namespaceSymbol);
while (stack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Pop();
var matchingChildren = current.GetMembers(namespaceName).OfType<INamespaceSymbol>();
foreach (var child in matchingChildren)
{
yield return child;
}
stack.Push(current.GetNamespaceMembers());
}
}
public static bool ContainsAccessibleTypesOrNamespaces(
this INamespaceSymbol namespaceSymbol,
IAssemblySymbol assembly)
{
using var namespaceQueue = SharedPools.Default<Queue<INamespaceOrTypeSymbol>>().GetPooledObject();
return ContainsAccessibleTypesOrNamespacesWorker(namespaceSymbol, assembly, namespaceQueue.Object);
}
public static INamespaceSymbol? GetQualifiedNamespace(
this INamespaceSymbol globalNamespace,
string namespaceName)
{
var namespaceSymbol = globalNamespace;
foreach (var name in namespaceName.Split('.'))
{
var members = namespaceSymbol.GetMembers(name);
namespaceSymbol = members.Count() == 1
? members.First() as INamespaceSymbol
: null;
if (namespaceSymbol is null)
{
break;
}
}
return namespaceSymbol;
}
private static bool ContainsAccessibleTypesOrNamespacesWorker(
this INamespaceSymbol namespaceSymbol,
IAssemblySymbol assembly,
Queue<INamespaceOrTypeSymbol> namespaceQueue)
{
// Note: we only store INamespaceSymbols in here, even though we type it as
// INamespaceOrTypeSymbol. This is because when we call GetMembers below we
// want it to return an ImmutableArray so we don't incur any costs to iterate
// over it.
foreach (var constituent in namespaceSymbol.ConstituentNamespaces)
{
// Assume that any namespace in our own assembly is accessible to us. This saves a
// lot of cpu time checking namespaces.
if (Equals(constituent.ContainingAssembly, assembly))
{
return true;
}
namespaceQueue.Enqueue(constituent);
}
while (namespaceQueue.Count > 0)
{
var ns = namespaceQueue.Dequeue();
// Upcast so we call the 'GetMembers' method that returns an ImmutableArray.
var members = ns.GetMembers();
foreach (var namespaceOrType in members)
{
if (namespaceOrType.Kind == SymbolKind.NamedType)
{
if (namespaceOrType.IsAccessibleWithin(assembly))
{
return true;
}
}
else
{
namespaceQueue.Enqueue((INamespaceSymbol)namespaceOrType);
}
}
}
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/Features/Core/Portable/ExternalAccess/Pythia/Api/PythiaSymbolMatchPriority.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Completion.Providers;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
internal static class PythiaSymbolMatchPriority
{
internal static readonly int Keyword = SymbolMatchPriority.Keyword;
internal static readonly int PreferType = SymbolMatchPriority.PreferType;
internal static readonly int PreferNamedArgument = SymbolMatchPriority.PreferNamedArgument;
internal static readonly int PreferEventOrMethod = SymbolMatchPriority.PreferEventOrMethod;
internal static readonly int PreferFieldOrProperty = SymbolMatchPriority.PreferFieldOrProperty;
internal static readonly int PreferLocalOrParameterOrRangeVariable = SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Completion.Providers;
namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api
{
internal static class PythiaSymbolMatchPriority
{
internal static readonly int Keyword = SymbolMatchPriority.Keyword;
internal static readonly int PreferType = SymbolMatchPriority.PreferType;
internal static readonly int PreferNamedArgument = SymbolMatchPriority.PreferNamedArgument;
internal static readonly int PreferEventOrMethod = SymbolMatchPriority.PreferEventOrMethod;
internal static readonly int PreferFieldOrProperty = SymbolMatchPriority.PreferFieldOrProperty;
internal static readonly int PreferLocalOrParameterOrRangeVariable = SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable;
}
}
| -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/InlineDeclaration/CSharpInlineDeclarationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.InlineDeclaration;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration
{
public partial class CSharpInlineDeclarationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public CSharpInlineDeclarationTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpInlineDeclarationDiagnosticAnalyzer(), new CSharpInlineDeclarationCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariable1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineInNestedCall()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (Goo(int.TryParse(v, out i)))
{
}
}
}",
@"class C
{
void M()
{
if (Goo(int.TryParse(v, out int i)))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableWithConstructor1()
{
await TestInRegularAndScript1Async(
@"class C1
{
public C1(int v, out int i) {}
void M(int v)
{
[|int|] i;
if (new C1(v, out i))
{
}
}
}",
@"class C1
{
public C1(int v, out int i) {}
void M(int v)
{
if (new C1(v, out int i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableMissingWithIndexer1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (this[out i])
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableIntoFirstOut1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i, out i))
{
}
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableIntoFirstOut2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i))
{
}
if (int.TryParse(v, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInCSharp6()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariablePreferVar1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M(string v)
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M(string v)
{
if (int.TryParse(v, out var i))
{
}
}
}", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere()));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariablePreferVarExceptForPredefinedTypes1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M(string v)
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M(string v)
{
if (int.TryParse(v, out int i))
{
}
}
}", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeButKeepIntrinsics()));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestAvailableWhenWrittenAfter1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
i = 0;
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i))
{
}
i = 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingWhenWrittenBetween1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
i = 0;
if (int.TryParse(v, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingWhenReadBetween1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
M1(i);
if (int.TryParse(v, out i))
{
}
}
void M1(int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingWithComplexInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = M1();
if (int.TryParse(v, out i))
{
}
}
int M1()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestAvailableInOuterScopeIfNotWrittenOutside()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
{
if (int.TryParse(v, out i))
{
}
i = 1;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingIfWrittenAfterInOuterScope()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
{
if (int.TryParse(v, out i))
{
}
}
i = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingIfWrittenBetweenInOuterScope()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
{
i = 1;
if (int.TryParse(v, out i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInNonOut()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInField()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[|int|] i;
void M()
{
if (int.TryParse(v, out this.i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInField2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[|int|] i;
void M()
{
if (int.TryParse(v, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInNonLocalStatement()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
foreach ([|int|] i in e)
{
if (int.TryParse(v, out i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInEmbeddedStatementWithWriteAfterwards()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
while (true)
if (int.TryParse(v, out i))
{
}
i = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInEmbeddedStatement()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
while (true)
if (int.TryParse(v, out i))
{
i = 1;
}
}
}",
@"class C
{
void M()
{
while (true)
if (int.TryParse(v, out int i))
{
i = 1;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestAvailableInNestedBlock()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
while (true)
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
while (true)
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestOverloadResolutionDoNotUseVar1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (M2(out i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}",
@"class C
{
void M()
{
if (M2(out int i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere()));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestOverloadResolutionDoNotUseVar2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|var|] i = 0;
if (M2(out i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}",
@"class C
{
void M()
{
if (M2(out int i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere()));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestGenericInferenceDoNotUseVar3()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (M2(out i))
{
}
}
void M2<T>(out T i)
{
}
}",
@"class C
{
void M()
{
if (M2(out int i))
{
}
}
void M2<T>(out T i)
{
}
}", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere()));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
// prefix comment
[|int|] i;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// prefix comment
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i; // suffix comment
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// suffix comment
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments3()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
// prefix comment
[|int|] i; // suffix comment
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// prefix comment
// suffix comment
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments4()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
int [|i|] /*suffix*/, j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int i /*suffix*/))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments5()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
int /*prefix*/ [|i|], j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int /*prefix*/ i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments6()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
int /*prefix*/ [|i|] /*suffix*/, j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int /*prefix*/ i /*suffix*/))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments7()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
int j, /*prefix*/ [|i|] /*suffix*/;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int /*prefix*/ i /*suffix*/))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments8()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
// prefix
int j, [|i|]; // suffix
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// prefix
int j; // suffix
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments9()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
int /*int comment*/
/*prefix*/ [|i|] /*suffix*/,
j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int /*int comment*/
j;
{
if (int.TryParse(v, out int /*prefix*/ i /*suffix*/))
{
}
}
}
}");
}
[WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestCommentsTrivia1()
{
await TestInRegularAndScript1Async(
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Goo"");
int [|result|];
if (int.TryParse(""12"", out result))
{
}
}
}",
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Goo"");
if (int.TryParse(""12"", out int result))
{
}
}
}");
}
[WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestCommentsTrivia2()
{
await TestInRegularAndScript1Async(
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Goo"");
// Goo
int [|result|];
if (int.TryParse(""12"", out result))
{
}
}
}",
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Goo"");
// Goo
if (int.TryParse(""12"", out int result))
{
}
}
}");
}
[WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotMissingIfCapturedInLambdaAndNotUsedAfterwards()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
void M()
{
string [|s|];
Bar(() => Baz(out s));
}
void Baz(out string s) { }
void Bar(Action a) { }
}",
@"
using System;
class C
{
void M()
{
Bar(() => Baz(out string s));
}
void Baz(out string s) { }
void Bar(Action a) { }
}");
}
[WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingIfCapturedInLambdaAndUsedAfterwards()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
void M()
{
string [|s|];
Bar(() => Baz(out s));
Console.WriteLine(s);
}
void Baz(out string s) { }
void Bar(Action a) { }
}");
}
[WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDataFlow1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
void Goo(string x)
{
object [|s|] = null;
if (x != null || TryBaz(out s))
{
Console.WriteLine(s);
}
}
private bool TryBaz(out object s)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDataFlow2()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
void Goo(string x)
{
object [|s|] = null;
if (x != null && TryBaz(out s))
{
Console.WriteLine(s);
}
}
private bool TryBaz(out object s)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
void Goo(string x)
{
if (x != null && TryBaz(out object s))
{
Console.WriteLine(s);
}
}
private bool TryBaz(out object s)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(16028, "https://github.com/dotnet/roslyn/issues/16028")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestExpressionTree1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
int [|result|];
Method(() => GetValue(out result));
}
public static void GetValue(out int result)
{
result = 0;
}
public static void Method(Expression<Action> expression)
{
}
}");
}
[WorkItem(16198, "https://github.com/dotnet/roslyn/issues/16198")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestIndentation1()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
private int Bar()
{
IProjectRuleSnapshot [|unresolvedReferenceSnapshot|] = null;
var itemType = GetUnresolvedReferenceItemType(originalItemSpec,
updatedUnresolvedSnapshots,
catalogs,
out unresolvedReferenceSnapshot);
}
}",
@"
using System;
class C
{
private int Bar()
{
var itemType = GetUnresolvedReferenceItemType(originalItemSpec,
updatedUnresolvedSnapshots,
catalogs,
out IProjectRuleSnapshot unresolvedReferenceSnapshot);
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops1()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
do
{
}
while (!TryExtractTokenFromEmail(out token));
Console.WriteLine(token == ""Test"");
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops2()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
while (!TryExtractTokenFromEmail(out token))
{
}
Console.WriteLine(token == ""Test"");
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops3()
{
await TestMissingAsync(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
foreach (var v in TryExtractTokenFromEmail(out token))
{
}
Console.WriteLine(token == ""Test"");
}
private static IEnumerable<bool> TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops4()
{
await TestMissingAsync(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
for ( ; TryExtractTokenFromEmail(out token); )
{
}
Console.WriteLine(token == ""Test"");
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInUsing()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
using (GetDisposableAndValue(out token))
{
}
Console.WriteLine(token);
}
private static IDisposable GetDisposableAndValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInExceptionFilter()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
try
{
}
catch when (GetValue(out token))
{
}
Console.WriteLine(token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInShortCircuitExpression1()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|] = null;
bool condition = false && GetValue(out token);
Console.WriteLine(token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInShortCircuitExpression2()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
bool condition = false && GetValue(out token);
Console.WriteLine(token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInFixed()
{
await TestMissingAsync(
@"
using System;
class C
{
static unsafe void Main(string[] args)
{
string [|token|];
fixed (int* p = GetValue(out token))
{
}
Console.WriteLine(token);
}
private static int[] GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops1()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
do
{
}
while (!TryExtractTokenFromEmail(out token));
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
do
{
}
while (!TryExtractTokenFromEmail(out string token));
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops2()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
while (!TryExtractTokenFromEmail(out token))
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
while (!TryExtractTokenFromEmail(out string token))
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops3()
{
await TestInRegularAndScript1Async(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
foreach (var v in TryExtractTokenFromEmail(out token))
{
}
}
private static IEnumerable<bool> TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
foreach (var v in TryExtractTokenFromEmail(out string token))
{
}
}
private static IEnumerable<bool> TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops4()
{
await TestInRegularAndScript1Async(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
for ( ; TryExtractTokenFromEmail(out token); )
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
for (; TryExtractTokenFromEmail(out string token);)
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInUsing()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
using (GetDisposableAndValue(out token))
{
}
}
private static IDisposable GetDisposableAndValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
using (GetDisposableAndValue(out string token))
{
}
}
private static IDisposable GetDisposableAndValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInExceptionFilter()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
try
{
}
catch when (GetValue(out token))
{
}
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
try
{
}
catch when (GetValue(out string token))
{
}
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInShortCircuitExpression1()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|] = null;
bool condition = false && GetValue(out token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
bool condition = false && GetValue(out string token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInShortCircuitExpression2()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
bool condition = false && GetValue(out token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
bool condition = false && GetValue(out string token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInFixed()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
fixed (int* p = GetValue(out token))
{
}
}
private static int[] GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
fixed (int* p = GetValue(out string token))
{
}
}
private static int[] GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17743, "https://github.com/dotnet/roslyn/issues/17743")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLocalFunction1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
F();
void F()
{
Action f = () =>
{
Dictionary<int, int> dict = null;
int [|x|] = 0;
dict?.TryGetValue(0, out x);
Console.WriteLine(x);
};
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLocalFunction2()
{
await TestInRegularAndScript1Async(
@"
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
F();
void F()
{
Action f = () =>
{
Dictionary<int, int> dict = null;
int [|x|] = 0;
dict.TryGetValue(0, out x);
Console.WriteLine(x);
};
}
}
}",
@"
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
F();
void F()
{
Action f = () =>
{
Dictionary<int, int> dict = null;
dict.TryGetValue(0, out int x);
Console.WriteLine(x);
};
}
}
}");
}
[WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMultipleDeclarationStatementsOnSameLine1()
{
await TestInRegularAndScript1Async(
@"
class C
{
void Goo()
{
string a; string [|b|];
Method(out a, out b);
}
}",
@"
class C
{
void Goo()
{
string a;
Method(out a, out string b);
}
}");
}
[WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMultipleDeclarationStatementsOnSameLine2()
{
await TestInRegularAndScript1Async(
@"
class C
{
void Goo()
{
string a; /*leading*/ string [|b|]; // trailing
Method(out a, out b);
}
}",
@"
class C
{
void Goo()
{
string a; /*leading*/ // trailing
Method(out a, out string b);
}
}");
}
[WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMultipleDeclarationStatementsOnSameLine3()
{
await TestInRegularAndScript1Async(
@"
class C
{
void Goo()
{
string a;
/*leading*/ string [|b|]; // trailing
Method(out a, out b);
}
}",
@"
class C
{
void Goo()
{
string a;
/*leading*/ // trailing
Method(out a, out string b);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnUnderscore()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
void M()
{
[|int|] _;
if (N(out _)
{
Console.WriteLine(_);
}
}
}");
}
[WorkItem(18668, "https://github.com/dotnet/roslyn/issues/18668")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDefiniteAssignmentIssueWithVar()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
static void M(bool condition)
{
[|var|] x = 1;
var result = condition && int.TryParse(""2"", out x);
Console.WriteLine(x);
}
}");
}
[WorkItem(18668, "https://github.com/dotnet/roslyn/issues/18668")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDefiniteAssignmentIssueWithNonVar()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
static void M(bool condition)
{
[|int|] x = 1;
var result = condition && int.TryParse(""2"", out x);
Console.WriteLine(x);
}
}");
}
[WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnCrossFunction1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
Method<string>();
}
public static void Method<T>()
{
[|T t|];
void Local<T>()
{
Out(out t);
Console.WriteLine(t);
}
Local<int>();
}
public static void Out<T>(out T t) => t = default;
}");
}
[WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnCrossFunction2()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
Method<string>();
}
public static void Method<T>()
{
void Local<T>()
{
[|T t|];
void InnerLocal<T>()
{
Out(out t);
Console.WriteLine(t);
}
}
Local<int>();
}
public static void Out<T>(out T t) => t = default;
}");
}
[WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnCrossFunction3()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
Method<string>();
}
public static void Method<T>()
{
[|T t|];
void Local<T>()
{
{ // <-- note this set of added braces
Out(out t);
Console.WriteLine(t);
}
}
Local<int>();
}
public static void Out<T>(out T t) => t = default;
}");
}
[WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnCrossFunction4()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
Method<string>();
}
public static void Method<T>()
{
{ // <-- note this set of added braces
[|T t|];
void Local<T>()
{
{ // <-- and my axe
Out(out t);
Console.WriteLine(t);
}
}
Local<int>();
}
}
public static void Out<T>(out T t) => t = default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDefiniteAssignment1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
static bool M(out bool i) => throw null;
static void M(bool condition)
{
[|bool|] x = false;
if (condition || M(out x))
{
Console.WriteLine(x);
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDefiniteAssignment2()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
static bool M(out bool i) => throw null;
static bool Use(bool i) => throw null;
static void M(bool condition)
{
[|bool|] x = false;
if (condition || M(out x))
{
x = Use(x);
}
}
}");
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
[InlineData("c && M(out x)", "c && M(out bool x)")]
[InlineData("false || M(out x)", "false || M(out bool x)")]
[InlineData("M(out x) || M(out x)", "M(out bool x) || M(out x)")]
public async Task TestDefiniteAssignment3(string input, string output)
{
await TestInRegularAndScript1Async(
$@"
using System;
class C
{{
static bool M(out bool i) => throw null;
static bool Use(bool i) => throw null;
static void M(bool c)
{{
[|bool|] x = false;
if ({input})
{{
Console.WriteLine(x);
}}
}}
}}",
$@"
using System;
class C
{{
static bool M(out bool i) => throw null;
static bool Use(bool i) => throw null;
static void M(bool c)
{{
if ({output})
{{
Console.WriteLine(x);
}}
}}
}}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariable_NullableEnable()
{
await TestInRegularAndScript1Async(@"
#nullable enable
class C
{
void M(out C c2)
{
[|C|] c;
M(out c);
c2 = c;
}
}", @"
#nullable enable
class C
{
void M(out C c2)
{
M(out C c);
c2 = c;
}
}");
}
[WorkItem(44429, "https://github.com/dotnet/roslyn/issues/44429")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TopLevelStatement()
{
await TestMissingAsync(@"
[|int|] i;
if (int.TryParse(v, out i))
{
}", new TestParameters(TestOptions.Regular));
}
[WorkItem(47041, "https://github.com/dotnet/roslyn/issues/47041")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task CollectionInitializer()
{
await TestInRegularAndScript1Async(
@"class C
{
private List<Func<string, bool>> _funcs2 = new List<Func<string, bool>>()
{
s => { int [|i|] = 0; return int.TryParse(s, out i); }
};
}",
@"class C
{
private List<Func<string, bool>> _funcs2 = new List<Func<string, bool>>()
{
s => { return int.TryParse(s, out int i); }
};
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.InlineDeclaration;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration
{
public partial class CSharpInlineDeclarationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public CSharpInlineDeclarationTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpInlineDeclarationDiagnosticAnalyzer(), new CSharpInlineDeclarationCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariable1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineInNestedCall()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (Goo(int.TryParse(v, out i)))
{
}
}
}",
@"class C
{
void M()
{
if (Goo(int.TryParse(v, out int i)))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableWithConstructor1()
{
await TestInRegularAndScript1Async(
@"class C1
{
public C1(int v, out int i) {}
void M(int v)
{
[|int|] i;
if (new C1(v, out i))
{
}
}
}",
@"class C1
{
public C1(int v, out int i) {}
void M(int v)
{
if (new C1(v, out int i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableMissingWithIndexer1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (this[out i])
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableIntoFirstOut1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i, out i))
{
}
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariableIntoFirstOut2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i))
{
}
if (int.TryParse(v, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInCSharp6()
{
await TestMissingAsync(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariablePreferVar1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M(string v)
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M(string v)
{
if (int.TryParse(v, out var i))
{
}
}
}", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere()));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariablePreferVarExceptForPredefinedTypes1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M(string v)
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
}
}",
@"class C
{
void M(string v)
{
if (int.TryParse(v, out int i))
{
}
}
}", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeButKeepIntrinsics()));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestAvailableWhenWrittenAfter1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, out i))
{
}
i = 0;
}
}",
@"class C
{
void M()
{
if (int.TryParse(v, out int i))
{
}
i = 0;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingWhenWrittenBetween1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
i = 0;
if (int.TryParse(v, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingWhenReadBetween1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
M1(i);
if (int.TryParse(v, out i))
{
}
}
void M1(int i)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingWithComplexInitializer()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = M1();
if (int.TryParse(v, out i))
{
}
}
int M1()
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestAvailableInOuterScopeIfNotWrittenOutside()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
{
if (int.TryParse(v, out i))
{
}
i = 1;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingIfWrittenAfterInOuterScope()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
{
if (int.TryParse(v, out i))
{
}
}
i = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingIfWrittenBetweenInOuterScope()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i = 0;
{
i = 1;
if (int.TryParse(v, out i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInNonOut()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
if (int.TryParse(v, i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInField()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[|int|] i;
void M()
{
if (int.TryParse(v, out this.i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInField2()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
[|int|] i;
void M()
{
if (int.TryParse(v, out i))
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInNonLocalStatement()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
foreach ([|int|] i in e)
{
if (int.TryParse(v, out i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingInEmbeddedStatementWithWriteAfterwards()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void M()
{
[|int|] i;
while (true)
if (int.TryParse(v, out i))
{
}
i = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInEmbeddedStatement()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
while (true)
if (int.TryParse(v, out i))
{
i = 1;
}
}
}",
@"class C
{
void M()
{
while (true)
if (int.TryParse(v, out int i))
{
i = 1;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestAvailableInNestedBlock()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
while (true)
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
while (true)
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestOverloadResolutionDoNotUseVar1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (M2(out i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}",
@"class C
{
void M()
{
if (M2(out int i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere()));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestOverloadResolutionDoNotUseVar2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|var|] i = 0;
if (M2(out i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}",
@"class C
{
void M()
{
if (M2(out int i))
{
}
}
void M2(out int i)
{
}
void M2(out string s)
{
}
}", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere()));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestGenericInferenceDoNotUseVar3()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i;
if (M2(out i))
{
}
}
void M2<T>(out T i)
{
}
}",
@"class C
{
void M()
{
if (M2(out int i))
{
}
}
void M2<T>(out T i)
{
}
}", new TestParameters(options: new UseImplicitTypeTests().ImplicitTypeEverywhere()));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments1()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
// prefix comment
[|int|] i;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// prefix comment
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments2()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
[|int|] i; // suffix comment
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// suffix comment
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments3()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
// prefix comment
[|int|] i; // suffix comment
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// prefix comment
// suffix comment
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments4()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
int [|i|] /*suffix*/, j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int i /*suffix*/))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments5()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
int /*prefix*/ [|i|], j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int /*prefix*/ i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments6()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
int /*prefix*/ [|i|] /*suffix*/, j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int /*prefix*/ i /*suffix*/))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments7()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
int j, /*prefix*/ [|i|] /*suffix*/;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int j;
{
if (int.TryParse(v, out int /*prefix*/ i /*suffix*/))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments8()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
// prefix
int j, [|i|]; // suffix
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
// prefix
int j; // suffix
{
if (int.TryParse(v, out int i))
{
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestComments9()
{
await TestInRegularAndScript1Async(
@"class C
{
void M()
{
int /*int comment*/
/*prefix*/ [|i|] /*suffix*/,
j;
{
if (int.TryParse(v, out i))
{
}
}
}
}",
@"class C
{
void M()
{
int /*int comment*/
j;
{
if (int.TryParse(v, out int /*prefix*/ i /*suffix*/))
{
}
}
}
}");
}
[WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestCommentsTrivia1()
{
await TestInRegularAndScript1Async(
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Goo"");
int [|result|];
if (int.TryParse(""12"", out result))
{
}
}
}",
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Goo"");
if (int.TryParse(""12"", out int result))
{
}
}
}");
}
[WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestCommentsTrivia2()
{
await TestInRegularAndScript1Async(
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Goo"");
// Goo
int [|result|];
if (int.TryParse(""12"", out result))
{
}
}
}",
@"using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(""Goo"");
// Goo
if (int.TryParse(""12"", out int result))
{
}
}
}");
}
[WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotMissingIfCapturedInLambdaAndNotUsedAfterwards()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
void M()
{
string [|s|];
Bar(() => Baz(out s));
}
void Baz(out string s) { }
void Bar(Action a) { }
}",
@"
using System;
class C
{
void M()
{
Bar(() => Baz(out string s));
}
void Baz(out string s) { }
void Bar(Action a) { }
}");
}
[WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingIfCapturedInLambdaAndUsedAfterwards()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
void M()
{
string [|s|];
Bar(() => Baz(out s));
Console.WriteLine(s);
}
void Baz(out string s) { }
void Bar(Action a) { }
}");
}
[WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDataFlow1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
void Goo(string x)
{
object [|s|] = null;
if (x != null || TryBaz(out s))
{
Console.WriteLine(s);
}
}
private bool TryBaz(out object s)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDataFlow2()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
void Goo(string x)
{
object [|s|] = null;
if (x != null && TryBaz(out s))
{
Console.WriteLine(s);
}
}
private bool TryBaz(out object s)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
void Goo(string x)
{
if (x != null && TryBaz(out object s))
{
Console.WriteLine(s);
}
}
private bool TryBaz(out object s)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(16028, "https://github.com/dotnet/roslyn/issues/16028")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestExpressionTree1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
int [|result|];
Method(() => GetValue(out result));
}
public static void GetValue(out int result)
{
result = 0;
}
public static void Method(Expression<Action> expression)
{
}
}");
}
[WorkItem(16198, "https://github.com/dotnet/roslyn/issues/16198")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestIndentation1()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
private int Bar()
{
IProjectRuleSnapshot [|unresolvedReferenceSnapshot|] = null;
var itemType = GetUnresolvedReferenceItemType(originalItemSpec,
updatedUnresolvedSnapshots,
catalogs,
out unresolvedReferenceSnapshot);
}
}",
@"
using System;
class C
{
private int Bar()
{
var itemType = GetUnresolvedReferenceItemType(originalItemSpec,
updatedUnresolvedSnapshots,
catalogs,
out IProjectRuleSnapshot unresolvedReferenceSnapshot);
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops1()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
do
{
}
while (!TryExtractTokenFromEmail(out token));
Console.WriteLine(token == ""Test"");
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops2()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
while (!TryExtractTokenFromEmail(out token))
{
}
Console.WriteLine(token == ""Test"");
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops3()
{
await TestMissingAsync(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
foreach (var v in TryExtractTokenFromEmail(out token))
{
}
Console.WriteLine(token == ""Test"");
}
private static IEnumerable<bool> TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInLoops4()
{
await TestMissingAsync(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
for ( ; TryExtractTokenFromEmail(out token); )
{
}
Console.WriteLine(token == ""Test"");
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInUsing()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
using (GetDisposableAndValue(out token))
{
}
Console.WriteLine(token);
}
private static IDisposable GetDisposableAndValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInExceptionFilter()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
try
{
}
catch when (GetValue(out token))
{
}
Console.WriteLine(token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInShortCircuitExpression1()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|] = null;
bool condition = false && GetValue(out token);
Console.WriteLine(token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInShortCircuitExpression2()
{
await TestMissingAsync(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
bool condition = false && GetValue(out token);
Console.WriteLine(token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestNotInFixed()
{
await TestMissingAsync(
@"
using System;
class C
{
static unsafe void Main(string[] args)
{
string [|token|];
fixed (int* p = GetValue(out token))
{
}
Console.WriteLine(token);
}
private static int[] GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops1()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
do
{
}
while (!TryExtractTokenFromEmail(out token));
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
do
{
}
while (!TryExtractTokenFromEmail(out string token));
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops2()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
while (!TryExtractTokenFromEmail(out token))
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
while (!TryExtractTokenFromEmail(out string token))
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops3()
{
await TestInRegularAndScript1Async(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
foreach (var v in TryExtractTokenFromEmail(out token))
{
}
}
private static IEnumerable<bool> TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
foreach (var v in TryExtractTokenFromEmail(out string token))
{
}
}
private static IEnumerable<bool> TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLoops4()
{
await TestInRegularAndScript1Async(
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
string [|token|];
for ( ; TryExtractTokenFromEmail(out token); )
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
using System.Collections.Generic;
class C
{
static void Main(string[] args)
{
for (; TryExtractTokenFromEmail(out string token);)
{
}
}
private static bool TryExtractTokenFromEmail(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInUsing()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
using (GetDisposableAndValue(out token))
{
}
}
private static IDisposable GetDisposableAndValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
using (GetDisposableAndValue(out string token))
{
}
}
private static IDisposable GetDisposableAndValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInExceptionFilter()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
try
{
}
catch when (GetValue(out token))
{
}
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
try
{
}
catch when (GetValue(out string token))
{
}
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInShortCircuitExpression1()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|] = null;
bool condition = false && GetValue(out token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
bool condition = false && GetValue(out string token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInShortCircuitExpression2()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
bool condition = false && GetValue(out token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
bool condition = false && GetValue(out string token);
}
private static bool GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(18076, "https://github.com/dotnet/roslyn/issues/18076")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInFixed()
{
await TestInRegularAndScript1Async(
@"
using System;
class C
{
static void Main(string[] args)
{
string [|token|];
fixed (int* p = GetValue(out token))
{
}
}
private static int[] GetValue(out string token)
{
throw new NotImplementedException();
}
}",
@"
using System;
class C
{
static void Main(string[] args)
{
fixed (int* p = GetValue(out string token))
{
}
}
private static int[] GetValue(out string token)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(17743, "https://github.com/dotnet/roslyn/issues/17743")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLocalFunction1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
F();
void F()
{
Action f = () =>
{
Dictionary<int, int> dict = null;
int [|x|] = 0;
dict?.TryGetValue(0, out x);
Console.WriteLine(x);
};
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestInLocalFunction2()
{
await TestInRegularAndScript1Async(
@"
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
F();
void F()
{
Action f = () =>
{
Dictionary<int, int> dict = null;
int [|x|] = 0;
dict.TryGetValue(0, out x);
Console.WriteLine(x);
};
}
}
}",
@"
using System;
using System.Collections.Generic;
class Demo
{
static void Main()
{
F();
void F()
{
Action f = () =>
{
Dictionary<int, int> dict = null;
dict.TryGetValue(0, out int x);
Console.WriteLine(x);
};
}
}
}");
}
[WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMultipleDeclarationStatementsOnSameLine1()
{
await TestInRegularAndScript1Async(
@"
class C
{
void Goo()
{
string a; string [|b|];
Method(out a, out b);
}
}",
@"
class C
{
void Goo()
{
string a;
Method(out a, out string b);
}
}");
}
[WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMultipleDeclarationStatementsOnSameLine2()
{
await TestInRegularAndScript1Async(
@"
class C
{
void Goo()
{
string a; /*leading*/ string [|b|]; // trailing
Method(out a, out b);
}
}",
@"
class C
{
void Goo()
{
string a; /*leading*/ // trailing
Method(out a, out string b);
}
}");
}
[WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMultipleDeclarationStatementsOnSameLine3()
{
await TestInRegularAndScript1Async(
@"
class C
{
void Goo()
{
string a;
/*leading*/ string [|b|]; // trailing
Method(out a, out b);
}
}",
@"
class C
{
void Goo()
{
string a;
/*leading*/ // trailing
Method(out a, out string b);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnUnderscore()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
void M()
{
[|int|] _;
if (N(out _)
{
Console.WriteLine(_);
}
}
}");
}
[WorkItem(18668, "https://github.com/dotnet/roslyn/issues/18668")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDefiniteAssignmentIssueWithVar()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
static void M(bool condition)
{
[|var|] x = 1;
var result = condition && int.TryParse(""2"", out x);
Console.WriteLine(x);
}
}");
}
[WorkItem(18668, "https://github.com/dotnet/roslyn/issues/18668")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDefiniteAssignmentIssueWithNonVar()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
static void M(bool condition)
{
[|int|] x = 1;
var result = condition && int.TryParse(""2"", out x);
Console.WriteLine(x);
}
}");
}
[WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnCrossFunction1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
Method<string>();
}
public static void Method<T>()
{
[|T t|];
void Local<T>()
{
Out(out t);
Console.WriteLine(t);
}
Local<int>();
}
public static void Out<T>(out T t) => t = default;
}");
}
[WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnCrossFunction2()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
Method<string>();
}
public static void Method<T>()
{
void Local<T>()
{
[|T t|];
void InnerLocal<T>()
{
Out(out t);
Console.WriteLine(t);
}
}
Local<int>();
}
public static void Out<T>(out T t) => t = default;
}");
}
[WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnCrossFunction3()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
Method<string>();
}
public static void Method<T>()
{
[|T t|];
void Local<T>()
{
{ // <-- note this set of added braces
Out(out t);
Console.WriteLine(t);
}
}
Local<int>();
}
public static void Out<T>(out T t) => t = default;
}");
}
[WorkItem(21907, "https://github.com/dotnet/roslyn/issues/21907")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestMissingOnCrossFunction4()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
Method<string>();
}
public static void Method<T>()
{
{ // <-- note this set of added braces
[|T t|];
void Local<T>()
{
{ // <-- and my axe
Out(out t);
Console.WriteLine(t);
}
}
Local<int>();
}
}
public static void Out<T>(out T t) => t = default;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDefiniteAssignment1()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
static bool M(out bool i) => throw null;
static void M(bool condition)
{
[|bool|] x = false;
if (condition || M(out x))
{
Console.WriteLine(x);
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TestDefiniteAssignment2()
{
await TestMissingInRegularAndScriptAsync(
@"
using System;
class C
{
static bool M(out bool i) => throw null;
static bool Use(bool i) => throw null;
static void M(bool condition)
{
[|bool|] x = false;
if (condition || M(out x))
{
x = Use(x);
}
}
}");
}
[Theory, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
[InlineData("c && M(out x)", "c && M(out bool x)")]
[InlineData("false || M(out x)", "false || M(out bool x)")]
[InlineData("M(out x) || M(out x)", "M(out bool x) || M(out x)")]
public async Task TestDefiniteAssignment3(string input, string output)
{
await TestInRegularAndScript1Async(
$@"
using System;
class C
{{
static bool M(out bool i) => throw null;
static bool Use(bool i) => throw null;
static void M(bool c)
{{
[|bool|] x = false;
if ({input})
{{
Console.WriteLine(x);
}}
}}
}}",
$@"
using System;
class C
{{
static bool M(out bool i) => throw null;
static bool Use(bool i) => throw null;
static void M(bool c)
{{
if ({output})
{{
Console.WriteLine(x);
}}
}}
}}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task InlineVariable_NullableEnable()
{
await TestInRegularAndScript1Async(@"
#nullable enable
class C
{
void M(out C c2)
{
[|C|] c;
M(out c);
c2 = c;
}
}", @"
#nullable enable
class C
{
void M(out C c2)
{
M(out C c);
c2 = c;
}
}");
}
[WorkItem(44429, "https://github.com/dotnet/roslyn/issues/44429")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task TopLevelStatement()
{
await TestMissingAsync(@"
[|int|] i;
if (int.TryParse(v, out i))
{
}", new TestParameters(TestOptions.Regular));
}
[WorkItem(47041, "https://github.com/dotnet/roslyn/issues/47041")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)]
public async Task CollectionInitializer()
{
await TestInRegularAndScript1Async(
@"class C
{
private List<Func<string, bool>> _funcs2 = new List<Func<string, bool>>()
{
s => { int [|i|] = 0; return int.TryParse(s, out i); }
};
}",
@"class C
{
private List<Func<string, bool>> _funcs2 = new List<Func<string, bool>>()
{
s => { return int.TryParse(s, out int i); }
};
}");
}
}
}
| -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/Shared/Tagging/Tags/ConflictTag.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal class ConflictTag : TextMarkerTag
{
public const string TagId = "RoslynConflictTag";
public static readonly ConflictTag Instance = new();
private ConflictTag()
: 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.
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal class ConflictTag : TextMarkerTag
{
public const string TagId = "RoslynConflictTag";
public static readonly ConflictTag Instance = new();
private ConflictTag()
: 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/Compilers/Core/Portable/Symbols/TypedConstantValue.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Reflection;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a simple value or a read-only array of <see cref="TypedConstant"/>.
/// </summary>
internal struct TypedConstantValue : IEquatable<TypedConstantValue>
{
// Simple value or ImmutableArray<TypedConstant>.
// Null array is represented by a null reference.
private readonly object? _value;
internal TypedConstantValue(object? value)
{
Debug.Assert(value == null || value is string || value.GetType().GetTypeInfo().IsEnum || (value.GetType().GetTypeInfo().IsPrimitive && !(value is System.IntPtr) && !(value is System.UIntPtr)) || value is ITypeSymbol);
_value = value;
}
internal TypedConstantValue(ImmutableArray<TypedConstant> array)
{
_value = array.IsDefault ? null : (object)array;
}
/// <summary>
/// True if the constant represents a null literal.
/// </summary>
public bool IsNull
{
get
{
return _value == null;
}
}
public ImmutableArray<TypedConstant> Array
{
get
{
return _value == null ? default(ImmutableArray<TypedConstant>) : (ImmutableArray<TypedConstant>)_value;
}
}
public object? Object
{
get
{
Debug.Assert(!(_value is ImmutableArray<TypedConstant>));
return _value;
}
}
public override int GetHashCode()
{
return _value?.GetHashCode() ?? 0;
}
public override bool Equals(object? obj)
{
return obj is TypedConstantValue && Equals((TypedConstantValue)obj);
}
public bool Equals(TypedConstantValue other)
{
return object.Equals(_value, other._value);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Represents a simple value or a read-only array of <see cref="TypedConstant"/>.
/// </summary>
internal struct TypedConstantValue : IEquatable<TypedConstantValue>
{
// Simple value or ImmutableArray<TypedConstant>.
// Null array is represented by a null reference.
private readonly object? _value;
internal TypedConstantValue(object? value)
{
Debug.Assert(value == null || value is string || value.GetType().GetTypeInfo().IsEnum || (value.GetType().GetTypeInfo().IsPrimitive && !(value is System.IntPtr) && !(value is System.UIntPtr)) || value is ITypeSymbol);
_value = value;
}
internal TypedConstantValue(ImmutableArray<TypedConstant> array)
{
_value = array.IsDefault ? null : (object)array;
}
/// <summary>
/// True if the constant represents a null literal.
/// </summary>
public bool IsNull
{
get
{
return _value == null;
}
}
public ImmutableArray<TypedConstant> Array
{
get
{
return _value == null ? default(ImmutableArray<TypedConstant>) : (ImmutableArray<TypedConstant>)_value;
}
}
public object? Object
{
get
{
Debug.Assert(!(_value is ImmutableArray<TypedConstant>));
return _value;
}
}
public override int GetHashCode()
{
return _value?.GetHashCode() ?? 0;
}
public override bool Equals(object? obj)
{
return obj is TypedConstantValue && Equals((TypedConstantValue)obj);
}
public bool Equals(TypedConstantValue other)
{
return object.Equals(_value, other._value);
}
}
}
| -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/InlineHints/AbstractInlineHintsService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.InlineHints
{
internal abstract class AbstractInlineHintsService : IInlineHintsService
{
public async Task<ImmutableArray<InlineHint>> GetInlineHintsAsync(
Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var inlineParameterService = document.GetLanguageService<IInlineParameterNameHintsService>();
var inlineTypeService = document.GetLanguageService<IInlineTypeHintsService>();
var parameters = inlineParameterService == null
? ImmutableArray<InlineHint>.Empty
: await inlineParameterService.GetInlineHintsAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
var types = inlineTypeService == null
? ImmutableArray<InlineHint>.Empty
: await inlineTypeService.GetInlineHintsAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
return parameters.Concat(types);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.InlineHints
{
internal abstract class AbstractInlineHintsService : IInlineHintsService
{
public async Task<ImmutableArray<InlineHint>> GetInlineHintsAsync(
Document document, TextSpan textSpan, CancellationToken cancellationToken)
{
var inlineParameterService = document.GetLanguageService<IInlineParameterNameHintsService>();
var inlineTypeService = document.GetLanguageService<IInlineTypeHintsService>();
var parameters = inlineParameterService == null
? ImmutableArray<InlineHint>.Empty
: await inlineParameterService.GetInlineHintsAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
var types = inlineTypeService == null
? ImmutableArray<InlineHint>.Empty
: await inlineTypeService.GetInlineHintsAsync(document, textSpan, cancellationToken).ConfigureAwait(false);
return parameters.Concat(types);
}
}
}
| -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/ResourceDescription.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Roslyn.Utilities;
using Microsoft.CodeAnalysis.Emit;
using System.Reflection;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Security.Cryptography;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Representation of a resource whose contents are to be embedded in the output assembly.
/// </summary>
public sealed class ResourceDescription : Cci.IFileReference
{
internal readonly string ResourceName;
internal readonly string? FileName; // null if embedded
internal readonly bool IsPublic;
internal readonly Func<Stream> DataProvider;
private readonly CryptographicHashProvider _hashes;
/// <summary>
/// Creates a representation of a resource whose contents are to be embedded in the output assembly.
/// </summary>
/// <param name="resourceName">Resource name.</param>
/// <param name="dataProvider">The callers will dispose the result after use.
/// This allows the resources to be opened and read one at a time.
/// </param>
/// <param name="isPublic">True if the resource is public.</param>
/// <remarks>
/// Returns a stream of the data to embed.
/// </remarks>
public ResourceDescription(string resourceName, Func<Stream> dataProvider, bool isPublic)
: this(resourceName, fileName: null, dataProvider, isPublic, isEmbedded: true, checkArgs: true)
{
}
/// <summary>
/// Creates a representation of a resource whose file name will be recorded in the assembly.
/// </summary>
/// <param name="resourceName">Resource name.</param>
/// <param name="fileName">File name with an extension to be stored in metadata.</param>
/// <param name="dataProvider">The callers will dispose the result after use.
/// This allows the resources to be opened and read one at a time.
/// </param>
/// <param name="isPublic">True if the resource is public.</param>
/// <remarks>
/// Function returning a stream of the resource content (used to calculate hash).
/// </remarks>
public ResourceDescription(string resourceName, string? fileName, Func<Stream> dataProvider, bool isPublic)
: this(resourceName, fileName, dataProvider, isPublic, isEmbedded: false, checkArgs: true)
{
}
internal ResourceDescription(string resourceName, string? fileName, Func<Stream> dataProvider, bool isPublic, bool isEmbedded, bool checkArgs)
{
if (checkArgs)
{
if (dataProvider == null)
{
throw new ArgumentNullException(nameof(dataProvider));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
if (!MetadataHelpers.IsValidMetadataIdentifier(resourceName))
{
throw new ArgumentException(CodeAnalysisResources.EmptyOrInvalidResourceName, nameof(resourceName));
}
if (!isEmbedded)
{
if (fileName == null)
{
throw new ArgumentNullException(nameof(fileName));
}
if (!MetadataHelpers.IsValidMetadataFileName(fileName))
{
throw new ArgumentException(CodeAnalysisResources.EmptyOrInvalidFileName, nameof(fileName));
}
}
}
this.ResourceName = resourceName;
this.DataProvider = dataProvider;
this.FileName = isEmbedded ? null : fileName;
this.IsPublic = isPublic;
_hashes = new ResourceHashProvider(this);
}
private sealed class ResourceHashProvider : CryptographicHashProvider
{
private readonly ResourceDescription _resource;
public ResourceHashProvider(ResourceDescription resource)
{
RoslynDebug.Assert(resource != null);
_resource = resource;
}
internal override ImmutableArray<byte> ComputeHash(HashAlgorithm algorithm)
{
try
{
using (var stream = _resource.DataProvider())
{
if (stream == null)
{
throw new InvalidOperationException(CodeAnalysisResources.ResourceDataProviderShouldReturnNonNullStream);
}
return ImmutableArray.CreateRange(algorithm.ComputeHash(stream));
}
}
catch (Exception ex)
{
throw new ResourceException(_resource.FileName, ex);
}
}
}
internal bool IsEmbedded
{
get { return FileName == null; }
}
internal Cci.ManagedResource ToManagedResource(CommonPEModuleBuilder moduleBeingBuilt)
{
return new Cci.ManagedResource(ResourceName, IsPublic, IsEmbedded ? DataProvider : null, IsEmbedded ? null : this, offset: 0);
}
ImmutableArray<byte> Cci.IFileReference.GetHashValue(AssemblyHashAlgorithm algorithmId)
{
return _hashes.GetHash(algorithmId);
}
string? Cci.IFileReference.FileName
{
get { return FileName; }
}
bool Cci.IFileReference.HasMetadata
{
get { 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.IO;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Emit;
using System.Reflection;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Security.Cryptography;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Representation of a resource whose contents are to be embedded in the output assembly.
/// </summary>
public sealed class ResourceDescription : Cci.IFileReference
{
internal readonly string ResourceName;
internal readonly string? FileName; // null if embedded
internal readonly bool IsPublic;
internal readonly Func<Stream> DataProvider;
private readonly CryptographicHashProvider _hashes;
/// <summary>
/// Creates a representation of a resource whose contents are to be embedded in the output assembly.
/// </summary>
/// <param name="resourceName">Resource name.</param>
/// <param name="dataProvider">The callers will dispose the result after use.
/// This allows the resources to be opened and read one at a time.
/// </param>
/// <param name="isPublic">True if the resource is public.</param>
/// <remarks>
/// Returns a stream of the data to embed.
/// </remarks>
public ResourceDescription(string resourceName, Func<Stream> dataProvider, bool isPublic)
: this(resourceName, fileName: null, dataProvider, isPublic, isEmbedded: true, checkArgs: true)
{
}
/// <summary>
/// Creates a representation of a resource whose file name will be recorded in the assembly.
/// </summary>
/// <param name="resourceName">Resource name.</param>
/// <param name="fileName">File name with an extension to be stored in metadata.</param>
/// <param name="dataProvider">The callers will dispose the result after use.
/// This allows the resources to be opened and read one at a time.
/// </param>
/// <param name="isPublic">True if the resource is public.</param>
/// <remarks>
/// Function returning a stream of the resource content (used to calculate hash).
/// </remarks>
public ResourceDescription(string resourceName, string? fileName, Func<Stream> dataProvider, bool isPublic)
: this(resourceName, fileName, dataProvider, isPublic, isEmbedded: false, checkArgs: true)
{
}
internal ResourceDescription(string resourceName, string? fileName, Func<Stream> dataProvider, bool isPublic, bool isEmbedded, bool checkArgs)
{
if (checkArgs)
{
if (dataProvider == null)
{
throw new ArgumentNullException(nameof(dataProvider));
}
if (resourceName == null)
{
throw new ArgumentNullException(nameof(resourceName));
}
if (!MetadataHelpers.IsValidMetadataIdentifier(resourceName))
{
throw new ArgumentException(CodeAnalysisResources.EmptyOrInvalidResourceName, nameof(resourceName));
}
if (!isEmbedded)
{
if (fileName == null)
{
throw new ArgumentNullException(nameof(fileName));
}
if (!MetadataHelpers.IsValidMetadataFileName(fileName))
{
throw new ArgumentException(CodeAnalysisResources.EmptyOrInvalidFileName, nameof(fileName));
}
}
}
this.ResourceName = resourceName;
this.DataProvider = dataProvider;
this.FileName = isEmbedded ? null : fileName;
this.IsPublic = isPublic;
_hashes = new ResourceHashProvider(this);
}
private sealed class ResourceHashProvider : CryptographicHashProvider
{
private readonly ResourceDescription _resource;
public ResourceHashProvider(ResourceDescription resource)
{
RoslynDebug.Assert(resource != null);
_resource = resource;
}
internal override ImmutableArray<byte> ComputeHash(HashAlgorithm algorithm)
{
try
{
using (var stream = _resource.DataProvider())
{
if (stream == null)
{
throw new InvalidOperationException(CodeAnalysisResources.ResourceDataProviderShouldReturnNonNullStream);
}
return ImmutableArray.CreateRange(algorithm.ComputeHash(stream));
}
}
catch (Exception ex)
{
throw new ResourceException(_resource.FileName, ex);
}
}
}
internal bool IsEmbedded
{
get { return FileName == null; }
}
internal Cci.ManagedResource ToManagedResource(CommonPEModuleBuilder moduleBeingBuilt)
{
return new Cci.ManagedResource(ResourceName, IsPublic, IsEmbedded ? DataProvider : null, IsEmbedded ? null : this, offset: 0);
}
ImmutableArray<byte> Cci.IFileReference.GetHashValue(AssemblyHashAlgorithm algorithmId)
{
return _hashes.GetHash(algorithmId);
}
string? Cci.IFileReference.FileName
{
get { return FileName; }
}
bool Cci.IFileReference.HasMetadata
{
get { 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/Compilers/CSharp/Test/Semantic/Semantics/VarianceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class VarianceTests : CompilingTestBase
{
/// <summary>
/// Test generic interface assignment with type parameter variance.
/// </summary>
[Fact]
public void TestInterfaceAssignment()
{
var text = @"
interface I<in TIn, out TOut, T> {{ }}
class A {{ }}
class B : A {{ }}
class C : B {{ }}
class Test
{{
static I<A, A, A> i01 = null;
static I<A, A, B> i02 = null;
static I<A, A, C> i03 = null;
static I<A, B, A> i04 = null;
static I<A, B, B> i05 = null;
static I<A, B, C> i06 = null;
static I<A, C, A> i07 = null;
static I<A, C, B> i08 = null;
static I<A, C, C> i09 = null;
static I<B, A, A> i10 = null;
static I<B, A, B> i11 = null;
static I<B, A, C> i12 = null;
static I<B, B, A> i13 = null;
static I<B, B, B> i14 = null;
static I<B, B, C> i15 = null;
static I<B, C, A> i16 = null;
static I<B, C, B> i17 = null;
static I<B, C, C> i18 = null;
static I<C, A, A> i19 = null;
static I<C, A, B> i20 = null;
static I<C, A, C> i21 = null;
static I<C, B, A> i22 = null;
static I<C, B, B> i23 = null;
static I<C, B, C> i24 = null;
static I<C, C, A> i25 = null;
static I<C, C, B> i26 = null;
static I<C, C, C> i27 = null;
static void Main()
{{
i{0:d2} = i{1:d2};
}}
}}";
// Table comes from manual Dev10 testing
int[][] validAssignments = new int[][]
{
/*filler for 1-indexing*/ new int[0],
/*01*/
new [] { 1, 4, 7 },
/*02*/ new [] { 2, 5, 8 },
/*03*/ new [] { 3, 6, 9 },
/*04*/ new [] { 4, 7 },
/*05*/ new [] { 5, 8 },
/*06*/ new [] { 6, 9 },
/*07*/ new [] { 7 },
/*08*/ new [] { 8 },
/*09*/ new [] { 9 },
/*10*/ new [] { 1, 4, 7, 10, 13, 16 },
/*11*/ new [] { 2, 5, 8, 11, 14, 17 },
/*12*/ new [] { 3, 6, 9, 12, 15, 18 },
/*13*/ new [] { 4, 7, 13, 16 },
/*14*/ new [] { 5, 8, 14, 17 },
/*15*/ new [] { 6, 9, 15, 18 },
/*16*/ new [] { 7, 16 },
/*17*/ new [] { 8, 17 },
/*18*/ new [] { 9, 18 },
/*19*/ new [] { 1, 4, 7, 10, 13, 16, 19, 22, 25 },
/*20*/ new [] { 2, 5, 8, 11, 14, 17, 20, 23, 26 },
/*21*/ new [] { 3, 6, 9, 12, 15, 18, 21, 24, 27 },
/*22*/ new [] { 4, 7, 13, 16, 22, 25 },
/*23*/ new [] { 5, 8, 14, 17, 23, 26 },
/*24*/ new [] { 6, 9, 15, 18, 24, 27 },
/*25*/ new [] { 7, 16, 25 },
/*26*/ new [] { 8, 17, 26 },
/*27*/ new [] { 9, 18, 27 },
};
int numFields = validAssignments.Length - 1;
for (int i = 1; i <= numFields; i++)
{
for (int j = 1; j <= numFields; j++)
{
try
{
var comp = CreateCompilation(string.Format(text, i, j));
var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
if (!validAssignments[i].Contains(j))
{
Assert.Equal(ErrorCode.ERR_NoImplicitConvCast, (ErrorCode)errors.Single().Code);
}
else
{
Assert.Empty(errors);
}
}
catch (Exception)
{
Console.WriteLine("Failed on assignment i{0:d2} = i{1:d2}", i, j);
throw;
}
}
}
}
/// <summary>
/// Test generic interface assignment with type parameter variance.
/// </summary>
[Fact]
public void TestDelegateAssignment()
{
var text = @"
delegate TOut D<in TIn, out TOut, T>(TIn tIn, T t);
class A {{ }}
class B : A {{ }}
class C : B {{ }}
class Test
{{
static D<A, A, A> d01 = null;
static D<A, A, B> d02 = null;
static D<A, A, C> d03 = null;
static D<A, B, A> d04 = null;
static D<A, B, B> d05 = null;
static D<A, B, C> d06 = null;
static D<A, C, A> d07 = null;
static D<A, C, B> d08 = null;
static D<A, C, C> d09 = null;
static D<B, A, A> d10 = null;
static D<B, A, B> d11 = null;
static D<B, A, C> d12 = null;
static D<B, B, A> d13 = null;
static D<B, B, B> d14 = null;
static D<B, B, C> d15 = null;
static D<B, C, A> d16 = null;
static D<B, C, B> d17 = null;
static D<B, C, C> d18 = null;
static D<C, A, A> d19 = null;
static D<C, A, B> d20 = null;
static D<C, A, C> d21 = null;
static D<C, B, A> d22 = null;
static D<C, B, B> d23 = null;
static D<C, B, C> d24 = null;
static D<C, C, A> d25 = null;
static D<C, C, B> d26 = null;
static D<C, C, C> d27 = null;
static void Main()
{{
d{0:d2} = d{1:d2};
}}
}}";
// Table comes from manual Dev10 testing
int[][] validAssignments = new int[][]
{
/*filler for 1-indexing*/ new int[0],
/*01*/
new [] { 1, 4, 7 },
/*02*/ new [] { 2, 5, 8 },
/*03*/ new [] { 3, 6, 9 },
/*04*/ new [] { 4, 7 },
/*05*/ new [] { 5, 8 },
/*06*/ new [] { 6, 9 },
/*07*/ new [] { 7 },
/*08*/ new [] { 8 },
/*09*/ new [] { 9 },
/*10*/ new [] { 1, 4, 7, 10, 13, 16 },
/*11*/ new [] { 2, 5, 8, 11, 14, 17 },
/*12*/ new [] { 3, 6, 9, 12, 15, 18 },
/*13*/ new [] { 4, 7, 13, 16 },
/*14*/ new [] { 5, 8, 14, 17 },
/*15*/ new [] { 6, 9, 15, 18 },
/*16*/ new [] { 7, 16 },
/*17*/ new [] { 8, 17 },
/*18*/ new [] { 9, 18 },
/*19*/ new [] { 1, 4, 7, 10, 13, 16, 19, 22, 25 },
/*20*/ new [] { 2, 5, 8, 11, 14, 17, 20, 23, 26 },
/*21*/ new [] { 3, 6, 9, 12, 15, 18, 21, 24, 27 },
/*22*/ new [] { 4, 7, 13, 16, 22, 25 },
/*23*/ new [] { 5, 8, 14, 17, 23, 26 },
/*24*/ new [] { 6, 9, 15, 18, 24, 27 },
/*25*/ new [] { 7, 16, 25 },
/*26*/ new [] { 8, 17, 26 },
/*27*/ new [] { 9, 18, 27 },
};
int numFields = validAssignments.Length - 1;
for (int i = 1; i <= numFields; i++)
{
for (int j = 1; j <= numFields; j++)
{
try
{
var comp = CreateCompilation(string.Format(text, i, j));
var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
if (!validAssignments[i].Contains(j))
{
var code = (ErrorCode)errors.Single().Code;
// UNDONE: which one will be used is predictable, but confirming that the behavior
// exactly matches dev10 is probably too tedious to be worthwhile
Assert.True(code == ErrorCode.ERR_NoImplicitConvCast || code == ErrorCode.ERR_NoImplicitConv, "Unexpected error code " + code);
}
else
{
Assert.Empty(errors);
}
}
catch (Exception)
{
Console.WriteLine("Failed on assignment d{0:d2} = d{1:d2}", i, j);
throw;
}
}
}
}
/// <remarks>Based on LambdaTests.TestLambdaErrors03</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionCycle()
{
// To determine which overload is better, we have to try to convert D<IIn<I>> to D<I>
// and vice versa. The former is impossible and the latter is possible if and only
// if it is possible (i.e. cycle).
var text = @"
interface IIn<in TIn> { }
interface I : IIn<IIn<I>> { }
delegate T D<out T>();
class C
{
static void Goo(D<IIn<I>> x) { }
static void Goo(D<I> x) { }
static void M()
{
Goo(null);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (13,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Goo(D<IIn<I>>)' and 'C.Goo(D<I>)'
Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("C.Goo(D<IIn<I>>)", "C.Goo(D<I>)"));
}
/// <remarks>http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionInfiniteExpansion01()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
public interface IN<in U> {}
public interface IC<X> : IN<IN<IC<IC<X>>>> {}
class C
{
static void M()
{
IC<double> bar = null;
IN<IC<string>> goo = bar;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (10,30): error CS0266: Cannot implicitly convert type 'IC<double>' to 'IN<IC<string>>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "bar").WithArguments("IC<double>", "IN<IC<string>>"));
}
/// <remarks>http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionInfiniteExpansion02()
{
var text = @"
interface A<in B> where B : class
{
}
interface B<in A> where A : class
{
}
class X : A<B<X>>
{
}
class Y : B<A<Y>>
{
}
class Test
{
static void Main ()
{
A<Y> x = new X ();
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (22,19): error CS0266: Cannot implicitly convert type 'X' to 'A<Y>'. An explicit conversion exists (are you missing a cast?)
// A<Y> x = new X ();
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new X ()").WithArguments("X", "A<Y>")
);
}
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
[Fact]
public void TestVarianceConversionLongFailure()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
interface A : B<B<A>> {}
interface B<T> : C<C<T>> {}
interface C<T> : D<D<T>> {}
interface D<T> : E<E<T>> {}
interface E<T> : F<F<T>> {}
interface F<T> : N<N<T>> {}
interface X : Y<Y<N<N<X>>>> {}
interface Y<T> : Z<Z<T>> {}
interface Z<T> : W<W<T>> {}
interface W<T> : U<U<T>> {}
interface U<T> : V<V<T>> {}
interface V<T> : N<N<T>> {}
interface N<in T> {}
class M {
static void Main() {
A a = null;
N<X> nx = a;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (22,15): error CS0266: Cannot implicitly convert type 'A' to 'N<X>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("A", "N<X>"));
}
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
[WorkItem(529488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529488")]
[Fact]
public void TestVarianceConversionLongSuccess_Breaking()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
interface A : B<B<A>> { }
interface B<T> : C<C<T>> { }
interface C<T> : D<D<T>> { }
interface D<T> : E<E<T>> { }
interface E<T> : F<F<T>> { }
interface F<T> : N<N<T>> { }
interface X : Y<Y<N<F<E<D<C<B<A>>>>>>>> { }
interface Y<T> : Z<Z<T>> { }
interface Z<T> : W<W<T>> { }
interface W<T> : U<U<T>> { }
interface U<T> : V<V<T>> { }
interface V<T> : N<N<T>> { }
interface N<in T> { }
class M
{
static void Main()
{
A a = null;
N<X> nx = a;
}
}
";
// There should not be any diagnostics, but we blow our stack and make a guess.
// NB: this is a breaking change.
CreateCompilation(text).VerifyDiagnostics(
// (24,19): error CS0266: Cannot implicitly convert type 'A' to 'N<X>'. An explicit conversion exists (are you missing a cast?)
// N<X> nx = a;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("A", "N<X>"));
}
[WorkItem(542482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542482")]
[Fact]
public void CS1961ERR_UnexpectedVariance_ConstraintTypes()
{
var text =
@"interface IIn<in T> { }
interface IOut<out T> { }
class C<T> { }
interface I1<out T, in U, V>
{
void M<X>() where X : T, U, V;
}
interface I2<out T, in U, V>
{
void M<X>() where X : IOut<T>, IOut<U>, IOut<V>;
}
interface I3<out T, in U, V>
{
void M<X>() where X : IIn<T>, IIn<U>, IIn<V>;
}
interface I4<out T, in U, V>
{
void M1<X>() where X : C<T>;
void M2<X>() where X : C<U>;
void M3<X>() where X : C<V>;
}";
CreateCompilation(text).VerifyDiagnostics(
// (6,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I1<T, U, V>.M<X>()'. 'T' is covariant.
// void M<X>() where X : T, U, V;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I1<T, U, V>.M<X>()", "T", "covariant", "contravariantly").WithLocation(6, 12),
// (10,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I2<T, U, V>.M<X>()'. 'T' is covariant.
// void M<X>() where X : IOut<T>, IOut<U>, IOut<V>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I2<T, U, V>.M<X>()", "T", "covariant", "contravariantly").WithLocation(10, 12),
// (14,12): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I3<T, U, V>.M<X>()'. 'U' is contravariant.
// void M<X>() where X : IIn<T>, IIn<U>, IIn<V>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I3<T, U, V>.M<X>()", "U", "contravariant", "covariantly").WithLocation(14, 12),
// (18,13): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U, V>.M1<X>()'. 'T' is covariant.
// void M1<X>() where X : C<T>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I4<T, U, V>.M1<X>()", "T", "covariant", "invariantly").WithLocation(18, 13),
// (19,13): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I4<T, U, V>.M2<X>()'. 'U' is contravariant.
// void M2<X>() where X : C<U>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I4<T, U, V>.M2<X>()", "U", "contravariant", "invariantly").WithLocation(19, 13));
}
[Fact]
public void CS1961ERR_UnexpectedVariance_ClassesAndStructs()
{
var text =
@"class C<T> { }
struct S<T> { }
interface I1<out T, U>
{
C<T> M(C<U> o);
}
interface I2<out T, U>
{
C<U> M(C<T> o);
}
interface I3<out T, U>
{
S<T> M(S<U> o);
}
interface I4<out T, U>
{
S<U> M(S<T> o);
}
interface I5<in T, U>
{
C<T> M(C<U> o);
}
interface I6<in T, U>
{
C<U> M(C<T> o);
}
interface I7<in T, U>
{
S<T> M(S<U> o);
}
interface I8<in T, U>
{
S<U> M(S<T> o);
}";
CreateCompilation(text).VerifyDiagnostics(
// (5,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I1<T, U>.M(C<U>)'. 'T' is covariant.
// C<T> M(C<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I1<T, U>.M(C<U>)", "T", "covariant", "invariantly").WithLocation(5, 5),
// (9,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I2<T, U>.M(C<T>)'. 'T' is covariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I2<T, U>.M(C<T>)", "T", "covariant", "invariantly").WithLocation(9, 12),
// (13,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I3<T, U>.M(S<U>)'. 'T' is covariant.
// S<T> M(S<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I3<T, U>.M(S<U>)", "T", "covariant", "invariantly").WithLocation(13, 5),
// (17,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U>.M(S<T>)'. 'T' is covariant.
// S<U> M(S<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I4<T, U>.M(S<T>)", "T", "covariant", "invariantly").WithLocation(17, 12),
// (21,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I5<T, U>.M(C<U>)'. 'T' is contravariant.
// C<T> M(C<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I5<T, U>.M(C<U>)", "T", "contravariant", "invariantly").WithLocation(21, 5),
// (25,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I6<T, U>.M(C<T>)'. 'T' is contravariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I6<T, U>.M(C<T>)", "T", "contravariant", "invariantly").WithLocation(25, 12),
// (29,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I7<T, U>.M(S<U>)'. 'T' is contravariant.
// S<T> M(S<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I7<T, U>.M(S<U>)", "T", "contravariant", "invariantly").WithLocation(29, 5),
// (33,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I8<T, U>.M(S<T>)'. 'T' is contravariant.
// S<U> M(S<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I8<T, U>.M(S<T>)", "T", "contravariant", "invariantly").WithLocation(33, 12));
}
[WorkItem(602022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602022")]
[Fact]
public void CS1961ERR_UnexpectedVariance_Enums()
{
var text =
@"class C<T>
{
public enum E { }
}
interface I1<out T, U>
{
C<T>.E M(C<U>.E o);
}
interface I2<out T, U>
{
C<U>.E M(C<T>.E o);
}
interface I3<in T, U>
{
C<T>.E M(C<U>.E o);
}
interface I4<in T, U>
{
C<U>.E M(C<T>.E o);
}";
CreateCompilation(text).VerifyDiagnostics(
// (7,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I1<T, U>.M(C<U>.E)'. 'T' is covariant.
// C<T>.E M(C<U>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I1<T, U>.M(C<U>.E)", "T", "covariant", "invariantly").WithLocation(7, 5),
// (11,14): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I2<T, U>.M(C<T>.E)'. 'T' is covariant.
// C<U>.E M(C<T>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I2<T, U>.M(C<T>.E)", "T", "covariant", "invariantly").WithLocation(11, 14),
// (15,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I3<T, U>.M(C<U>.E)'. 'T' is contravariant.
// C<T>.E M(C<U>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I3<T, U>.M(C<U>.E)", "T", "contravariant", "invariantly").WithLocation(15, 5),
// (19,14): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U>.M(C<T>.E)'. 'T' is contravariant.
// C<U>.E M(C<T>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I4<T, U>.M(C<T>.E)", "T", "contravariant", "invariantly").WithLocation(19, 14));
}
[WorkItem(542794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542794")]
[Fact]
public void ContravariantBaseInterface()
{
var text =
@"
interface IA<in T> { }
interface IB<in T> : IA<IB<T>> { }
";
CreateCompilation(text).VerifyDiagnostics(
// (3,17): error CS1961: Invalid variance: The type parameter 'T' must be covariantly valid on 'IA<IB<T>>'. 'T' is contravariant.
// interface IB<in T> : IA<IB<T>> { }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("IA<IB<T>>", "T", "contravariant", "covariantly").WithLocation(3, 17));
}
/// <summary>
/// Report errors on type parameter use
/// rather than declaration.
/// </summary>
[WorkItem(855750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/855750")]
[Fact]
public void ErrorLocations()
{
var text =
@"interface IIn<in T> { }
interface IOut<out T> { }
class C<T> { }
delegate void D<in T>();
interface I<out T, in U>
{
C<U> M(C<T> o);
IIn<T>[] P { get; }
U this[object o] { get; }
event D<U> E;
void M<X>()
where X : C<IIn<U>>, IOut<T>;
}
interface I<out T> :
I<T, T>
{
}";
CreateCompilation(text).VerifyDiagnostics(
// (7,5): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I<T, U>.M(C<T>)'. 'U' is contravariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<U>").WithArguments("I<T, U>.M(C<T>)", "U", "contravariant", "invariantly").WithLocation(7, 5),
// (7,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I<T, U>.M(C<T>)'. 'T' is covariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I<T, U>.M(C<T>)", "T", "covariant", "invariantly").WithLocation(7, 12),
// (8,5): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, U>.P'. 'T' is covariant.
// IIn<T>[] P { get; }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<T>[]").WithArguments("I<T, U>.P", "T", "covariant", "contravariantly").WithLocation(8, 5),
// (9,5): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I<T, U>.this[object]'. 'U' is contravariant.
// U this[object o] { get; }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "U").WithArguments("I<T, U>.this[object]", "U", "contravariant", "covariantly").WithLocation(9, 5),
// (10,16): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I<T, U>.E'. 'U' is contravariant.
// event D<U> E;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E").WithArguments("I<T, U>.E", "U", "contravariant", "covariantly").WithLocation(10, 16),
// (11,12): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I<T, U>.M<X>()'. 'U' is contravariant.
// void M<X>()
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I<T, U>.M<X>()", "U", "contravariant", "invariantly").WithLocation(11, 12),
// (11,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, U>.M<X>()'. 'T' is covariant.
// void M<X>()
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I<T, U>.M<X>()", "T", "covariant", "contravariantly").WithLocation(11, 12),
// (14,17): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, T>'. 'T' is covariant.
// interface I<out T> :
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("I<T, T>", "T", "covariant", "contravariantly").WithLocation(14, 17));
}
[Fact]
public void CovarianceBoundariesForRefReadOnly_Parameters()
{
CreateCompilation(@"
interface ITest<in T>
{
void M(in T p);
}").VerifyDiagnostics(
// (4,15): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'ITest<T>.M(in T)'. 'T' is contravariant.
// void M(in T p);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("ITest<T>.M(in T)", "T", "contravariant", "invariantly").WithLocation(4, 15));
}
[Fact]
public void CovarianceBoundariesForRefReadOnly_ReturnType()
{
CreateCompilation(@"
interface ITest<in T>
{
ref readonly T M();
}").VerifyDiagnostics(
// (4,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'ITest<T>.M()'. 'T' is contravariant.
// ref readonly T M();
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref readonly T").WithArguments("ITest<T>.M()", "T", "contravariant", "invariantly").WithLocation(4, 5));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class VarianceTests : CompilingTestBase
{
/// <summary>
/// Test generic interface assignment with type parameter variance.
/// </summary>
[Fact]
public void TestInterfaceAssignment()
{
var text = @"
interface I<in TIn, out TOut, T> {{ }}
class A {{ }}
class B : A {{ }}
class C : B {{ }}
class Test
{{
static I<A, A, A> i01 = null;
static I<A, A, B> i02 = null;
static I<A, A, C> i03 = null;
static I<A, B, A> i04 = null;
static I<A, B, B> i05 = null;
static I<A, B, C> i06 = null;
static I<A, C, A> i07 = null;
static I<A, C, B> i08 = null;
static I<A, C, C> i09 = null;
static I<B, A, A> i10 = null;
static I<B, A, B> i11 = null;
static I<B, A, C> i12 = null;
static I<B, B, A> i13 = null;
static I<B, B, B> i14 = null;
static I<B, B, C> i15 = null;
static I<B, C, A> i16 = null;
static I<B, C, B> i17 = null;
static I<B, C, C> i18 = null;
static I<C, A, A> i19 = null;
static I<C, A, B> i20 = null;
static I<C, A, C> i21 = null;
static I<C, B, A> i22 = null;
static I<C, B, B> i23 = null;
static I<C, B, C> i24 = null;
static I<C, C, A> i25 = null;
static I<C, C, B> i26 = null;
static I<C, C, C> i27 = null;
static void Main()
{{
i{0:d2} = i{1:d2};
}}
}}";
// Table comes from manual Dev10 testing
int[][] validAssignments = new int[][]
{
/*filler for 1-indexing*/ new int[0],
/*01*/
new [] { 1, 4, 7 },
/*02*/ new [] { 2, 5, 8 },
/*03*/ new [] { 3, 6, 9 },
/*04*/ new [] { 4, 7 },
/*05*/ new [] { 5, 8 },
/*06*/ new [] { 6, 9 },
/*07*/ new [] { 7 },
/*08*/ new [] { 8 },
/*09*/ new [] { 9 },
/*10*/ new [] { 1, 4, 7, 10, 13, 16 },
/*11*/ new [] { 2, 5, 8, 11, 14, 17 },
/*12*/ new [] { 3, 6, 9, 12, 15, 18 },
/*13*/ new [] { 4, 7, 13, 16 },
/*14*/ new [] { 5, 8, 14, 17 },
/*15*/ new [] { 6, 9, 15, 18 },
/*16*/ new [] { 7, 16 },
/*17*/ new [] { 8, 17 },
/*18*/ new [] { 9, 18 },
/*19*/ new [] { 1, 4, 7, 10, 13, 16, 19, 22, 25 },
/*20*/ new [] { 2, 5, 8, 11, 14, 17, 20, 23, 26 },
/*21*/ new [] { 3, 6, 9, 12, 15, 18, 21, 24, 27 },
/*22*/ new [] { 4, 7, 13, 16, 22, 25 },
/*23*/ new [] { 5, 8, 14, 17, 23, 26 },
/*24*/ new [] { 6, 9, 15, 18, 24, 27 },
/*25*/ new [] { 7, 16, 25 },
/*26*/ new [] { 8, 17, 26 },
/*27*/ new [] { 9, 18, 27 },
};
int numFields = validAssignments.Length - 1;
for (int i = 1; i <= numFields; i++)
{
for (int j = 1; j <= numFields; j++)
{
try
{
var comp = CreateCompilation(string.Format(text, i, j));
var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
if (!validAssignments[i].Contains(j))
{
Assert.Equal(ErrorCode.ERR_NoImplicitConvCast, (ErrorCode)errors.Single().Code);
}
else
{
Assert.Empty(errors);
}
}
catch (Exception)
{
Console.WriteLine("Failed on assignment i{0:d2} = i{1:d2}", i, j);
throw;
}
}
}
}
/// <summary>
/// Test generic interface assignment with type parameter variance.
/// </summary>
[Fact]
public void TestDelegateAssignment()
{
var text = @"
delegate TOut D<in TIn, out TOut, T>(TIn tIn, T t);
class A {{ }}
class B : A {{ }}
class C : B {{ }}
class Test
{{
static D<A, A, A> d01 = null;
static D<A, A, B> d02 = null;
static D<A, A, C> d03 = null;
static D<A, B, A> d04 = null;
static D<A, B, B> d05 = null;
static D<A, B, C> d06 = null;
static D<A, C, A> d07 = null;
static D<A, C, B> d08 = null;
static D<A, C, C> d09 = null;
static D<B, A, A> d10 = null;
static D<B, A, B> d11 = null;
static D<B, A, C> d12 = null;
static D<B, B, A> d13 = null;
static D<B, B, B> d14 = null;
static D<B, B, C> d15 = null;
static D<B, C, A> d16 = null;
static D<B, C, B> d17 = null;
static D<B, C, C> d18 = null;
static D<C, A, A> d19 = null;
static D<C, A, B> d20 = null;
static D<C, A, C> d21 = null;
static D<C, B, A> d22 = null;
static D<C, B, B> d23 = null;
static D<C, B, C> d24 = null;
static D<C, C, A> d25 = null;
static D<C, C, B> d26 = null;
static D<C, C, C> d27 = null;
static void Main()
{{
d{0:d2} = d{1:d2};
}}
}}";
// Table comes from manual Dev10 testing
int[][] validAssignments = new int[][]
{
/*filler for 1-indexing*/ new int[0],
/*01*/
new [] { 1, 4, 7 },
/*02*/ new [] { 2, 5, 8 },
/*03*/ new [] { 3, 6, 9 },
/*04*/ new [] { 4, 7 },
/*05*/ new [] { 5, 8 },
/*06*/ new [] { 6, 9 },
/*07*/ new [] { 7 },
/*08*/ new [] { 8 },
/*09*/ new [] { 9 },
/*10*/ new [] { 1, 4, 7, 10, 13, 16 },
/*11*/ new [] { 2, 5, 8, 11, 14, 17 },
/*12*/ new [] { 3, 6, 9, 12, 15, 18 },
/*13*/ new [] { 4, 7, 13, 16 },
/*14*/ new [] { 5, 8, 14, 17 },
/*15*/ new [] { 6, 9, 15, 18 },
/*16*/ new [] { 7, 16 },
/*17*/ new [] { 8, 17 },
/*18*/ new [] { 9, 18 },
/*19*/ new [] { 1, 4, 7, 10, 13, 16, 19, 22, 25 },
/*20*/ new [] { 2, 5, 8, 11, 14, 17, 20, 23, 26 },
/*21*/ new [] { 3, 6, 9, 12, 15, 18, 21, 24, 27 },
/*22*/ new [] { 4, 7, 13, 16, 22, 25 },
/*23*/ new [] { 5, 8, 14, 17, 23, 26 },
/*24*/ new [] { 6, 9, 15, 18, 24, 27 },
/*25*/ new [] { 7, 16, 25 },
/*26*/ new [] { 8, 17, 26 },
/*27*/ new [] { 9, 18, 27 },
};
int numFields = validAssignments.Length - 1;
for (int i = 1; i <= numFields; i++)
{
for (int j = 1; j <= numFields; j++)
{
try
{
var comp = CreateCompilation(string.Format(text, i, j));
var errors = comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error);
if (!validAssignments[i].Contains(j))
{
var code = (ErrorCode)errors.Single().Code;
// UNDONE: which one will be used is predictable, but confirming that the behavior
// exactly matches dev10 is probably too tedious to be worthwhile
Assert.True(code == ErrorCode.ERR_NoImplicitConvCast || code == ErrorCode.ERR_NoImplicitConv, "Unexpected error code " + code);
}
else
{
Assert.Empty(errors);
}
}
catch (Exception)
{
Console.WriteLine("Failed on assignment d{0:d2} = d{1:d2}", i, j);
throw;
}
}
}
}
/// <remarks>Based on LambdaTests.TestLambdaErrors03</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionCycle()
{
// To determine which overload is better, we have to try to convert D<IIn<I>> to D<I>
// and vice versa. The former is impossible and the latter is possible if and only
// if it is possible (i.e. cycle).
var text = @"
interface IIn<in TIn> { }
interface I : IIn<IIn<I>> { }
delegate T D<out T>();
class C
{
static void Goo(D<IIn<I>> x) { }
static void Goo(D<I> x) { }
static void M()
{
Goo(null);
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (13,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Goo(D<IIn<I>>)' and 'C.Goo(D<I>)'
Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("C.Goo(D<IIn<I>>)", "C.Goo(D<I>)"));
}
/// <remarks>http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionInfiniteExpansion01()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
public interface IN<in U> {}
public interface IC<X> : IN<IN<IC<IC<X>>>> {}
class C
{
static void M()
{
IC<double> bar = null;
IN<IC<string>> goo = bar;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (10,30): error CS0266: Cannot implicitly convert type 'IC<double>' to 'IN<IC<string>>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "bar").WithArguments("IC<double>", "IN<IC<string>>"));
}
/// <remarks>http://blogs.msdn.com/b/ericlippert/archive/2008/05/07/covariance-and-contravariance-part-twelve-to-infinity-but-not-beyond.aspx</remarks>
[Fact]
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
public void TestVarianceConversionInfiniteExpansion02()
{
var text = @"
interface A<in B> where B : class
{
}
interface B<in A> where A : class
{
}
class X : A<B<X>>
{
}
class Y : B<A<Y>>
{
}
class Test
{
static void Main ()
{
A<Y> x = new X ();
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (22,19): error CS0266: Cannot implicitly convert type 'X' to 'A<Y>'. An explicit conversion exists (are you missing a cast?)
// A<Y> x = new X ();
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new X ()").WithArguments("X", "A<Y>")
);
}
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
[Fact]
public void TestVarianceConversionLongFailure()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
interface A : B<B<A>> {}
interface B<T> : C<C<T>> {}
interface C<T> : D<D<T>> {}
interface D<T> : E<E<T>> {}
interface E<T> : F<F<T>> {}
interface F<T> : N<N<T>> {}
interface X : Y<Y<N<N<X>>>> {}
interface Y<T> : Z<Z<T>> {}
interface Z<T> : W<W<T>> {}
interface W<T> : U<U<T>> {}
interface U<T> : V<V<T>> {}
interface V<T> : N<N<T>> {}
interface N<in T> {}
class M {
static void Main() {
A a = null;
N<X> nx = a;
}
}
";
CreateCompilation(text).VerifyDiagnostics(
// (22,15): error CS0266: Cannot implicitly convert type 'A' to 'N<X>'. An explicit conversion exists (are you missing a cast?)
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("A", "N<X>"));
}
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
[WorkItem(529488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529488")]
[Fact]
public void TestVarianceConversionLongSuccess_Breaking()
{
// IC<double> is convertible to IN<IC<string>> if and only
// if IC<IC<double>> is convertible to IN<IC<IC<string>>>.
var text = @"
interface A : B<B<A>> { }
interface B<T> : C<C<T>> { }
interface C<T> : D<D<T>> { }
interface D<T> : E<E<T>> { }
interface E<T> : F<F<T>> { }
interface F<T> : N<N<T>> { }
interface X : Y<Y<N<F<E<D<C<B<A>>>>>>>> { }
interface Y<T> : Z<Z<T>> { }
interface Z<T> : W<W<T>> { }
interface W<T> : U<U<T>> { }
interface U<T> : V<V<T>> { }
interface V<T> : N<N<T>> { }
interface N<in T> { }
class M
{
static void Main()
{
A a = null;
N<X> nx = a;
}
}
";
// There should not be any diagnostics, but we blow our stack and make a guess.
// NB: this is a breaking change.
CreateCompilation(text).VerifyDiagnostics(
// (24,19): error CS0266: Cannot implicitly convert type 'A' to 'N<X>'. An explicit conversion exists (are you missing a cast?)
// N<X> nx = a;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "a").WithArguments("A", "N<X>"));
}
[WorkItem(542482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542482")]
[Fact]
public void CS1961ERR_UnexpectedVariance_ConstraintTypes()
{
var text =
@"interface IIn<in T> { }
interface IOut<out T> { }
class C<T> { }
interface I1<out T, in U, V>
{
void M<X>() where X : T, U, V;
}
interface I2<out T, in U, V>
{
void M<X>() where X : IOut<T>, IOut<U>, IOut<V>;
}
interface I3<out T, in U, V>
{
void M<X>() where X : IIn<T>, IIn<U>, IIn<V>;
}
interface I4<out T, in U, V>
{
void M1<X>() where X : C<T>;
void M2<X>() where X : C<U>;
void M3<X>() where X : C<V>;
}";
CreateCompilation(text).VerifyDiagnostics(
// (6,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I1<T, U, V>.M<X>()'. 'T' is covariant.
// void M<X>() where X : T, U, V;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I1<T, U, V>.M<X>()", "T", "covariant", "contravariantly").WithLocation(6, 12),
// (10,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I2<T, U, V>.M<X>()'. 'T' is covariant.
// void M<X>() where X : IOut<T>, IOut<U>, IOut<V>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I2<T, U, V>.M<X>()", "T", "covariant", "contravariantly").WithLocation(10, 12),
// (14,12): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I3<T, U, V>.M<X>()'. 'U' is contravariant.
// void M<X>() where X : IIn<T>, IIn<U>, IIn<V>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I3<T, U, V>.M<X>()", "U", "contravariant", "covariantly").WithLocation(14, 12),
// (18,13): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U, V>.M1<X>()'. 'T' is covariant.
// void M1<X>() where X : C<T>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I4<T, U, V>.M1<X>()", "T", "covariant", "invariantly").WithLocation(18, 13),
// (19,13): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I4<T, U, V>.M2<X>()'. 'U' is contravariant.
// void M2<X>() where X : C<U>;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I4<T, U, V>.M2<X>()", "U", "contravariant", "invariantly").WithLocation(19, 13));
}
[Fact]
public void CS1961ERR_UnexpectedVariance_ClassesAndStructs()
{
var text =
@"class C<T> { }
struct S<T> { }
interface I1<out T, U>
{
C<T> M(C<U> o);
}
interface I2<out T, U>
{
C<U> M(C<T> o);
}
interface I3<out T, U>
{
S<T> M(S<U> o);
}
interface I4<out T, U>
{
S<U> M(S<T> o);
}
interface I5<in T, U>
{
C<T> M(C<U> o);
}
interface I6<in T, U>
{
C<U> M(C<T> o);
}
interface I7<in T, U>
{
S<T> M(S<U> o);
}
interface I8<in T, U>
{
S<U> M(S<T> o);
}";
CreateCompilation(text).VerifyDiagnostics(
// (5,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I1<T, U>.M(C<U>)'. 'T' is covariant.
// C<T> M(C<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I1<T, U>.M(C<U>)", "T", "covariant", "invariantly").WithLocation(5, 5),
// (9,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I2<T, U>.M(C<T>)'. 'T' is covariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I2<T, U>.M(C<T>)", "T", "covariant", "invariantly").WithLocation(9, 12),
// (13,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I3<T, U>.M(S<U>)'. 'T' is covariant.
// S<T> M(S<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I3<T, U>.M(S<U>)", "T", "covariant", "invariantly").WithLocation(13, 5),
// (17,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U>.M(S<T>)'. 'T' is covariant.
// S<U> M(S<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I4<T, U>.M(S<T>)", "T", "covariant", "invariantly").WithLocation(17, 12),
// (21,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I5<T, U>.M(C<U>)'. 'T' is contravariant.
// C<T> M(C<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I5<T, U>.M(C<U>)", "T", "contravariant", "invariantly").WithLocation(21, 5),
// (25,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I6<T, U>.M(C<T>)'. 'T' is contravariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I6<T, U>.M(C<T>)", "T", "contravariant", "invariantly").WithLocation(25, 12),
// (29,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I7<T, U>.M(S<U>)'. 'T' is contravariant.
// S<T> M(S<U> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I7<T, U>.M(S<U>)", "T", "contravariant", "invariantly").WithLocation(29, 5),
// (33,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I8<T, U>.M(S<T>)'. 'T' is contravariant.
// S<U> M(S<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "S<T>").WithArguments("I8<T, U>.M(S<T>)", "T", "contravariant", "invariantly").WithLocation(33, 12));
}
[WorkItem(602022, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602022")]
[Fact]
public void CS1961ERR_UnexpectedVariance_Enums()
{
var text =
@"class C<T>
{
public enum E { }
}
interface I1<out T, U>
{
C<T>.E M(C<U>.E o);
}
interface I2<out T, U>
{
C<U>.E M(C<T>.E o);
}
interface I3<in T, U>
{
C<T>.E M(C<U>.E o);
}
interface I4<in T, U>
{
C<U>.E M(C<T>.E o);
}";
CreateCompilation(text).VerifyDiagnostics(
// (7,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I1<T, U>.M(C<U>.E)'. 'T' is covariant.
// C<T>.E M(C<U>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I1<T, U>.M(C<U>.E)", "T", "covariant", "invariantly").WithLocation(7, 5),
// (11,14): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I2<T, U>.M(C<T>.E)'. 'T' is covariant.
// C<U>.E M(C<T>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I2<T, U>.M(C<T>.E)", "T", "covariant", "invariantly").WithLocation(11, 14),
// (15,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I3<T, U>.M(C<U>.E)'. 'T' is contravariant.
// C<T>.E M(C<U>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I3<T, U>.M(C<U>.E)", "T", "contravariant", "invariantly").WithLocation(15, 5),
// (19,14): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I4<T, U>.M(C<T>.E)'. 'T' is contravariant.
// C<U>.E M(C<T>.E o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>.E").WithArguments("I4<T, U>.M(C<T>.E)", "T", "contravariant", "invariantly").WithLocation(19, 14));
}
[WorkItem(542794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542794")]
[Fact]
public void ContravariantBaseInterface()
{
var text =
@"
interface IA<in T> { }
interface IB<in T> : IA<IB<T>> { }
";
CreateCompilation(text).VerifyDiagnostics(
// (3,17): error CS1961: Invalid variance: The type parameter 'T' must be covariantly valid on 'IA<IB<T>>'. 'T' is contravariant.
// interface IB<in T> : IA<IB<T>> { }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("IA<IB<T>>", "T", "contravariant", "covariantly").WithLocation(3, 17));
}
/// <summary>
/// Report errors on type parameter use
/// rather than declaration.
/// </summary>
[WorkItem(855750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/855750")]
[Fact]
public void ErrorLocations()
{
var text =
@"interface IIn<in T> { }
interface IOut<out T> { }
class C<T> { }
delegate void D<in T>();
interface I<out T, in U>
{
C<U> M(C<T> o);
IIn<T>[] P { get; }
U this[object o] { get; }
event D<U> E;
void M<X>()
where X : C<IIn<U>>, IOut<T>;
}
interface I<out T> :
I<T, T>
{
}";
CreateCompilation(text).VerifyDiagnostics(
// (7,5): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I<T, U>.M(C<T>)'. 'U' is contravariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<U>").WithArguments("I<T, U>.M(C<T>)", "U", "contravariant", "invariantly").WithLocation(7, 5),
// (7,12): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'I<T, U>.M(C<T>)'. 'T' is covariant.
// C<U> M(C<T> o);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "C<T>").WithArguments("I<T, U>.M(C<T>)", "T", "covariant", "invariantly").WithLocation(7, 12),
// (8,5): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, U>.P'. 'T' is covariant.
// IIn<T>[] P { get; }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "IIn<T>[]").WithArguments("I<T, U>.P", "T", "covariant", "contravariantly").WithLocation(8, 5),
// (9,5): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I<T, U>.this[object]'. 'U' is contravariant.
// U this[object o] { get; }
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "U").WithArguments("I<T, U>.this[object]", "U", "contravariant", "covariantly").WithLocation(9, 5),
// (10,16): error CS1961: Invalid variance: The type parameter 'U' must be covariantly valid on 'I<T, U>.E'. 'U' is contravariant.
// event D<U> E;
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "E").WithArguments("I<T, U>.E", "U", "contravariant", "covariantly").WithLocation(10, 16),
// (11,12): error CS1961: Invalid variance: The type parameter 'U' must be invariantly valid on 'I<T, U>.M<X>()'. 'U' is contravariant.
// void M<X>()
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I<T, U>.M<X>()", "U", "contravariant", "invariantly").WithLocation(11, 12),
// (11,12): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, U>.M<X>()'. 'T' is covariant.
// void M<X>()
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "X").WithArguments("I<T, U>.M<X>()", "T", "covariant", "contravariantly").WithLocation(11, 12),
// (14,17): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'I<T, T>'. 'T' is covariant.
// interface I<out T> :
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("I<T, T>", "T", "covariant", "contravariantly").WithLocation(14, 17));
}
[Fact]
public void CovarianceBoundariesForRefReadOnly_Parameters()
{
CreateCompilation(@"
interface ITest<in T>
{
void M(in T p);
}").VerifyDiagnostics(
// (4,15): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'ITest<T>.M(in T)'. 'T' is contravariant.
// void M(in T p);
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("ITest<T>.M(in T)", "T", "contravariant", "invariantly").WithLocation(4, 15));
}
[Fact]
public void CovarianceBoundariesForRefReadOnly_ReturnType()
{
CreateCompilation(@"
interface ITest<in T>
{
ref readonly T M();
}").VerifyDiagnostics(
// (4,5): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'ITest<T>.M()'. 'T' is contravariant.
// ref readonly T M();
Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref readonly T").WithArguments("ITest<T>.M()", "T", "contravariant", "invariantly").WithLocation(4, 5));
}
}
}
| -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/Core/Def/Implementation/SemanticClassificationCache/SemanticClassificationCacheIncrementalAnalyzerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SolutionCrawler;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SemanticClassificationCache
{
[ExportIncrementalAnalyzerProvider(nameof(SemanticClassificationCacheIncrementalAnalyzerProvider), new[] { WorkspaceKind.Host }), Shared]
internal class SemanticClassificationCacheIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SemanticClassificationCacheIncrementalAnalyzerProvider()
{
}
public IIncrementalAnalyzer? CreateIncrementalAnalyzer(Workspace workspace)
{
if (workspace is not VisualStudioWorkspace)
return null;
return new SemanticClassificationCacheIncrementalAnalyzer();
}
private class SemanticClassificationCacheIncrementalAnalyzer : IncrementalAnalyzerBase
{
public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken)
{
// only process C# and VB. OOP does not contain files for other languages.
if (document.Project.Language is not (LanguageNames.CSharp or LanguageNames.VisualBasic))
return;
// Only cache classifications for open files. This keeps our CPU/memory usage low, but hits the common
// case of ensuring we cache classifications for the files the user edits so that they're ready the next
// time they open VS.
if (!document.IsOpen())
return;
var solution = document.Project.Solution;
var client = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
// We don't do anything if we fail to get the external process. That's the case when something has gone
// wrong, or the user is explicitly choosing to run inproc only. In neither of those cases do we want
// to bog down the VS process with the work to semantically classify files.
return;
}
var statusService = document.Project.Solution.Workspace.Services.GetRequiredService<IWorkspaceStatusService>();
// If we're not fully loaded, then we don't want to cache classifications. The classifications we have
// will likely not be accurate. And, if we shutdown after that, we'll have cached incomplete classifications.
var isFullyLoaded = await statusService.IsFullyLoadedAsync(cancellationToken).ConfigureAwait(false);
if (!isFullyLoaded)
return;
// Call the project overload. We don't need to sync the full solution just to classify this document.
await client.TryInvokeAsync<IRemoteSemanticClassificationCacheService>(
document.Project,
(service, solutionInfo, cancellationToken) => service.CacheSemanticClassificationsAsync(solutionInfo, document.Id, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SolutionCrawler;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SemanticClassificationCache
{
[ExportIncrementalAnalyzerProvider(nameof(SemanticClassificationCacheIncrementalAnalyzerProvider), new[] { WorkspaceKind.Host }), Shared]
internal class SemanticClassificationCacheIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public SemanticClassificationCacheIncrementalAnalyzerProvider()
{
}
public IIncrementalAnalyzer? CreateIncrementalAnalyzer(Workspace workspace)
{
if (workspace is not VisualStudioWorkspace)
return null;
return new SemanticClassificationCacheIncrementalAnalyzer();
}
private class SemanticClassificationCacheIncrementalAnalyzer : IncrementalAnalyzerBase
{
public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken)
{
// only process C# and VB. OOP does not contain files for other languages.
if (document.Project.Language is not (LanguageNames.CSharp or LanguageNames.VisualBasic))
return;
// Only cache classifications for open files. This keeps our CPU/memory usage low, but hits the common
// case of ensuring we cache classifications for the files the user edits so that they're ready the next
// time they open VS.
if (!document.IsOpen())
return;
var solution = document.Project.Solution;
var client = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false);
if (client == null)
{
// We don't do anything if we fail to get the external process. That's the case when something has gone
// wrong, or the user is explicitly choosing to run inproc only. In neither of those cases do we want
// to bog down the VS process with the work to semantically classify files.
return;
}
var statusService = document.Project.Solution.Workspace.Services.GetRequiredService<IWorkspaceStatusService>();
// If we're not fully loaded, then we don't want to cache classifications. The classifications we have
// will likely not be accurate. And, if we shutdown after that, we'll have cached incomplete classifications.
var isFullyLoaded = await statusService.IsFullyLoadedAsync(cancellationToken).ConfigureAwait(false);
if (!isFullyLoaded)
return;
// Call the project overload. We don't need to sync the full solution just to classify this document.
await client.TryInvokeAsync<IRemoteSemanticClassificationCacheService>(
document.Project,
(service, solutionInfo, cancellationToken) => service.CacheSemanticClassificationsAsync(solutionInfo, document.Id, cancellationToken),
cancellationToken).ConfigureAwait(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/Workspaces/Core/Portable/DesignerAttribute/DesignerAttributeHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.DesignerAttribute
{
internal static class DesignerAttributeHelpers
{
public static async Task<string?> ComputeDesignerAttributeCategoryAsync(
INamedTypeSymbol? designerCategoryType,
Document document,
CancellationToken cancellationToken)
{
// simple case. If there's no DesignerCategory type in this compilation, then there's
// definitely no designable types. Just immediately bail out.
if (designerCategoryType == null)
return null;
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
// Legacy behavior. We only register the designer info for the first non-nested class
// in the file.
var firstClass = FindFirstNonNestedClass(
syntaxFacts, syntaxFacts.GetMembersOfCompilationUnit(root), cancellationToken);
if (firstClass == null)
return null;
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var firstClassType = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(firstClass, cancellationToken);
return TryGetDesignerCategory(firstClassType, designerCategoryType, cancellationToken);
}
private static string? TryGetDesignerCategory(
INamedTypeSymbol classType,
INamedTypeSymbol designerCategoryType,
CancellationToken cancellationToken)
{
foreach (var type in classType.GetBaseTypesAndThis())
{
cancellationToken.ThrowIfCancellationRequested();
// if it has designer attribute, set it
var attribute = type.GetAttributes().FirstOrDefault(d => designerCategoryType.Equals(d.AttributeClass));
if (attribute?.ConstructorArguments.Length == 1)
return GetArgumentString(attribute.ConstructorArguments[0]);
}
return null;
}
private static SyntaxNode? FindFirstNonNestedClass(
ISyntaxFactsService syntaxFacts, SyntaxList<SyntaxNode> members, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
if (syntaxFacts.IsNamespaceDeclaration(member))
{
var firstClass = FindFirstNonNestedClass(
syntaxFacts, syntaxFacts.GetMembersOfNamespaceDeclaration(member), cancellationToken);
if (firstClass != null)
return firstClass;
}
else if (syntaxFacts.IsClassDeclaration(member))
{
return member;
}
}
return null;
}
private static string? GetArgumentString(TypedConstant argument)
{
if (argument.Type == null ||
argument.Type.SpecialType != SpecialType.System_String ||
argument.IsNull ||
!(argument.Value is string stringValue))
{
return null;
}
return stringValue.Trim();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.DesignerAttribute
{
internal static class DesignerAttributeHelpers
{
public static async Task<string?> ComputeDesignerAttributeCategoryAsync(
INamedTypeSymbol? designerCategoryType,
Document document,
CancellationToken cancellationToken)
{
// simple case. If there's no DesignerCategory type in this compilation, then there's
// definitely no designable types. Just immediately bail out.
if (designerCategoryType == null)
return null;
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
// Legacy behavior. We only register the designer info for the first non-nested class
// in the file.
var firstClass = FindFirstNonNestedClass(
syntaxFacts, syntaxFacts.GetMembersOfCompilationUnit(root), cancellationToken);
if (firstClass == null)
return null;
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var firstClassType = (INamedTypeSymbol)semanticModel.GetRequiredDeclaredSymbol(firstClass, cancellationToken);
return TryGetDesignerCategory(firstClassType, designerCategoryType, cancellationToken);
}
private static string? TryGetDesignerCategory(
INamedTypeSymbol classType,
INamedTypeSymbol designerCategoryType,
CancellationToken cancellationToken)
{
foreach (var type in classType.GetBaseTypesAndThis())
{
cancellationToken.ThrowIfCancellationRequested();
// if it has designer attribute, set it
var attribute = type.GetAttributes().FirstOrDefault(d => designerCategoryType.Equals(d.AttributeClass));
if (attribute?.ConstructorArguments.Length == 1)
return GetArgumentString(attribute.ConstructorArguments[0]);
}
return null;
}
private static SyntaxNode? FindFirstNonNestedClass(
ISyntaxFactsService syntaxFacts, SyntaxList<SyntaxNode> members, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
if (syntaxFacts.IsNamespaceDeclaration(member))
{
var firstClass = FindFirstNonNestedClass(
syntaxFacts, syntaxFacts.GetMembersOfNamespaceDeclaration(member), cancellationToken);
if (firstClass != null)
return firstClass;
}
else if (syntaxFacts.IsClassDeclaration(member))
{
return member;
}
}
return null;
}
private static string? GetArgumentString(TypedConstant argument)
{
if (argument.Type == null ||
argument.Type.SpecialType != SpecialType.System_String ||
argument.IsNull ||
!(argument.Value is string stringValue))
{
return null;
}
return stringValue.Trim();
}
}
}
| -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/Workspace/CSharp/Extensions/NameSyntaxExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class NameSyntaxExtensions
{
public static IList<NameSyntax> GetNameParts(this NameSyntax nameSyntax)
=> new NameSyntaxIterator(nameSyntax).ToList();
public static NameSyntax GetLastDottedName(this NameSyntax nameSyntax)
{
var parts = nameSyntax.GetNameParts();
return parts[parts.Count - 1];
}
public static SyntaxToken GetNameToken(this NameSyntax nameSyntax)
{
while (true)
{
if (nameSyntax.Kind() == SyntaxKind.IdentifierName)
{
return ((IdentifierNameSyntax)nameSyntax).Identifier;
}
else if (nameSyntax.Kind() == SyntaxKind.QualifiedName)
{
nameSyntax = ((QualifiedNameSyntax)nameSyntax).Right;
}
else if (nameSyntax.Kind() == SyntaxKind.GenericName)
{
return ((GenericNameSyntax)nameSyntax).Identifier;
}
else if (nameSyntax.Kind() == SyntaxKind.AliasQualifiedName)
{
nameSyntax = ((AliasQualifiedNameSyntax)nameSyntax).Name;
}
else
{
throw new NotSupportedException();
}
}
}
public static bool CanBeReplacedWithAnyName(this NameSyntax nameSyntax)
{
if (nameSyntax.IsParentKind(SyntaxKind.AliasQualifiedName) ||
nameSyntax.IsParentKind(SyntaxKind.NameColon) ||
nameSyntax.IsParentKind(SyntaxKind.NameEquals) ||
nameSyntax.IsParentKind(SyntaxKind.TypeParameterConstraintClause))
{
return false;
}
if (nameSyntax.CheckParent<QualifiedNameSyntax>(q => q.Right == nameSyntax) ||
nameSyntax.CheckParent<MemberAccessExpressionSyntax>(m => m.Name == nameSyntax))
{
return false;
}
// TODO(cyrusn): Add more cases as the language changes.
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.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class NameSyntaxExtensions
{
public static IList<NameSyntax> GetNameParts(this NameSyntax nameSyntax)
=> new NameSyntaxIterator(nameSyntax).ToList();
public static NameSyntax GetLastDottedName(this NameSyntax nameSyntax)
{
var parts = nameSyntax.GetNameParts();
return parts[parts.Count - 1];
}
public static SyntaxToken GetNameToken(this NameSyntax nameSyntax)
{
while (true)
{
if (nameSyntax.Kind() == SyntaxKind.IdentifierName)
{
return ((IdentifierNameSyntax)nameSyntax).Identifier;
}
else if (nameSyntax.Kind() == SyntaxKind.QualifiedName)
{
nameSyntax = ((QualifiedNameSyntax)nameSyntax).Right;
}
else if (nameSyntax.Kind() == SyntaxKind.GenericName)
{
return ((GenericNameSyntax)nameSyntax).Identifier;
}
else if (nameSyntax.Kind() == SyntaxKind.AliasQualifiedName)
{
nameSyntax = ((AliasQualifiedNameSyntax)nameSyntax).Name;
}
else
{
throw new NotSupportedException();
}
}
}
public static bool CanBeReplacedWithAnyName(this NameSyntax nameSyntax)
{
if (nameSyntax.IsParentKind(SyntaxKind.AliasQualifiedName) ||
nameSyntax.IsParentKind(SyntaxKind.NameColon) ||
nameSyntax.IsParentKind(SyntaxKind.NameEquals) ||
nameSyntax.IsParentKind(SyntaxKind.TypeParameterConstraintClause))
{
return false;
}
if (nameSyntax.CheckParent<QualifiedNameSyntax>(q => q.Right == nameSyntax) ||
nameSyntax.CheckParent<MemberAccessExpressionSyntax>(m => m.Name == nameSyntax))
{
return false;
}
// TODO(cyrusn): Add more cases as the language changes.
return 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/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,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/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
public class UseExpressionBodyForIndexersRefactoringTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new UseExpressionBodyCodeRefactoringProvider();
private OptionsCollection UseExpressionBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement);
private OptionsCollection UseExpressionBodyDisabledDiagnostic =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None));
private OptionsCollection UseBlockBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement);
private OptionsCollection UseBlockBodyDisabledDiagnostic =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()
{
await TestMissingAsync(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}", parameters: new TestParameters(options: UseExpressionBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}",
@"class C
{
int this[int i] => Bar();
}", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}",
@"class C
{
int this[int i] => Bar();
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedInLambda()
{
await TestMissingAsync(
@"class C
{
Action Goo[int i]
{
get
{
return () => { [||] };
}
}
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
{
await TestMissingAsync(
@"class C
{
int this[int i] => [||]Bar();
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i] => [||]Bar();
}",
@"class C
{
int this[int i]
{
get
{
return Bar();
}
}
}", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic));
}
[WorkItem(20363, "https://github.com/dotnet/roslyn/issues/20363")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i] => [||]Bar();
}",
@"class C
{
int this[int i]
{
get
{
return Bar();
}
}
}", parameters: new TestParameters(options: UseExpressionBody));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
public class UseExpressionBodyForIndexersRefactoringTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new UseExpressionBodyCodeRefactoringProvider();
private OptionsCollection UseExpressionBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement);
private OptionsCollection UseExpressionBodyDisabledDiagnostic =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None));
private OptionsCollection UseBlockBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement);
private OptionsCollection UseBlockBodyDisabledDiagnostic =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()
{
await TestMissingAsync(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}", parameters: new TestParameters(options: UseExpressionBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}",
@"class C
{
int this[int i] => Bar();
}", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}",
@"class C
{
int this[int i] => Bar();
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedInLambda()
{
await TestMissingAsync(
@"class C
{
Action Goo[int i]
{
get
{
return () => { [||] };
}
}
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
{
await TestMissingAsync(
@"class C
{
int this[int i] => [||]Bar();
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i] => [||]Bar();
}",
@"class C
{
int this[int i]
{
get
{
return Bar();
}
}
}", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic));
}
[WorkItem(20363, "https://github.com/dotnet/roslyn/issues/20363")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i] => [||]Bar();
}",
@"class C
{
int this[int i]
{
get
{
return Bar();
}
}
}", parameters: new TestParameters(options: UseExpressionBody));
}
}
}
| -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/Core/Portable/Experiments/IExperimentationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
void EnableExperiment(string experimentName, bool value);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => false;
public void EnableExperiment(string experimentName, bool value) { }
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string OOPServerGC = "Roslyn.OOPServerGC";
public const string ImportsOnPasteDefaultEnabled = "Roslyn.ImportsOnPasteDefaultEnabled";
public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled";
public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace";
public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences";
public const string LSPCompletion = "Roslyn.LSP.Completion";
public const string CloudCache = "Roslyn.CloudCache";
public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled";
public const string InheritanceMargin = "Roslyn.InheritanceMargin";
public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor";
public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics";
public const string OOPCoreClr = "Roslyn.OOPCoreClr";
public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch";
public const string AsynchronousQuickActions = "Roslyn.AsynchronousQuickActions";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
void EnableExperiment(string experimentName, bool value);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => false;
public void EnableExperiment(string experimentName, bool value) { }
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string OOPServerGC = "Roslyn.OOPServerGC";
public const string ImportsOnPasteDefaultEnabled = "Roslyn.ImportsOnPasteDefaultEnabled";
public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled";
public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace";
public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences";
public const string LSPCompletion = "Roslyn.LSP.Completion";
public const string CloudCache = "Roslyn.CloudCache";
public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled";
public const string InheritanceMargin = "Roslyn.InheritanceMargin";
public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor";
public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics";
public const string OOPCoreClr = "Roslyn.OOPCoreClr";
public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch";
public const string AsynchronousQuickActions = "Roslyn.AsynchronousQuickActions";
}
}
| -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/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/Symbols/ObjectAddressLocalSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class ObjectAddressLocalSymbol : PlaceholderLocalSymbol
{
private readonly ulong _address;
internal ObjectAddressLocalSymbol(MethodSymbol method, string name, TypeSymbol type, ulong address) :
base(method, name, name, type)
{
Debug.Assert(type.SpecialType == SpecialType.System_Object);
_address = address;
}
internal override bool IsWritableVariable
{
// Return true?
get { return false; }
}
internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, DiagnosticBag diagnostics)
{
var method = GetIntrinsicMethod(compilation, ExpressionCompilerConstants.GetObjectAtAddressMethodName);
var argument = new BoundLiteral(
syntax,
Microsoft.CodeAnalysis.ConstantValue.Create(_address),
method.Parameters[0].Type);
var call = BoundCall.Synthesized(
syntax,
receiverOpt: null,
method: method,
arguments: ImmutableArray.Create<BoundExpression>(argument));
Debug.Assert(TypeSymbol.Equals(call.Type, this.Type, TypeCompareKind.ConsiderEverything2));
return call;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class ObjectAddressLocalSymbol : PlaceholderLocalSymbol
{
private readonly ulong _address;
internal ObjectAddressLocalSymbol(MethodSymbol method, string name, TypeSymbol type, ulong address) :
base(method, name, name, type)
{
Debug.Assert(type.SpecialType == SpecialType.System_Object);
_address = address;
}
internal override bool IsWritableVariable
{
// Return true?
get { return false; }
}
internal override BoundExpression RewriteLocal(CSharpCompilation compilation, EENamedTypeSymbol container, SyntaxNode syntax, DiagnosticBag diagnostics)
{
var method = GetIntrinsicMethod(compilation, ExpressionCompilerConstants.GetObjectAtAddressMethodName);
var argument = new BoundLiteral(
syntax,
Microsoft.CodeAnalysis.ConstantValue.Create(_address),
method.Parameters[0].Type);
var call = BoundCall.Synthesized(
syntax,
receiverOpt: null,
method: method,
arguments: ImmutableArray.Create<BoundExpression>(argument));
Debug.Assert(TypeSymbol.Equals(call.Type, this.Type, TypeCompareKind.ConsiderEverything2));
return call;
}
}
}
| -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/CSharp/Test/PersistentStorage/Mocks/MockCloudCachePersistentStorageService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.ServiceHub.Framework;
using Microsoft.ServiceHub.Framework.Services;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Cache;
using Microsoft.VisualStudio.Cache.SQLite;
using Microsoft.VisualStudio.LanguageServices.Storage;
using Microsoft.VisualStudio.RpcContracts.Caching;
namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks
{
internal class MockCloudCachePersistentStorageService : AbstractCloudCachePersistentStorageService
{
private readonly string _relativePathBase;
private readonly Action<ICacheService> _disposeCacheService;
public MockCloudCachePersistentStorageService(
IPersistentStorageLocationService locationService,
string relativePathBase,
Action<ICacheService> disposeCacheService)
: base(locationService)
{
_relativePathBase = relativePathBase;
_disposeCacheService = disposeCacheService;
}
protected override void DisposeCacheService(ICacheService cacheService)
=> _disposeCacheService(cacheService);
protected override async ValueTask<ICacheService> CreateCacheServiceAsync(CancellationToken cancellationToken)
{
// Directly access VS' CacheService through their library and not as a brokered service. Then create our
// wrapper CloudCacheService directly on that instance.
var authorizationServiceClient = new AuthorizationServiceClient(new AuthorizationServiceMock());
var solutionService = new SolutionServiceMock();
var fileSystem = new FileSystemServiceMock();
var serviceBroker = new ServiceBrokerMock()
{
BrokeredServices =
{
{ VisualStudioServices.VS2019_10.SolutionService.Moniker, solutionService },
{ VisualStudioServices.VS2019_10.FileSystem.Moniker, fileSystem },
{ FrameworkServices.Authorization.Moniker, new AuthorizationServiceMock() },
},
};
var someContext = new CacheContext { RelativePathBase = _relativePathBase };
var pool = new SqliteConnectionPool();
var activeContext = await pool.ActivateContextAsync(someContext, default);
var cacheService = new CacheService(activeContext, serviceBroker, authorizationServiceClient, pool);
return cacheService;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.ServiceHub.Framework;
using Microsoft.ServiceHub.Framework.Services;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Cache;
using Microsoft.VisualStudio.Cache.SQLite;
using Microsoft.VisualStudio.LanguageServices.Storage;
using Microsoft.VisualStudio.RpcContracts.Caching;
namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks
{
internal class MockCloudCachePersistentStorageService : AbstractCloudCachePersistentStorageService
{
private readonly string _relativePathBase;
private readonly Action<ICacheService> _disposeCacheService;
public MockCloudCachePersistentStorageService(
IPersistentStorageLocationService locationService,
string relativePathBase,
Action<ICacheService> disposeCacheService)
: base(locationService)
{
_relativePathBase = relativePathBase;
_disposeCacheService = disposeCacheService;
}
protected override void DisposeCacheService(ICacheService cacheService)
=> _disposeCacheService(cacheService);
protected override async ValueTask<ICacheService> CreateCacheServiceAsync(CancellationToken cancellationToken)
{
// Directly access VS' CacheService through their library and not as a brokered service. Then create our
// wrapper CloudCacheService directly on that instance.
var authorizationServiceClient = new AuthorizationServiceClient(new AuthorizationServiceMock());
var solutionService = new SolutionServiceMock();
var fileSystem = new FileSystemServiceMock();
var serviceBroker = new ServiceBrokerMock()
{
BrokeredServices =
{
{ VisualStudioServices.VS2019_10.SolutionService.Moniker, solutionService },
{ VisualStudioServices.VS2019_10.FileSystem.Moniker, fileSystem },
{ FrameworkServices.Authorization.Moniker, new AuthorizationServiceMock() },
},
};
var someContext = new CacheContext { RelativePathBase = _relativePathBase };
var pool = new SqliteConnectionPool();
var activeContext = await pool.ActivateContextAsync(someContext, default);
var cacheService = new CacheService(activeContext, serviceBroker, authorizationServiceClient, pool);
return cacheService;
}
}
}
| -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/AddDebuggerDisplay/CSharpAddDebuggerDisplayCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.AddDebuggerDisplay;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.AddDebuggerDisplay
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.AddDebuggerDisplay), Shared]
internal sealed class CSharpAddDebuggerDisplayCodeRefactoringProvider
: AbstractAddDebuggerDisplayCodeRefactoringProvider<
TypeDeclarationSyntax,
MethodDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpAddDebuggerDisplayCodeRefactoringProvider()
{
}
protected override bool CanNameofAccessNonPublicMembersFromAttributeArgument => true;
protected override bool SupportsConstantInterpolatedStrings(Document document)
=> ((CSharpParseOptions)document.Project.ParseOptions!).LanguageVersion.HasConstantInterpolatedStrings();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.AddDebuggerDisplay;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Shared.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.AddDebuggerDisplay
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.AddDebuggerDisplay), Shared]
internal sealed class CSharpAddDebuggerDisplayCodeRefactoringProvider
: AbstractAddDebuggerDisplayCodeRefactoringProvider<
TypeDeclarationSyntax,
MethodDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpAddDebuggerDisplayCodeRefactoringProvider()
{
}
protected override bool CanNameofAccessNonPublicMembersFromAttributeArgument => true;
protected override bool SupportsConstantInterpolatedStrings(Document document)
=> ((CSharpParseOptions)document.Project.ParseOptions!).LanguageVersion.HasConstantInterpolatedStrings();
}
}
| -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/SolutionCrawler/IWorkCoordinatorPriorityService.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal interface IWorkCoordinatorPriorityService : ILanguageService
{
/// <summary>
/// True if this document is less important than other documents in the project it is
/// contained in, and should have work scheduled for it happen after all other documents
/// in the project.
/// </summary>
Task<bool> IsLowPriorityAsync(Document document, 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.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal interface IWorkCoordinatorPriorityService : ILanguageService
{
/// <summary>
/// True if this document is less important than other documents in the project it is
/// contained in, and should have work scheduled for it happen after all other documents
/// in the project.
/// </summary>
Task<bool> IsLowPriorityAsync(Document document, 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/Features/LanguageServer/ProtocolUnitTests/References/FindAllReferencesHandlerTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.References
{
public class FindAllReferencesHandlerTests : AbstractLanguageServerProtocolTests
{
[WpfFact]
public async Task TestFindAllReferencesAsync()
{
var markup =
@"class A
{
public int {|reference:someInt|} = 1;
void M()
{
var i = {|reference:someInt|} + 1;
}
}
class B
{
int someInt = A.{|reference:someInt|} + 1;
void M2()
{
var j = someInt + A.{|caret:|}{|reference:someInt|};
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));
// Results are returned in a non-deterministic order, so we order them by location
var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray();
Assert.Equal("A", orderedResults[0].ContainingType);
Assert.Equal("B", orderedResults[2].ContainingType);
Assert.Equal("M", orderedResults[1].ContainingMember);
Assert.Equal("M2", orderedResults[3].ContainingMember);
AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic);
AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 3);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_Streaming()
{
var markup =
@"class A
{
public static int {|reference:someInt|} = 1;
void M()
{
var i = {|reference:someInt|} + 1;
}
}
class B
{
int someInt = A.{|reference:someInt|} + 1;
void M2()
{
var j = someInt + A.{|caret:|}{|reference:someInt|};
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
using var progress = BufferedProgress.Create<object>(null);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First(), progress);
Assert.Null(results);
// BufferedProgress wraps individual elements in an array, so when they are nested them like this,
// with the test creating one, and the handler another, we have to unwrap.
results = progress.GetValues().Cast<LSP.VSInternalReferenceItem>().ToArray();
Assert.NotNull(results);
Assert.NotEmpty(results);
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));
// Results are returned in a non-deterministic order, so we order them by location
var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray();
Assert.Equal("A", orderedResults[0].ContainingType);
Assert.Equal("B", orderedResults[2].ContainingType);
Assert.Equal("M", orderedResults[1].ContainingMember);
Assert.Equal("M2", orderedResults[3].ContainingMember);
AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic);
AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 3);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_Class()
{
var markup =
@"class {|reference:A|}
{
public static int someInt = 1;
void M()
{
var i = someInt + 1;
}
}
class B
{
int someInt = {|reference:A|}.someInt + 1;
void M2()
{
var j = someInt + {|caret:|}{|reference:A|}.someInt;
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));
var textElement = results[0].Text as ClassifiedTextElement;
Assert.NotNull(textElement);
var actualText = string.Concat(textElement.Runs.Select(r => r.Text));
Assert.Equal("class A", actualText);
// Results are returned in a non-deterministic order, so we order them by location
var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray();
Assert.Equal("B", orderedResults[1].ContainingType);
Assert.Equal("B", orderedResults[2].ContainingType);
Assert.Equal("M2", orderedResults[2].ContainingMember);
AssertValidDefinitionProperties(results, 0, Glyph.ClassInternal);
AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 2);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_MultipleDocuments()
{
var markups = new string[] {
@"class A
{
public static int {|reference:someInt|} = 1;
void M()
{
var i = {|reference:someInt|} + 1;
}
}",
@"class B
{
int someInt = A.{|reference:someInt|} + 1;
void M2()
{
var j = someInt + A.{|caret:|}{|reference:someInt|};
}
}"
};
using var testLspServer = CreateTestLspServer(markups, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));
// Results are returned in a non-deterministic order, so we order them by location
var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray();
Assert.Equal("A", orderedResults[0].ContainingType);
Assert.Equal("B", orderedResults[2].ContainingType);
Assert.Equal("M", orderedResults[1].ContainingMember);
Assert.Equal("M2", orderedResults[3].ContainingMember);
AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic);
AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 3);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_InvalidLocation()
{
var markup =
@"class A
{
{|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
Assert.Empty(results);
}
[WpfFact]
public async Task TestFindAllReferencesMetadataDefinitionAsync()
{
var markup =
@"using System;
class A
{
void M()
{
Console.{|caret:|}{|reference:WriteLine|}(""text"");
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
Assert.NotNull(results[0].Location.Uri);
AssertHighlightCount(results, expectedDefinitionCount: 0, expectedWrittenReferenceCount: 0, expectedReferenceCount: 1);
}
[WpfFact, WorkItem(1240061, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1240061/")]
public async Task TestFindAllReferencesAsync_Namespace()
{
var markup =
@"namespace {|caret:|}{|reference:N|}
{
class C
{
void M()
{
var x = new {|reference:N|}.C();
}
}
}
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
// Namespace definitions should not have a location
Assert.True(results.Any(r => r.DefinitionText != null && r.Location == null));
// Namespace references should have a location
Assert.True(results.Any(r => r.DefinitionText == null && r.Location != null));
AssertValidDefinitionProperties(results, 0, Glyph.Namespace);
AssertHighlightCount(results, expectedDefinitionCount: 0, expectedWrittenReferenceCount: 0, expectedReferenceCount: 2);
}
[WpfFact, WorkItem(1245616, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1245616/")]
public async Task TestFindAllReferencesAsync_Highlights()
{
var markup =
@"using System;
class C
{
void M()
{
var {|caret:|}{|reference:x|} = 1;
Console.WriteLine({|reference:x|});
{|reference:x|} = 2;
}
}
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 1, expectedReferenceCount: 1);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_StaticClassification()
{
var markup =
@"static class {|caret:|}{|reference:C|} { }
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
// Ensure static definitions and references are only classified once
var textRuns = ((ClassifiedTextElement)results.First().Text).Runs;
Assert.Equal(9, textRuns.Count());
}
private static LSP.ReferenceParams CreateReferenceParams(LSP.Location caret, IProgress<object> progress) =>
new LSP.ReferenceParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri),
Position = caret.Range.Start,
Context = new LSP.ReferenceContext(),
PartialResultToken = progress
};
internal static async Task<LSP.VSInternalReferenceItem[]> RunFindAllReferencesAsync(TestLspServer testLspServer, LSP.Location caret, IProgress<object> progress = null)
{
var vsClientCapabilities = new LSP.VSInternalClientCapabilities
{
SupportsVisualStudioExtensions = true
};
var results = await testLspServer.ExecuteRequestAsync<LSP.ReferenceParams, LSP.VSInternalReferenceItem[]>(LSP.Methods.TextDocumentReferencesName,
CreateReferenceParams(caret, progress), vsClientCapabilities, null, CancellationToken.None);
return results?.Cast<LSP.VSInternalReferenceItem>()?.ToArray();
}
private static void AssertValidDefinitionProperties(LSP.VSInternalReferenceItem[] referenceItems, int definitionIndex, Glyph definitionGlyph)
{
var definition = referenceItems[definitionIndex];
var definitionId = definition.DefinitionId;
Assert.NotNull(definition.DefinitionText);
Assert.Equal(definitionGlyph.GetImageId(), definition.DefinitionIcon.ImageId);
for (var i = 0; i < referenceItems.Length; i++)
{
if (i == definitionIndex)
{
continue;
}
Assert.Null(referenceItems[i].DefinitionText);
Assert.Equal(0, referenceItems[i].DefinitionIcon.ImageId.Id);
Assert.Equal(definitionId, referenceItems[i].DefinitionId);
Assert.NotEqual(definitionId, referenceItems[i].Id);
}
}
private static void AssertHighlightCount(
LSP.VSInternalReferenceItem[] referenceItems,
int expectedDefinitionCount,
int expectedWrittenReferenceCount,
int expectedReferenceCount)
{
var actualDefinitionCount = referenceItems.Select(
item => ((ClassifiedTextElement)item.Text).Runs.Where(run => run.MarkerTagType == DefinitionHighlightTag.TagId)).Where(i => i.Any()).Count();
var actualWrittenReferenceCount = referenceItems.Select(
item => ((ClassifiedTextElement)item.Text).Runs.Where(run => run.MarkerTagType == WrittenReferenceHighlightTag.TagId)).Where(i => i.Any()).Count();
var actualReferenceCount = referenceItems.Select(
item => ((ClassifiedTextElement)item.Text).Runs.Where(run => run.MarkerTagType == ReferenceHighlightTag.TagId)).Where(i => i.Any()).Count();
Assert.Equal(expectedDefinitionCount, actualDefinitionCount);
Assert.Equal(expectedWrittenReferenceCount, actualWrittenReferenceCount);
Assert.Equal(expectedReferenceCount, actualReferenceCount);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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 System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.References
{
public class FindAllReferencesHandlerTests : AbstractLanguageServerProtocolTests
{
[WpfFact]
public async Task TestFindAllReferencesAsync()
{
var markup =
@"class A
{
public int {|reference:someInt|} = 1;
void M()
{
var i = {|reference:someInt|} + 1;
}
}
class B
{
int someInt = A.{|reference:someInt|} + 1;
void M2()
{
var j = someInt + A.{|caret:|}{|reference:someInt|};
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));
// Results are returned in a non-deterministic order, so we order them by location
var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray();
Assert.Equal("A", orderedResults[0].ContainingType);
Assert.Equal("B", orderedResults[2].ContainingType);
Assert.Equal("M", orderedResults[1].ContainingMember);
Assert.Equal("M2", orderedResults[3].ContainingMember);
AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic);
AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 3);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_Streaming()
{
var markup =
@"class A
{
public static int {|reference:someInt|} = 1;
void M()
{
var i = {|reference:someInt|} + 1;
}
}
class B
{
int someInt = A.{|reference:someInt|} + 1;
void M2()
{
var j = someInt + A.{|caret:|}{|reference:someInt|};
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
using var progress = BufferedProgress.Create<object>(null);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First(), progress);
Assert.Null(results);
// BufferedProgress wraps individual elements in an array, so when they are nested them like this,
// with the test creating one, and the handler another, we have to unwrap.
results = progress.GetValues().Cast<LSP.VSInternalReferenceItem>().ToArray();
Assert.NotNull(results);
Assert.NotEmpty(results);
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));
// Results are returned in a non-deterministic order, so we order them by location
var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray();
Assert.Equal("A", orderedResults[0].ContainingType);
Assert.Equal("B", orderedResults[2].ContainingType);
Assert.Equal("M", orderedResults[1].ContainingMember);
Assert.Equal("M2", orderedResults[3].ContainingMember);
AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic);
AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 3);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_Class()
{
var markup =
@"class {|reference:A|}
{
public static int someInt = 1;
void M()
{
var i = someInt + 1;
}
}
class B
{
int someInt = {|reference:A|}.someInt + 1;
void M2()
{
var j = someInt + {|caret:|}{|reference:A|}.someInt;
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));
var textElement = results[0].Text as ClassifiedTextElement;
Assert.NotNull(textElement);
var actualText = string.Concat(textElement.Runs.Select(r => r.Text));
Assert.Equal("class A", actualText);
// Results are returned in a non-deterministic order, so we order them by location
var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray();
Assert.Equal("B", orderedResults[1].ContainingType);
Assert.Equal("B", orderedResults[2].ContainingType);
Assert.Equal("M2", orderedResults[2].ContainingMember);
AssertValidDefinitionProperties(results, 0, Glyph.ClassInternal);
AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 2);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_MultipleDocuments()
{
var markups = new string[] {
@"class A
{
public static int {|reference:someInt|} = 1;
void M()
{
var i = {|reference:someInt|} + 1;
}
}",
@"class B
{
int someInt = A.{|reference:someInt|} + 1;
void M2()
{
var j = someInt + A.{|caret:|}{|reference:someInt|};
}
}"
};
using var testLspServer = CreateTestLspServer(markups, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
AssertLocationsEqual(locations["reference"], results.Select(result => result.Location));
// Results are returned in a non-deterministic order, so we order them by location
var orderedResults = results.OrderBy(r => r.Location, new OrderLocations()).ToArray();
Assert.Equal("A", orderedResults[0].ContainingType);
Assert.Equal("B", orderedResults[2].ContainingType);
Assert.Equal("M", orderedResults[1].ContainingMember);
Assert.Equal("M2", orderedResults[3].ContainingMember);
AssertValidDefinitionProperties(results, 0, Glyph.FieldPublic);
AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 0, expectedReferenceCount: 3);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_InvalidLocation()
{
var markup =
@"class A
{
{|caret:|}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
Assert.Empty(results);
}
[WpfFact]
public async Task TestFindAllReferencesMetadataDefinitionAsync()
{
var markup =
@"using System;
class A
{
void M()
{
Console.{|caret:|}{|reference:WriteLine|}(""text"");
}
}";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
Assert.NotNull(results[0].Location.Uri);
AssertHighlightCount(results, expectedDefinitionCount: 0, expectedWrittenReferenceCount: 0, expectedReferenceCount: 1);
}
[WpfFact, WorkItem(1240061, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1240061/")]
public async Task TestFindAllReferencesAsync_Namespace()
{
var markup =
@"namespace {|caret:|}{|reference:N|}
{
class C
{
void M()
{
var x = new {|reference:N|}.C();
}
}
}
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
// Namespace definitions should not have a location
Assert.True(results.Any(r => r.DefinitionText != null && r.Location == null));
// Namespace references should have a location
Assert.True(results.Any(r => r.DefinitionText == null && r.Location != null));
AssertValidDefinitionProperties(results, 0, Glyph.Namespace);
AssertHighlightCount(results, expectedDefinitionCount: 0, expectedWrittenReferenceCount: 0, expectedReferenceCount: 2);
}
[WpfFact, WorkItem(1245616, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1245616/")]
public async Task TestFindAllReferencesAsync_Highlights()
{
var markup =
@"using System;
class C
{
void M()
{
var {|caret:|}{|reference:x|} = 1;
Console.WriteLine({|reference:x|});
{|reference:x|} = 2;
}
}
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
AssertHighlightCount(results, expectedDefinitionCount: 1, expectedWrittenReferenceCount: 1, expectedReferenceCount: 1);
}
[WpfFact]
public async Task TestFindAllReferencesAsync_StaticClassification()
{
var markup =
@"static class {|caret:|}{|reference:C|} { }
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunFindAllReferencesAsync(testLspServer, locations["caret"].First());
// Ensure static definitions and references are only classified once
var textRuns = ((ClassifiedTextElement)results.First().Text).Runs;
Assert.Equal(9, textRuns.Count());
}
private static LSP.ReferenceParams CreateReferenceParams(LSP.Location caret, IProgress<object> progress) =>
new LSP.ReferenceParams()
{
TextDocument = CreateTextDocumentIdentifier(caret.Uri),
Position = caret.Range.Start,
Context = new LSP.ReferenceContext(),
PartialResultToken = progress
};
internal static async Task<LSP.VSInternalReferenceItem[]> RunFindAllReferencesAsync(TestLspServer testLspServer, LSP.Location caret, IProgress<object> progress = null)
{
var vsClientCapabilities = new LSP.VSInternalClientCapabilities
{
SupportsVisualStudioExtensions = true
};
var results = await testLspServer.ExecuteRequestAsync<LSP.ReferenceParams, LSP.VSInternalReferenceItem[]>(LSP.Methods.TextDocumentReferencesName,
CreateReferenceParams(caret, progress), vsClientCapabilities, null, CancellationToken.None);
return results?.Cast<LSP.VSInternalReferenceItem>()?.ToArray();
}
private static void AssertValidDefinitionProperties(LSP.VSInternalReferenceItem[] referenceItems, int definitionIndex, Glyph definitionGlyph)
{
var definition = referenceItems[definitionIndex];
var definitionId = definition.DefinitionId;
Assert.NotNull(definition.DefinitionText);
Assert.Equal(definitionGlyph.GetImageId(), definition.DefinitionIcon.ImageId);
for (var i = 0; i < referenceItems.Length; i++)
{
if (i == definitionIndex)
{
continue;
}
Assert.Null(referenceItems[i].DefinitionText);
Assert.Equal(0, referenceItems[i].DefinitionIcon.ImageId.Id);
Assert.Equal(definitionId, referenceItems[i].DefinitionId);
Assert.NotEqual(definitionId, referenceItems[i].Id);
}
}
private static void AssertHighlightCount(
LSP.VSInternalReferenceItem[] referenceItems,
int expectedDefinitionCount,
int expectedWrittenReferenceCount,
int expectedReferenceCount)
{
var actualDefinitionCount = referenceItems.Select(
item => ((ClassifiedTextElement)item.Text).Runs.Where(run => run.MarkerTagType == DefinitionHighlightTag.TagId)).Where(i => i.Any()).Count();
var actualWrittenReferenceCount = referenceItems.Select(
item => ((ClassifiedTextElement)item.Text).Runs.Where(run => run.MarkerTagType == WrittenReferenceHighlightTag.TagId)).Where(i => i.Any()).Count();
var actualReferenceCount = referenceItems.Select(
item => ((ClassifiedTextElement)item.Text).Runs.Where(run => run.MarkerTagType == ReferenceHighlightTag.TagId)).Where(i => i.Any()).Count();
Assert.Equal(expectedDefinitionCount, actualDefinitionCount);
Assert.Equal(expectedWrittenReferenceCount, actualWrittenReferenceCount);
Assert.Equal(expectedReferenceCount, actualReferenceCount);
}
}
}
| -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/CSharpTest/CodeActions/SyncNamespace/SyncNamespaceTests_NoAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace
{
public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnNamespaceDeclaration()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace NS
{{
class [||]Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnNamespaceDeclaration_FileScopedNamespace()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace NS;
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnFirstMemberInGlobal()
{
var folders = new[] { "A" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class Class1
{{
}}
class [||]Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MultipleNamespaceDeclarations()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
class Class1
{{
}}
}}
namespace NS2
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MembersInBothGlobalAndNamespaceDeclaration_CursorOnNamespace()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
class Class1
{{
}}
}}
class Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MembersInBothGlobalAndNamespaceDeclaration_CursorOnFirstGlobalMember()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
namespace NS1
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NestedNamespaceDeclarations()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
namespace NS2
{{
class Class1
{{
}}
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_InvalidNamespaceIdentifier()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_InGlobalNamespace()
{
var folders = Array.Empty<string>();
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_DefaultGlobalNamespace()
{
var folders = new[] { "A", "B", "C" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A.B.C
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_InNamespaceDeclaration()
{
var folders = new[] { "B", "C" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""A"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A.B.C
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_FileNotRooted()
{
var filePath = PathUtilities.CombineAbsoluteAndRelativePaths(PathUtilities.GetPathRoot(ProjectFilePath), "Foo.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document FilePath=""{filePath}"">
namespace [||]NS
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NoDeclaration()
{
var folders = new[] { "A" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
[||]
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.SyncNamespace
{
public partial class SyncNamespaceTests : CSharpSyncNamespaceTestsBase
{
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnNamespaceDeclaration()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace NS
{{
class [||]Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnNamespaceDeclaration_FileScopedNamespace()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace NS;
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NotOnFirstMemberInGlobal()
{
var folders = new[] { "A" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class Class1
{{
}}
class [||]Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MultipleNamespaceDeclarations()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
class Class1
{{
}}
}}
namespace NS2
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MembersInBothGlobalAndNamespaceDeclaration_CursorOnNamespace()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
class Class1
{{
}}
}}
class Class2
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MembersInBothGlobalAndNamespaceDeclaration_CursorOnFirstGlobalMember()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
namespace NS1
{{
class Class2
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NestedNamespaceDeclarations()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]NS1
{{
namespace NS2
{{
class Class1
{{
}}
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_InvalidNamespaceIdentifier()
{
var folders = new[] { "A", "B" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_InGlobalNamespace()
{
var folders = Array.Empty<string>();
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
class [||]Class1
{{
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_DefaultGlobalNamespace()
{
var folders = new[] { "A", "B", "C" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace="""" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A.B.C
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_MatchingNamespace_InNamespaceDeclaration()
{
var folders = new[] { "B", "C" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" RootNamespace=""A"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
namespace [||]A.B.C
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_FileNotRooted()
{
var filePath = PathUtilities.CombineAbsoluteAndRelativePaths(PathUtilities.GetPathRoot(ProjectFilePath), "Foo.cs");
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document FilePath=""{filePath}"">
namespace [||]NS
{{
class Class1
{{
}}
}}
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsSyncNamespace)]
public async Task NoAction_NoDeclaration()
{
var folders = new[] { "A" };
var (folder, filePath) = CreateDocumentFilePath(folders);
var code =
$@"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" FilePath=""{ProjectFilePath}"" CommonReferences=""true"">
<Document Folders=""{folder}"" FilePath=""{filePath}"">
using System;
[||]
</Document>
</Project>
</Workspace>";
await TestMissingInRegularAndScriptAsync(code);
}
}
}
| -1 |
dotnet/roslyn | 55,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/Core/Analyzers/MatchFolderAndNamespace/MatchFolderAndNamespaceConstants.cs | // Licensed to the .NET Foundation under one or more 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.Analyzers.MatchFolderAndNamespace
{
internal static class MatchFolderAndNamespaceConstants
{
public const string RootNamespaceOption = "build_property.RootNamespace";
public const string ProjectDirOption = "build_property.ProjectDir";
public const string TargetNamespace = "TargetNamespace";
}
}
| // Licensed to the .NET Foundation under one or more 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.Analyzers.MatchFolderAndNamespace
{
internal static class MatchFolderAndNamespaceConstants
{
public const string RootNamespaceOption = "build_property.RootNamespace";
public const string ProjectDirOption = "build_property.ProjectDir";
public const string TargetNamespace = "TargetNamespace";
}
}
| -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/Core/Portable/Shared/TestHooks/IAsynchronousOperationListenerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Shared.TestHooks
{
/// <summary>
/// Return <see cref="IAsynchronousOperationListener"/> for the given featureName
///
/// We have this abstraction so that we can have isolated listener/waiter in unit tests
/// </summary>
internal interface IAsynchronousOperationListenerProvider
{
/// <summary>
/// Get <see cref="IAsynchronousOperationListener"/> for given feature.
/// same provider will return a singleton listener for same feature
/// </summary>
IAsynchronousOperationListener GetListener(string featureName);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Shared.TestHooks
{
/// <summary>
/// Return <see cref="IAsynchronousOperationListener"/> for the given featureName
///
/// We have this abstraction so that we can have isolated listener/waiter in unit tests
/// </summary>
internal interface IAsynchronousOperationListenerProvider
{
/// <summary>
/// Get <see cref="IAsynchronousOperationListener"/> for given feature.
/// same provider will return a singleton listener for same feature
/// </summary>
IAsynchronousOperationListener GetListener(string featureName);
}
}
| -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/PublicModel/NonSourceAssemblySymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Symbols.PublicModel
{
internal sealed class NonSourceAssemblySymbol : AssemblySymbol
{
private readonly Symbols.AssemblySymbol _underlying;
public NonSourceAssemblySymbol(Symbols.AssemblySymbol underlying)
{
Debug.Assert(underlying is object);
Debug.Assert(!(underlying is Symbols.SourceAssemblySymbol));
_underlying = underlying;
}
internal override Symbols.AssemblySymbol UnderlyingAssemblySymbol => _underlying;
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Symbols.PublicModel
{
internal sealed class NonSourceAssemblySymbol : AssemblySymbol
{
private readonly Symbols.AssemblySymbol _underlying;
public NonSourceAssemblySymbol(Symbols.AssemblySymbol underlying)
{
Debug.Assert(underlying is object);
Debug.Assert(!(underlying is Symbols.SourceAssemblySymbol));
_underlying = underlying;
}
internal override Symbols.AssemblySymbol UnderlyingAssemblySymbol => _underlying;
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
}
}
| -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/SearchScopes/SourceSymbolsProjectSearchScope.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.SymbolTree;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddImport
{
internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax>
{
/// <summary>
/// SearchScope used for searching *only* the source symbols contained within a project/compilation.
/// i.e. symbols from metadata will not be searched.
/// </summary>
private class SourceSymbolsProjectSearchScope : ProjectSearchScope
{
private readonly ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> _projectToAssembly;
public SourceSymbolsProjectSearchScope(
AbstractAddImportFeatureService<TSimpleNameSyntax> provider,
ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly,
Project project, bool ignoreCase, CancellationToken cancellationToken)
: base(provider, project, ignoreCase, cancellationToken)
{
_projectToAssembly = projectToAssembly;
}
protected override async Task<ImmutableArray<ISymbol>> FindDeclarationsAsync(
SymbolFilter filter, SearchQuery searchQuery)
{
var service = _project.Solution.Workspace.Services.GetService<ISymbolTreeInfoCacheService>();
var info = await service.TryGetSourceSymbolTreeInfoAsync(_project, CancellationToken).ConfigureAwait(false);
if (info == null)
{
// Looks like there was nothing in the cache. Return no results for now.
return ImmutableArray<ISymbol>.Empty;
}
// Don't create the assembly until it is actually needed by the SymbolTreeInfo.FindAsync
// code. Creating the assembly can be costly and we want to avoid it until it is actually
// needed.
var lazyAssembly = _projectToAssembly.GetOrAdd(_project, CreateLazyAssembly);
var declarations = await info.FindAsync(
searchQuery, lazyAssembly, filter, CancellationToken).ConfigureAwait(false);
return declarations;
}
private static AsyncLazy<IAssemblySymbol> CreateLazyAssembly(Project project)
{
return new AsyncLazy<IAssemblySymbol>(
async c =>
{
var compilation = await project.GetCompilationAsync(c).ConfigureAwait(false);
return compilation.Assembly;
}, cacheResult: 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.Collections.Concurrent;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.SymbolTree;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddImport
{
internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax>
{
/// <summary>
/// SearchScope used for searching *only* the source symbols contained within a project/compilation.
/// i.e. symbols from metadata will not be searched.
/// </summary>
private class SourceSymbolsProjectSearchScope : ProjectSearchScope
{
private readonly ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> _projectToAssembly;
public SourceSymbolsProjectSearchScope(
AbstractAddImportFeatureService<TSimpleNameSyntax> provider,
ConcurrentDictionary<Project, AsyncLazy<IAssemblySymbol>> projectToAssembly,
Project project, bool ignoreCase, CancellationToken cancellationToken)
: base(provider, project, ignoreCase, cancellationToken)
{
_projectToAssembly = projectToAssembly;
}
protected override async Task<ImmutableArray<ISymbol>> FindDeclarationsAsync(
SymbolFilter filter, SearchQuery searchQuery)
{
var service = _project.Solution.Workspace.Services.GetService<ISymbolTreeInfoCacheService>();
var info = await service.TryGetSourceSymbolTreeInfoAsync(_project, CancellationToken).ConfigureAwait(false);
if (info == null)
{
// Looks like there was nothing in the cache. Return no results for now.
return ImmutableArray<ISymbol>.Empty;
}
// Don't create the assembly until it is actually needed by the SymbolTreeInfo.FindAsync
// code. Creating the assembly can be costly and we want to avoid it until it is actually
// needed.
var lazyAssembly = _projectToAssembly.GetOrAdd(_project, CreateLazyAssembly);
var declarations = await info.FindAsync(
searchQuery, lazyAssembly, filter, CancellationToken).ConfigureAwait(false);
return declarations;
}
private static AsyncLazy<IAssemblySymbol> CreateLazyAssembly(Project project)
{
return new AsyncLazy<IAssemblySymbol>(
async c =>
{
var compilation = await project.GetCompilationAsync(c).ConfigureAwait(false);
return compilation.Assembly;
}, cacheResult: 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/Compilers/CSharp/Portable/Syntax/SyntaxFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A class containing factory methods for constructing syntax nodes, tokens and trivia.
/// </summary>
public static partial class SyntaxFactory
{
/// <summary>
/// A trivia with kind EndOfLineTrivia containing both the carriage return and line feed characters.
/// </summary>
public static SyntaxTrivia CarriageReturnLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.CarriageReturnLineFeed;
/// <summary>
/// A trivia with kind EndOfLineTrivia containing a single line feed character.
/// </summary>
public static SyntaxTrivia LineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.LineFeed;
/// <summary>
/// A trivia with kind EndOfLineTrivia containing a single carriage return character.
/// </summary>
public static SyntaxTrivia CarriageReturn { get; } = Syntax.InternalSyntax.SyntaxFactory.CarriageReturn;
/// <summary>
/// A trivia with kind WhitespaceTrivia containing a single space character.
/// </summary>
public static SyntaxTrivia Space { get; } = Syntax.InternalSyntax.SyntaxFactory.Space;
/// <summary>
/// A trivia with kind WhitespaceTrivia containing a single tab character.
/// </summary>
public static SyntaxTrivia Tab { get; } = Syntax.InternalSyntax.SyntaxFactory.Tab;
/// <summary>
/// An elastic trivia with kind EndOfLineTrivia containing both the carriage return and line feed characters.
/// Elastic trivia are used to denote trivia that was not produced by parsing source text, and are usually not
/// preserved during formatting.
/// </summary>
public static SyntaxTrivia ElasticCarriageReturnLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturnLineFeed;
/// <summary>
/// An elastic trivia with kind EndOfLineTrivia containing a single line feed character. Elastic trivia are used
/// to denote trivia that was not produced by parsing source text, and are usually not preserved during
/// formatting.
/// </summary>
public static SyntaxTrivia ElasticLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticLineFeed;
/// <summary>
/// An elastic trivia with kind EndOfLineTrivia containing a single carriage return character. Elastic trivia
/// are used to denote trivia that was not produced by parsing source text, and are usually not preserved during
/// formatting.
/// </summary>
public static SyntaxTrivia ElasticCarriageReturn { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturn;
/// <summary>
/// An elastic trivia with kind WhitespaceTrivia containing a single space character. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
public static SyntaxTrivia ElasticSpace { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticSpace;
/// <summary>
/// An elastic trivia with kind WhitespaceTrivia containing a single tab character. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
public static SyntaxTrivia ElasticTab { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticTab;
/// <summary>
/// An elastic trivia with kind WhitespaceTrivia containing no characters. Elastic marker trivia are included
/// automatically by factory methods when trivia is not specified. Syntax formatting will replace elastic
/// markers with appropriate trivia.
/// </summary>
public static SyntaxTrivia ElasticMarker { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticZeroSpace;
/// <summary>
/// Creates a trivia with kind EndOfLineTrivia containing the specified text.
/// </summary>
/// <param name="text">The text of the end of line. Any text can be specified here, however only carriage return and
/// line feed characters are recognized by the parser as end of line.</param>
public static SyntaxTrivia EndOfLine(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: false);
}
/// <summary>
/// Creates a trivia with kind EndOfLineTrivia containing the specified text. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
/// <param name="text">The text of the end of line. Any text can be specified here, however only carriage return and
/// line feed characters are recognized by the parser as end of line.</param>
public static SyntaxTrivia ElasticEndOfLine(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: true);
}
[Obsolete("Use SyntaxFactory.EndOfLine or SyntaxFactory.ElasticEndOfLine")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static SyntaxTrivia EndOfLine(string text, bool elastic)
{
return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic);
}
/// <summary>
/// Creates a trivia with kind WhitespaceTrivia containing the specified text.
/// </summary>
/// <param name="text">The text of the whitespace. Any text can be specified here, however only specific
/// whitespace characters are recognized by the parser.</param>
public static SyntaxTrivia Whitespace(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic: false);
}
/// <summary>
/// Creates a trivia with kind WhitespaceTrivia containing the specified text. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
/// <param name="text">The text of the whitespace. Any text can be specified here, however only specific
/// whitespace characters are recognized by the parser.</param>
public static SyntaxTrivia ElasticWhitespace(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic: false);
}
[Obsolete("Use SyntaxFactory.Whitespace or SyntaxFactory.ElasticWhitespace")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static SyntaxTrivia Whitespace(string text, bool elastic)
{
return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic);
}
/// <summary>
/// Creates a trivia with kind either SingleLineCommentTrivia or MultiLineCommentTrivia containing the specified
/// text.
/// </summary>
/// <param name="text">The entire text of the comment including the leading '//' token for single line comments
/// or stop or start tokens for multiline comments.</param>
public static SyntaxTrivia Comment(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.Comment(text);
}
/// <summary>
/// Creates a trivia with kind DisabledTextTrivia. Disabled text corresponds to any text between directives that
/// is not considered active.
/// </summary>
public static SyntaxTrivia DisabledText(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.DisabledText(text);
}
/// <summary>
/// Creates a trivia with kind PreprocessingMessageTrivia.
/// </summary>
public static SyntaxTrivia PreprocessingMessage(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.PreprocessingMessage(text);
}
/// <summary>
/// Trivia nodes represent parts of the program text that are not parts of the
/// syntactic grammar, such as spaces, newlines, comments, preprocessor
/// directives, and disabled code.
/// </summary>
/// <param name="kind">
/// A <see cref="SyntaxKind"/> representing the specific kind of <see cref="SyntaxTrivia"/>. One of
/// <see cref="SyntaxKind.WhitespaceTrivia"/>, <see cref="SyntaxKind.EndOfLineTrivia"/>,
/// <see cref="SyntaxKind.SingleLineCommentTrivia"/>, <see cref="SyntaxKind.MultiLineCommentTrivia"/>,
/// <see cref="SyntaxKind.DocumentationCommentExteriorTrivia"/>, <see cref="SyntaxKind.DisabledTextTrivia"/>
/// </param>
/// <param name="text">
/// The actual text of this token.
/// </param>
public static SyntaxTrivia SyntaxTrivia(SyntaxKind kind, string text)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
switch (kind)
{
case SyntaxKind.DisabledTextTrivia:
case SyntaxKind.DocumentationCommentExteriorTrivia:
case SyntaxKind.EndOfLineTrivia:
case SyntaxKind.MultiLineCommentTrivia:
case SyntaxKind.SingleLineCommentTrivia:
case SyntaxKind.WhitespaceTrivia:
return new SyntaxTrivia(default(SyntaxToken), new Syntax.InternalSyntax.SyntaxTrivia(kind, text, null, null), 0, 0);
default:
throw new ArgumentException("kind");
}
}
/// <summary>
/// Creates a token corresponding to a syntax kind. This method can be used for token syntax kinds whose text
/// can be inferred by the kind alone.
/// </summary>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <returns></returns>
public static SyntaxToken Token(SyntaxKind kind)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(ElasticMarker.UnderlyingNode, kind, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token corresponding to syntax kind. This method can be used for token syntax kinds whose text can
/// be inferred by the kind alone.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(leading.Node, kind, trailing.Node));
}
/// <summary>
/// Creates a token corresponding to syntax kind. This method gives control over token Text and ValueText.
///
/// For example, consider the text '<see cref="operator &#43;"/>'. To create a token for the value of
/// the operator symbol (&#43;), one would call
/// Token(default(SyntaxTriviaList), SyntaxKind.PlusToken, "&#43;", "+", default(SyntaxTriviaList)).
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <param name="text">The text from which this token was created (e.g. lexed).</param>
/// <param name="valueText">How C# should interpret the text of this token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, string text, string valueText, SyntaxTriviaList trailing)
{
switch (kind)
{
case SyntaxKind.IdentifierToken:
// Have a different representation.
throw new ArgumentException(CSharpResources.UseVerbatimIdentifier, nameof(kind));
case SyntaxKind.CharacterLiteralToken:
// Value should not have type string.
throw new ArgumentException(CSharpResources.UseLiteralForTokens, nameof(kind));
case SyntaxKind.NumericLiteralToken:
// Value should not have type string.
throw new ArgumentException(CSharpResources.UseLiteralForNumeric, nameof(kind));
}
if (!SyntaxFacts.IsAnyToken(kind))
{
throw new ArgumentException(string.Format(CSharpResources.ThisMethodCanOnlyBeUsedToCreateTokens, kind), nameof(kind));
}
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(leading.Node, kind, text, valueText, trailing.Node));
}
/// <summary>
/// Creates a missing token corresponding to syntax kind. A missing token is produced by the parser when an
/// expected token is not found. A missing token has no text and normally has associated diagnostics.
/// </summary>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
public static SyntaxToken MissingToken(SyntaxKind kind)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.MissingToken(ElasticMarker.UnderlyingNode, kind, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a missing token corresponding to syntax kind. A missing token is produced by the parser when an
/// expected token is not found. A missing token has no text and normally has associated diagnostics.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken MissingToken(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.MissingToken(leading.Node, kind, trailing.Node));
}
/// <summary>
/// Creates a token with kind IdentifierToken containing the specified text.
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character.</param>
/// </summary>
public static SyntaxToken Identifier(string text)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(ElasticMarker.UnderlyingNode, text, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind IdentifierToken containing the specified text.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Identifier(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(leading.Node, text, trailing.Node));
}
/// <summary>
/// Creates a verbatim token with kind IdentifierToken containing the specified text.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character as it is in source.</param>
/// <param name="valueText">The canonical value of the token's text.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken VerbatimIdentifier(SyntaxTriviaList leading, string text, string valueText, SyntaxTriviaList trailing)
{
if (text.StartsWith("@", StringComparison.Ordinal))
{
throw new ArgumentException("text should not start with an @ character.");
}
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(SyntaxKind.IdentifierName, leading.Node, "@" + text, valueText, trailing.Node));
}
/// <summary>
/// Creates a token with kind IdentifierToken containing the specified text.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="contextualKind">An alternative SyntaxKind that can be inferred for this token in special
/// contexts. These are usually keywords.</param>
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character.</param>
/// <param name="valueText">The text of the identifier name without escapes or leading '@' character.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
/// <returns></returns>
public static SyntaxToken Identifier(SyntaxTriviaList leading, SyntaxKind contextualKind, string text, string valueText, SyntaxTriviaList trailing)
{
return new SyntaxToken(InternalSyntax.SyntaxFactory.Identifier(contextualKind, leading.Node, text, valueText, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a 4-byte signed integer value.
/// </summary>
/// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(int value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte signed integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, int value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte signed integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, int value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a 4-byte unsigned integer value.
/// </summary>
/// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(uint value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte unsigned integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, uint value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte unsigned integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, uint value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from an 8-byte signed integer value.
/// </summary>
/// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(long value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte signed integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, long value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte signed integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, long value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from an 8-byte unsigned integer value.
/// </summary>
/// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(ulong value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte unsigned integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, ulong value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte unsigned integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, ulong value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a 4-byte floating point value.
/// </summary>
/// <param name="value">The 4-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(float value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte floating point value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, float value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte floating point value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte floating point value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, float value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from an 8-byte floating point value.
/// </summary>
/// <param name="value">The 8-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(double value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte floating point value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, double value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte floating point value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte floating point value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, double value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a decimal value.
/// </summary>
/// <param name="value">The decimal value to be represented by the returned token.</param>
public static SyntaxToken Literal(decimal value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding decimal value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The decimal value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, decimal value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding decimal value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The decimal value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, decimal value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind StringLiteralToken from a string value.
/// </summary>
/// <param name="value">The string value to be represented by the returned token.</param>
public static SyntaxToken Literal(string value)
{
return Literal(SymbolDisplay.FormatLiteral(value, quote: true), value);
}
/// <summary>
/// Creates a token with kind StringLiteralToken from the text and corresponding string value.
/// </summary>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The string value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, string value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind StringLiteralToken from the text and corresponding string value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The string value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind CharacterLiteralToken from a character value.
/// </summary>
/// <param name="value">The character value to be represented by the returned token.</param>
public static SyntaxToken Literal(char value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters), value);
}
/// <summary>
/// Creates a token with kind CharacterLiteralToken from the text and corresponding character value.
/// </summary>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The character value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, char value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind CharacterLiteralToken from the text and corresponding character value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The character value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, char value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind BadToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the bad token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken BadToken(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.BadToken(leading.Node, text, trailing.Node));
}
/// <summary>
/// Creates a token with kind XmlTextLiteralToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The xml text value.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken XmlTextLiteral(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind XmlEntityLiteralToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The xml entity value.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken XmlEntity(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlEntity(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates an xml documentation comment that abstracts xml syntax creation.
/// </summary>
/// <param name="content">
/// A list of xml node syntax that will be the content within the xml documentation comment
/// (e.g. a summary element, a returns element, exception element and so on).
/// </param>
public static DocumentationCommentTriviaSyntax DocumentationComment(params XmlNodeSyntax[] content)
{
return DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia, List(content))
.WithLeadingTrivia(DocumentationCommentExterior("/// "))
.WithTrailingTrivia(EndOfLine(""));
}
/// <summary>
/// Creates a summary element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the summary element.</param>
public static XmlElementSyntax XmlSummaryElement(params XmlNodeSyntax[] content)
{
return XmlSummaryElement(List(content));
}
/// <summary>
/// Creates a summary element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the summary element.</param>
public static XmlElementSyntax XmlSummaryElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.SummaryElementName, content);
}
/// <summary>
/// Creates a see element within an xml documentation comment.
/// </summary>
/// <param name="cref">A cref syntax node that points to the referenced item (e.g. a class, struct).</param>
public static XmlEmptyElementSyntax XmlSeeElement(CrefSyntax cref)
{
return XmlEmptyElement(DocumentationCommentXmlNames.SeeElementName).AddAttributes(XmlCrefAttribute(cref));
}
/// <summary>
/// Creates a seealso element within an xml documentation comment.
/// </summary>
/// <param name="cref">A cref syntax node that points to the referenced item (e.g. a class, struct).</param>
public static XmlEmptyElementSyntax XmlSeeAlsoElement(CrefSyntax cref)
{
return XmlEmptyElement(DocumentationCommentXmlNames.SeeAlsoElementName).AddAttributes(XmlCrefAttribute(cref));
}
/// <summary>
/// Creates a seealso element within an xml documentation comment.
/// </summary>
/// <param name="linkAddress">The uri of the referenced item.</param>
/// <param name="linkText">A list of xml node syntax that will be used as the link text for the referenced item.</param>
public static XmlElementSyntax XmlSeeAlsoElement(Uri linkAddress, SyntaxList<XmlNodeSyntax> linkText)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.SeeAlsoElementName, linkText);
return element.WithStartTag(element.StartTag.AddAttributes(XmlTextAttribute(DocumentationCommentXmlNames.CrefAttributeName, linkAddress.ToString())));
}
/// <summary>
/// Creates a threadsafety element within an xml documentation comment.
/// </summary>
public static XmlEmptyElementSyntax XmlThreadSafetyElement()
{
return XmlThreadSafetyElement(true, false);
}
/// <summary>
/// Creates a threadsafety element within an xml documentation comment.
/// </summary>
/// <param name="isStatic">Indicates whether static member of this type are safe for multi-threaded operations.</param>
/// <param name="isInstance">Indicates whether instance members of this type are safe for multi-threaded operations.</param>
public static XmlEmptyElementSyntax XmlThreadSafetyElement(bool isStatic, bool isInstance)
{
return XmlEmptyElement(DocumentationCommentXmlNames.ThreadSafetyElementName).AddAttributes(
XmlTextAttribute(DocumentationCommentXmlNames.StaticAttributeName, isStatic.ToString().ToLowerInvariant()),
XmlTextAttribute(DocumentationCommentXmlNames.InstanceAttributeName, isInstance.ToString().ToLowerInvariant()));
}
/// <summary>
/// Creates a syntax node for a name attribute in a xml element within a xml documentation comment.
/// </summary>
/// <param name="parameterName">The value of the name attribute.</param>
public static XmlNameAttributeSyntax XmlNameAttribute(string parameterName)
{
return XmlNameAttribute(
XmlName(DocumentationCommentXmlNames.NameAttributeName),
Token(SyntaxKind.DoubleQuoteToken),
parameterName,
Token(SyntaxKind.DoubleQuoteToken))
.WithLeadingTrivia(Whitespace(" "));
}
/// <summary>
/// Creates a syntax node for a preliminary element within a xml documentation comment.
/// </summary>
public static XmlEmptyElementSyntax XmlPreliminaryElement()
{
return XmlEmptyElement(DocumentationCommentXmlNames.PreliminaryElementName);
}
/// <summary>
/// Creates a syntax node for a cref attribute within a xml documentation comment.
/// </summary>
/// <param name="cref">The <see cref="CrefSyntax"/> used for the xml cref attribute syntax.</param>
public static XmlCrefAttributeSyntax XmlCrefAttribute(CrefSyntax cref)
{
return XmlCrefAttribute(cref, SyntaxKind.DoubleQuoteToken);
}
/// <summary>
/// Creates a syntax node for a cref attribute within a xml documentation comment.
/// </summary>
/// <param name="cref">The <see cref="CrefSyntax"/> used for the xml cref attribute syntax.</param>
/// <param name="quoteKind">The kind of the quote for the referenced item in the cref attribute.</param>
public static XmlCrefAttributeSyntax XmlCrefAttribute(CrefSyntax cref, SyntaxKind quoteKind)
{
cref = cref.ReplaceTokens(cref.DescendantTokens(), XmlReplaceBracketTokens);
return XmlCrefAttribute(
XmlName(DocumentationCommentXmlNames.CrefAttributeName),
Token(quoteKind),
cref,
Token(quoteKind))
.WithLeadingTrivia(Whitespace(" "));
}
/// <summary>
/// Creates a remarks element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the remarks element.</param>
public static XmlElementSyntax XmlRemarksElement(params XmlNodeSyntax[] content)
{
return XmlRemarksElement(List(content));
}
/// <summary>
/// Creates a remarks element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the remarks element.</param>
public static XmlElementSyntax XmlRemarksElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.RemarksElementName, content);
}
/// <summary>
/// Creates a returns element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the returns element.</param>
public static XmlElementSyntax XmlReturnsElement(params XmlNodeSyntax[] content)
{
return XmlReturnsElement(List(content));
}
/// <summary>
/// Creates a returns element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the returns element.</param>
public static XmlElementSyntax XmlReturnsElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.ReturnsElementName, content);
}
/// <summary>
/// Creates the syntax representation of an xml value element (e.g. for xml documentation comments).
/// </summary>
/// <param name="content">A list of xml syntax nodes that represents the content of the value element.</param>
public static XmlElementSyntax XmlValueElement(params XmlNodeSyntax[] content)
{
return XmlValueElement(List(content));
}
/// <summary>
/// Creates the syntax representation of an xml value element (e.g. for xml documentation comments).
/// </summary>
/// <param name="content">A list of xml syntax nodes that represents the content of the value element.</param>
public static XmlElementSyntax XmlValueElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.ValueElementName, content);
}
/// <summary>
/// Creates the syntax representation of an exception element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the exception type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the exception element.</param>
public static XmlElementSyntax XmlExceptionElement(CrefSyntax cref, params XmlNodeSyntax[] content)
{
return XmlExceptionElement(cref, List(content));
}
/// <summary>
/// Creates the syntax representation of an exception element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the exception type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the exception element.</param>
public static XmlElementSyntax XmlExceptionElement(CrefSyntax cref, SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ExceptionElementName, content);
return element.WithStartTag(element.StartTag.AddAttributes(XmlCrefAttribute(cref)));
}
/// <summary>
/// Creates the syntax representation of a permission element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the permission type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the permission element.</param>
public static XmlElementSyntax XmlPermissionElement(CrefSyntax cref, params XmlNodeSyntax[] content)
{
return XmlPermissionElement(cref, List(content));
}
/// <summary>
/// Creates the syntax representation of a permission element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the permission type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the permission element.</param>
public static XmlElementSyntax XmlPermissionElement(CrefSyntax cref, SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.PermissionElementName, content);
return element.WithStartTag(element.StartTag.AddAttributes(XmlCrefAttribute(cref)));
}
/// <summary>
/// Creates the syntax representation of an example element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the example element.</param>
public static XmlElementSyntax XmlExampleElement(params XmlNodeSyntax[] content)
{
return XmlExampleElement(List(content));
}
/// <summary>
/// Creates the syntax representation of an example element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the example element.</param>
public static XmlElementSyntax XmlExampleElement(SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ExampleElementName, content);
return element.WithStartTag(element.StartTag);
}
/// <summary>
/// Creates the syntax representation of a para element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the para element.</param>
public static XmlElementSyntax XmlParaElement(params XmlNodeSyntax[] content)
{
return XmlParaElement(List(content));
}
/// <summary>
/// Creates the syntax representation of a para element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the para element.</param>
public static XmlElementSyntax XmlParaElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(DocumentationCommentXmlNames.ParaElementName, content);
}
/// <summary>
/// Creates the syntax representation of a param element within xml documentation comments (e.g. for
/// documentation of method parameters).
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="content">A list of syntax nodes that represents the content of the param element (e.g.
/// the description and meaning of the parameter).</param>
public static XmlElementSyntax XmlParamElement(string parameterName, params XmlNodeSyntax[] content)
{
return XmlParamElement(parameterName, List(content));
}
/// <summary>
/// Creates the syntax representation of a param element within xml documentation comments (e.g. for
/// documentation of method parameters).
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="content">A list of syntax nodes that represents the content of the param element (e.g.
/// the description and meaning of the parameter).</param>
public static XmlElementSyntax XmlParamElement(string parameterName, SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ParameterElementName, content);
return element.WithStartTag(element.StartTag.AddAttributes(XmlNameAttribute(parameterName)));
}
/// <summary>
/// Creates the syntax representation of a paramref element within xml documentation comments (e.g. for
/// referencing particular parameters of a method).
/// </summary>
/// <param name="parameterName">The name of the referenced parameter.</param>
public static XmlEmptyElementSyntax XmlParamRefElement(string parameterName)
{
return XmlEmptyElement(DocumentationCommentXmlNames.ParameterReferenceElementName).AddAttributes(XmlNameAttribute(parameterName));
}
/// <summary>
/// Creates the syntax representation of a see element within xml documentation comments,
/// that points to the 'null' language keyword.
/// </summary>
public static XmlEmptyElementSyntax XmlNullKeywordElement()
{
return XmlKeywordElement("null");
}
/// <summary>
/// Creates the syntax representation of a see element within xml documentation comments,
/// that points to a language keyword.
/// </summary>
/// <param name="keyword">The language keyword to which the see element points to.</param>
private static XmlEmptyElementSyntax XmlKeywordElement(string keyword)
{
return XmlEmptyElement(DocumentationCommentXmlNames.SeeElementName).AddAttributes(
XmlTextAttribute(DocumentationCommentXmlNames.LangwordAttributeName, keyword));
}
/// <summary>
/// Creates the syntax representation of a placeholder element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the placeholder element.</param>
public static XmlElementSyntax XmlPlaceholderElement(params XmlNodeSyntax[] content)
{
return XmlPlaceholderElement(List(content));
}
/// <summary>
/// Creates the syntax representation of a placeholder element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the placeholder element.</param>
public static XmlElementSyntax XmlPlaceholderElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(DocumentationCommentXmlNames.PlaceholderElementName, content);
}
/// <summary>
/// Creates the syntax representation of a named empty xml element within xml documentation comments.
/// </summary>
/// <param name="localName">The name of the empty xml element.</param>
public static XmlEmptyElementSyntax XmlEmptyElement(string localName)
{
return XmlEmptyElement(XmlName(localName));
}
/// <summary>
/// Creates the syntax representation of a named xml element within xml documentation comments.
/// </summary>
/// <param name="localName">The name of the empty xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml element.</param>
public static XmlElementSyntax XmlElement(string localName, SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(XmlName(localName), content);
}
/// <summary>
/// Creates the syntax representation of a named xml element within xml documentation comments.
/// </summary>
/// <param name="name">The name of the empty xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml element.</param>
public static XmlElementSyntax XmlElement(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(
XmlElementStartTag(name),
content,
XmlElementEndTag(name));
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="value">The value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(string name, string value)
{
return XmlTextAttribute(name, XmlTextLiteral(value));
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(string name, params SyntaxToken[] textTokens)
{
return XmlTextAttribute(XmlName(name), SyntaxKind.DoubleQuoteToken, TokenList(textTokens));
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="quoteKind">The kind of the quote token to be used to quote the value (e.g. " or ').</param>
/// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(string name, SyntaxKind quoteKind, SyntaxTokenList textTokens)
{
return XmlTextAttribute(XmlName(name), quoteKind, textTokens);
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="quoteKind">The kind of the quote token to be used to quote the value (e.g. " or ').</param>
/// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(XmlNameSyntax name, SyntaxKind quoteKind, SyntaxTokenList textTokens)
{
return XmlTextAttribute(name, Token(quoteKind), textTokens, Token(quoteKind))
.WithLeadingTrivia(Whitespace(" "));
}
/// <summary>
/// Creates the syntax representation of an xml element that spans multiple text lines.
/// </summary>
/// <param name="localName">The name of the xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml multi line element.</param>
public static XmlElementSyntax XmlMultiLineElement(string localName, SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(XmlName(localName), content);
}
/// <summary>
/// Creates the syntax representation of an xml element that spans multiple text lines.
/// </summary>
/// <param name="name">The name of the xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml multi line element.</param>
public static XmlElementSyntax XmlMultiLineElement(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(
XmlElementStartTag(name),
content,
XmlElementEndTag(name));
}
/// <summary>
/// Creates the syntax representation of an xml text that contains a newline token with a documentation comment
/// exterior trivia at the end (continued documentation comment).
/// </summary>
/// <param name="text">The raw text within the new line.</param>
public static XmlTextSyntax XmlNewLine(string text)
{
return XmlText(XmlTextNewLine(text));
}
/// <summary>
/// Creates the syntax representation of an xml newline token with a documentation comment exterior trivia at
/// the end (continued documentation comment).
/// </summary>
/// <param name="text">The raw text within the new line.</param>
public static SyntaxToken XmlTextNewLine(string text)
{
return XmlTextNewLine(text, true);
}
/// <summary>
/// Creates a token with kind XmlTextLiteralNewLineToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The xml text new line value.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken XmlTextNewLine(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(
InternalSyntax.SyntaxFactory.XmlTextNewLine(
leading.Node,
text,
value,
trailing.Node));
}
/// <summary>
/// Creates the syntax representation of an xml newline token for xml documentation comments.
/// </summary>
/// <param name="text">The raw text within the new line.</param>
/// <param name="continueXmlDocumentationComment">
/// If set to true, a documentation comment exterior token will be added to the trailing trivia
/// of the new token.</param>
public static SyntaxToken XmlTextNewLine(string text, bool continueXmlDocumentationComment)
{
var token = new SyntaxToken(
InternalSyntax.SyntaxFactory.XmlTextNewLine(
ElasticMarker.UnderlyingNode,
text,
text,
ElasticMarker.UnderlyingNode));
if (continueXmlDocumentationComment)
token = token.WithTrailingTrivia(token.TrailingTrivia.Add(DocumentationCommentExterior("/// ")));
return token;
}
/// <summary>
/// Generates the syntax representation of a xml text node (e.g. for xml documentation comments).
/// </summary>
/// <param name="value">The string literal used as the text of the xml text node.</param>
public static XmlTextSyntax XmlText(string value)
{
return XmlText(XmlTextLiteral(value));
}
/// <summary>
/// Generates the syntax representation of a xml text node (e.g. for xml documentation comments).
/// </summary>
/// <param name="textTokens">A list of text tokens used as the text of the xml text node.</param>
public static XmlTextSyntax XmlText(params SyntaxToken[] textTokens)
{
return XmlText(TokenList(textTokens));
}
/// <summary>
/// Generates the syntax representation of an xml text literal.
/// </summary>
/// <param name="value">The text used within the xml text literal.</param>
public static SyntaxToken XmlTextLiteral(string value)
{
// TODO: [RobinSedlaczek] It is no compiler hot path here I think. But the contribution guide
// states to avoid LINQ (https://github.com/dotnet/roslyn/wiki/Contributing-Code). With
// XText we have a reference to System.Xml.Linq. Isn't this rule valid here?
string encoded = new XText(value).ToString();
return XmlTextLiteral(
TriviaList(),
encoded,
value,
TriviaList());
}
/// <summary>
/// Generates the syntax representation of an xml text literal.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The text used within the xml text literal.</param>
public static SyntaxToken XmlTextLiteral(string text, string value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Helper method that replaces less-than and greater-than characters with brackets.
/// </summary>
/// <param name="originalToken">The original token that is to be replaced.</param>
/// <param name="rewrittenToken">The new rewritten token.</param>
/// <returns>Returns the new rewritten token with replaced characters.</returns>
private static SyntaxToken XmlReplaceBracketTokens(SyntaxToken originalToken, SyntaxToken rewrittenToken)
{
if (rewrittenToken.IsKind(SyntaxKind.LessThanToken) && string.Equals("<", rewrittenToken.Text, StringComparison.Ordinal))
return Token(rewrittenToken.LeadingTrivia, SyntaxKind.LessThanToken, "{", rewrittenToken.ValueText, rewrittenToken.TrailingTrivia);
if (rewrittenToken.IsKind(SyntaxKind.GreaterThanToken) && string.Equals(">", rewrittenToken.Text, StringComparison.Ordinal))
return Token(rewrittenToken.LeadingTrivia, SyntaxKind.GreaterThanToken, "}", rewrittenToken.ValueText, rewrittenToken.TrailingTrivia);
return rewrittenToken;
}
/// <summary>
/// Creates a trivia with kind DocumentationCommentExteriorTrivia.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
public static SyntaxTrivia DocumentationCommentExterior(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.DocumentationCommentExteriorTrivia(text);
}
/// <summary>
/// Creates an empty list of syntax nodes.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
public static SyntaxList<TNode> List<TNode>() where TNode : SyntaxNode
{
return default(SyntaxList<TNode>);
}
/// <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>
/// <returns></returns>
public static SyntaxList<TNode> SingletonList<TNode>(TNode node) where TNode : SyntaxNode
{
return new SyntaxList<TNode>(node);
}
/// <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 static SyntaxList<TNode> List<TNode>(IEnumerable<TNode> nodes) where TNode : SyntaxNode
{
return new SyntaxList<TNode>(nodes);
}
/// <summary>
/// Creates an empty list of tokens.
/// </summary>
public static SyntaxTokenList TokenList()
{
return default(SyntaxTokenList);
}
/// <summary>
/// Creates a singleton list of tokens.
/// </summary>
/// <param name="token">The single token.</param>
public static SyntaxTokenList TokenList(SyntaxToken token)
{
return new SyntaxTokenList(token);
}
/// <summary>
/// Creates a list of tokens.
/// </summary>
/// <param name="tokens">An array of tokens.</param>
public static SyntaxTokenList TokenList(params SyntaxToken[] tokens)
{
return new SyntaxTokenList(tokens);
}
/// <summary>
/// Creates a list of tokens.
/// </summary>
/// <param name="tokens"></param>
/// <returns></returns>
public static SyntaxTokenList TokenList(IEnumerable<SyntaxToken> tokens)
{
return new SyntaxTokenList(tokens);
}
/// <summary>
/// Creates a trivia from a StructuredTriviaSyntax node.
/// </summary>
public static SyntaxTrivia Trivia(StructuredTriviaSyntax node)
{
return new SyntaxTrivia(default(SyntaxToken), node.Green, position: 0, index: 0);
}
/// <summary>
/// Creates an empty list of trivia.
/// </summary>
public static SyntaxTriviaList TriviaList()
{
return default(SyntaxTriviaList);
}
/// <summary>
/// Creates a singleton list of trivia.
/// </summary>
/// <param name="trivia">A single trivia.</param>
public static SyntaxTriviaList TriviaList(SyntaxTrivia trivia)
{
return new SyntaxTriviaList(trivia);
}
/// <summary>
/// Creates a list of trivia.
/// </summary>
/// <param name="trivias">An array of trivia.</param>
public static SyntaxTriviaList TriviaList(params SyntaxTrivia[] trivias)
=> new SyntaxTriviaList(trivias);
/// <summary>
/// Creates a list of trivia.
/// </summary>
/// <param name="trivias">A sequence of trivia.</param>
public static SyntaxTriviaList TriviaList(IEnumerable<SyntaxTrivia> trivias)
=> new SyntaxTriviaList(trivias);
/// <summary>
/// Creates an empty separated list.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>() where TNode : SyntaxNode
{
return default(SeparatedSyntaxList<TNode>);
}
/// <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 static SeparatedSyntaxList<TNode> SingletonSeparatedList<TNode>(TNode node) where TNode : SyntaxNode
{
return new SeparatedSyntaxList<TNode>(new SyntaxNodeOrTokenList(node, index: 0));
}
/// <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 static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<TNode>? nodes) where TNode : SyntaxNode
{
if (nodes == null)
{
return default(SeparatedSyntaxList<TNode>);
}
var collection = nodes as ICollection<TNode>;
if (collection != null && collection.Count == 0)
{
return default(SeparatedSyntaxList<TNode>);
}
using (var enumerator = nodes.GetEnumerator())
{
if (!enumerator.MoveNext())
{
return default(SeparatedSyntaxList<TNode>);
}
var firstNode = enumerator.Current;
if (!enumerator.MoveNext())
{
return SingletonSeparatedList<TNode>(firstNode);
}
var builder = new SeparatedSyntaxListBuilder<TNode>(collection != null ? collection.Count : 3);
builder.Add(firstNode);
var commaToken = Token(SyntaxKind.CommaToken);
do
{
builder.AddSeparator(commaToken);
builder.Add(enumerator.Current);
}
while (enumerator.MoveNext());
return builder.ToList();
}
}
/// <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 static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<TNode>? nodes, IEnumerable<SyntaxToken>? separators) where TNode : SyntaxNode
{
// Interleave the nodes and the separators. The number of separators must be equal to or 1 less than the number of nodes or
// an argument exception is thrown.
if (nodes != null)
{
IEnumerator<TNode> enumerator = nodes.GetEnumerator();
SeparatedSyntaxListBuilder<TNode> builder = SeparatedSyntaxListBuilder<TNode>.Create();
if (separators != null)
{
foreach (SyntaxToken token in separators)
{
if (!enumerator.MoveNext())
{
throw new ArgumentException($"{nameof(nodes)} must not be empty.", nameof(nodes));
}
builder.Add(enumerator.Current);
builder.AddSeparator(token);
}
}
if (enumerator.MoveNext())
{
builder.Add(enumerator.Current);
if (enumerator.MoveNext())
{
throw new ArgumentException($"{nameof(separators)} must have 1 fewer element than {nameof(nodes)}", nameof(separators));
}
}
return builder.ToList();
}
if (separators != null)
{
throw new ArgumentException($"When {nameof(nodes)} is null, {nameof(separators)} must also be null.", nameof(separators));
}
return default(SeparatedSyntaxList<TNode>);
}
/// <summary>
/// Creates a separated list from a sequence of nodes and tokens, starting with a node and alternating between additional nodes and separator tokens.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="nodesAndTokens">A sequence of nodes or tokens, alternating between nodes and separator tokens.</param>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<SyntaxNodeOrToken> nodesAndTokens) where TNode : SyntaxNode
{
return SeparatedList<TNode>(NodeOrTokenList(nodesAndTokens));
}
/// <summary>
/// Creates a separated list from a <see cref="SyntaxNodeOrTokenList"/>, where the list elements start with a node and then alternate between
/// additional nodes and separator tokens.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="nodesAndTokens">The list of nodes and tokens.</param>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(SyntaxNodeOrTokenList nodesAndTokens) where TNode : SyntaxNode
{
if (!HasSeparatedNodeTokenPattern(nodesAndTokens))
{
throw new ArgumentException(CodeAnalysisResources.NodeOrTokenOutOfSequence);
}
if (!NodesAreCorrectType<TNode>(nodesAndTokens))
{
throw new ArgumentException(CodeAnalysisResources.UnexpectedTypeOfNodeInList);
}
return new SeparatedSyntaxList<TNode>(nodesAndTokens);
}
private static bool NodesAreCorrectType<TNode>(SyntaxNodeOrTokenList list)
{
for (int i = 0, n = list.Count; i < n; i++)
{
var element = list[i];
if (element.IsNode && !(element.AsNode() is TNode))
{
return false;
}
}
return true;
}
private static bool HasSeparatedNodeTokenPattern(SyntaxNodeOrTokenList list)
{
for (int i = 0, n = list.Count; i < n; i++)
{
var element = list[i];
if (element.IsToken == ((i & 1) == 0))
{
return false;
}
}
return true;
}
/// <summary>
/// Creates an empty <see cref="SyntaxNodeOrTokenList"/>.
/// </summary>
public static SyntaxNodeOrTokenList NodeOrTokenList()
{
return default(SyntaxNodeOrTokenList);
}
/// <summary>
/// Create a <see cref="SyntaxNodeOrTokenList"/> from a sequence of <see cref="SyntaxNodeOrToken"/>.
/// </summary>
/// <param name="nodesAndTokens">The sequence of nodes and tokens</param>
public static SyntaxNodeOrTokenList NodeOrTokenList(IEnumerable<SyntaxNodeOrToken> nodesAndTokens)
{
return new SyntaxNodeOrTokenList(nodesAndTokens);
}
/// <summary>
/// Create a <see cref="SyntaxNodeOrTokenList"/> from one or more <see cref="SyntaxNodeOrToken"/>.
/// </summary>
/// <param name="nodesAndTokens">The nodes and tokens</param>
public static SyntaxNodeOrTokenList NodeOrTokenList(params SyntaxNodeOrToken[] nodesAndTokens)
{
return new SyntaxNodeOrTokenList(nodesAndTokens);
}
/// <summary>
/// Creates an IdentifierNameSyntax node.
/// </summary>
/// <param name="name">The identifier name.</param>
public static IdentifierNameSyntax IdentifierName(string name)
{
return IdentifierName(Identifier(name));
}
// direct access to parsing for common grammar areas
/// <summary>
/// Create a new syntax tree from a syntax node.
/// </summary>
public static SyntaxTree SyntaxTree(SyntaxNode root, ParseOptions? options = null, string path = "", Encoding? encoding = null)
{
return CSharpSyntaxTree.Create((CSharpSyntaxNode)root, (CSharpParseOptions?)options, path, encoding);
}
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
#pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads.
/// <inheritdoc cref="CSharpSyntaxTree.ParseText(string, CSharpParseOptions?, string, Encoding?, CancellationToken)"/>
public static SyntaxTree ParseSyntaxTree(
string text,
ParseOptions? options = null,
string path = "",
Encoding? encoding = null,
CancellationToken cancellationToken = default)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, encoding, cancellationToken);
}
/// <inheritdoc cref="CSharpSyntaxTree.ParseText(SourceText, CSharpParseOptions?, string, CancellationToken)"/>
public static SyntaxTree ParseSyntaxTree(
SourceText text,
ParseOptions? options = null,
string path = "",
CancellationToken cancellationToken = default)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, cancellationToken);
}
#pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads.
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Parse a list of trivia rules for leading trivia.
/// </summary>
public static SyntaxTriviaList ParseLeadingTrivia(string text, int offset = 0)
{
return ParseLeadingTrivia(text, CSharpParseOptions.Default, offset);
}
/// <summary>
/// Parse a list of trivia rules for leading trivia.
/// </summary>
internal static SyntaxTriviaList ParseLeadingTrivia(string text, CSharpParseOptions? options, int offset = 0)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), options))
{
return lexer.LexSyntaxLeadingTrivia();
}
}
/// <summary>
/// Parse a list of trivia using the parsing rules for trailing trivia.
/// </summary>
public static SyntaxTriviaList ParseTrailingTrivia(string text, int offset = 0)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default))
{
return lexer.LexSyntaxTrailingTrivia();
}
}
// TODO: If this becomes a real API, we'll need to add an offset parameter to
// match the pattern followed by the other ParseX methods.
internal static CrefSyntax? ParseCref(string text)
{
// NOTE: Conceivably, we could introduce a new code path that directly calls
// DocumentationCommentParser.ParseCrefAttributeValue, but that method won't
// work unless the lexer makes the appropriate mode transitions. Rather than
// introducing a new code path that will have to be kept in sync with other
// mode changes distributed throughout Lexer, SyntaxParser, and
// DocumentationCommentParser, we'll just wrap the text in some lexable syntax
// and then extract the piece we want.
string commentText = string.Format(@"/// <see cref=""{0}""/>", text);
SyntaxTriviaList leadingTrivia = ParseLeadingTrivia(commentText, CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose));
Debug.Assert(leadingTrivia.Count == 1);
SyntaxTrivia trivia = leadingTrivia.First();
DocumentationCommentTriviaSyntax structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure()!;
Debug.Assert(structure.Content.Count == 2);
XmlEmptyElementSyntax elementSyntax = (XmlEmptyElementSyntax)structure.Content[1];
Debug.Assert(elementSyntax.Attributes.Count == 1);
XmlAttributeSyntax attributeSyntax = (XmlAttributeSyntax)elementSyntax.Attributes[0];
return attributeSyntax.Kind() == SyntaxKind.XmlCrefAttribute ? ((XmlCrefAttributeSyntax)attributeSyntax).Cref : null;
}
/// <summary>
/// Parse a C# language token.
/// </summary>
/// <param name="text">The text of the token including leading and trailing trivia.</param>
/// <param name="offset">Optional offset into text.</param>
public static SyntaxToken ParseToken(string text, int offset = 0)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default))
{
return new SyntaxToken(lexer.Lex(InternalSyntax.LexerMode.Syntax));
}
}
/// <summary>
/// Parse a sequence of C# language tokens.
/// </summary>
/// <param name="text">The text of all the tokens.</param>
/// <param name="initialTokenPosition">An integer to use as the starting position of the first token.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">Parse options.</param>
public static IEnumerable<SyntaxToken> ParseTokens(string text, int offset = 0, int initialTokenPosition = 0, CSharpParseOptions? options = null)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), options ?? CSharpParseOptions.Default))
{
var position = initialTokenPosition;
while (true)
{
var token = lexer.Lex(InternalSyntax.LexerMode.Syntax);
yield return new SyntaxToken(parent: null, token: token, position: position, index: 0);
position += token.FullWidth;
if (token.Kind == SyntaxKind.EndOfFileToken)
{
break;
}
}
}
}
/// <summary>
/// Parse a NameSyntax node using the grammar rule for names.
/// </summary>
public static NameSyntax ParseName(string text, int offset = 0, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseName();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (NameSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a TypeNameSyntax node using the grammar rule for type names.
/// </summary>
// Backcompat overload, do not remove
[EditorBrowsable(EditorBrowsableState.Never)]
public static TypeSyntax ParseTypeName(string text, int offset, bool consumeFullText)
{
return ParseTypeName(text, offset, options: null, consumeFullText);
}
/// <summary>
/// Parse a TypeNameSyntax node using the grammar rule for type names.
/// </summary>
public static TypeSyntax ParseTypeName(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseTypeName();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (TypeSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse an ExpressionSyntax node using the lowest precedence grammar rule for expressions.
/// </summary>
/// <param name="text">The text of the expression.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static ExpressionSyntax ParseExpression(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseExpression();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (ExpressionSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a StatementSyntaxNode using grammar rule for statements.
/// </summary>
/// <param name="text">The text of the statement.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static StatementSyntax ParseStatement(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseStatement();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (StatementSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a MemberDeclarationSyntax. This includes all of the kinds of members that could occur in a type declaration.
/// If nothing resembling a valid member declaration is found in the input, returns null.
/// </summary>
/// <param name="text">The text of the declaration.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input following a declaration should be treated as an error</param>
public static MemberDeclarationSyntax? ParseMemberDeclaration(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseMemberDeclaration();
if (node == null)
{
return null;
}
return (MemberDeclarationSyntax)(consumeFullText ? parser.ConsumeUnexpectedTokens(node) : node).CreateRed();
}
}
/// <summary>
/// Parse a CompilationUnitSyntax using the grammar rule for an entire compilation unit (file). To produce a
/// SyntaxTree instance, use CSharpSyntaxTree.ParseText instead.
/// </summary>
/// <param name="text">The text of the compilation unit.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
public static CompilationUnitSyntax ParseCompilationUnit(string text, int offset = 0, CSharpParseOptions? options = null)
{
// note that we do not need a "consumeFullText" parameter, because parsing a compilation unit always must
// consume input until the end-of-file
using (var lexer = MakeLexer(text, offset, options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseCompilationUnit();
return (CompilationUnitSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a ParameterListSyntax node.
/// </summary>
/// <param name="text">The text of the parenthesized parameter list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static ParameterListSyntax ParseParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseParenthesizedParameterList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (ParameterListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a BracketedParameterListSyntax node.
/// </summary>
/// <param name="text">The text of the bracketed parameter list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static BracketedParameterListSyntax ParseBracketedParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseBracketedParameterList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (BracketedParameterListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse an ArgumentListSyntax node.
/// </summary>
/// <param name="text">The text of the parenthesized argument list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static ArgumentListSyntax ParseArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseParenthesizedArgumentList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (ArgumentListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a BracketedArgumentListSyntax node.
/// </summary>
/// <param name="text">The text of the bracketed argument list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static BracketedArgumentListSyntax ParseBracketedArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseBracketedArgumentList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (BracketedArgumentListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse an AttributeArgumentListSyntax node.
/// </summary>
/// <param name="text">The text of the attribute argument list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static AttributeArgumentListSyntax ParseAttributeArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseAttributeArgumentList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (AttributeArgumentListSyntax)node.CreateRed();
}
}
/// <summary>
/// Helper method for wrapping a string in a SourceText.
/// </summary>
private static SourceText MakeSourceText(string text, int offset)
{
return SourceText.From(text, Encoding.UTF8).GetSubText(offset);
}
private static InternalSyntax.Lexer MakeLexer(string text, int offset, CSharpParseOptions? options = null)
{
return new InternalSyntax.Lexer(
text: MakeSourceText(text, offset),
options: options ?? CSharpParseOptions.Default);
}
private static InternalSyntax.LanguageParser MakeParser(InternalSyntax.Lexer lexer)
{
return new InternalSyntax.LanguageParser(lexer, oldTree: null, changes: null);
}
/// <summary>
/// Determines if two trees are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldTree">The original tree.</param>
/// <param name="newTree">The new tree.</param>
/// <param name="topLevel">
/// If true then the trees are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent(SyntaxTree? oldTree, SyntaxTree? newTree, bool topLevel)
{
if (oldTree == null && newTree == null)
{
return true;
}
if (oldTree == null || newTree == null)
{
return false;
}
return SyntaxEquivalence.AreEquivalent(oldTree, newTree, ignoreChildNode: null, topLevel: topLevel);
}
/// <summary>
/// Determines if two syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldNode">The old node.</param>
/// <param name="newNode">The new node.</param>
/// <param name="topLevel">
/// If true then the nodes are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, bool topLevel)
{
return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode: null, topLevel: topLevel);
}
/// <summary>
/// Determines if two syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldNode">The old node.</param>
/// <param name="newNode">The new node.</param>
/// <param name="ignoreChildNode">
/// If specified called for every child syntax node (not token) that is visited during the comparison.
/// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded.
/// </param>
public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, Func<SyntaxKind, bool>? ignoreChildNode = null)
{
return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode: ignoreChildNode, topLevel: false);
}
/// <summary>
/// Determines if two syntax tokens are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldToken">The old token.</param>
/// <param name="newToken">The new token.</param>
public static bool AreEquivalent(SyntaxToken oldToken, SyntaxToken newToken)
{
return SyntaxEquivalence.AreEquivalent(oldToken, newToken);
}
/// <summary>
/// Determines if two lists of tokens are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old token list.</param>
/// <param name="newList">The new token list.</param>
public static bool AreEquivalent(SyntaxTokenList oldList, SyntaxTokenList newList)
{
return SyntaxEquivalence.AreEquivalent(oldList, newList);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="topLevel">
/// If true then the nodes are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent<TNode>(SyntaxList<TNode> oldList, SyntaxList<TNode> newList, bool topLevel)
where TNode : CSharpSyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="ignoreChildNode">
/// If specified called for every child syntax node (not token) that is visited during the comparison.
/// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded.
/// </param>
public static bool AreEquivalent<TNode>(SyntaxList<TNode> oldList, SyntaxList<TNode> newList, Func<SyntaxKind, bool>? ignoreChildNode = null)
where TNode : SyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="topLevel">
/// If true then the nodes are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent<TNode>(SeparatedSyntaxList<TNode> oldList, SeparatedSyntaxList<TNode> newList, bool topLevel)
where TNode : SyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="ignoreChildNode">
/// If specified called for every child syntax node (not token) that is visited during the comparison.
/// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded.
/// </param>
public static bool AreEquivalent<TNode>(SeparatedSyntaxList<TNode> oldList, SeparatedSyntaxList<TNode> newList, Func<SyntaxKind, bool>? ignoreChildNode = null)
where TNode : SyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false);
}
internal static TypeSyntax? GetStandaloneType(TypeSyntax? node)
{
if (node != null)
{
var parent = node.Parent as ExpressionSyntax;
if (parent != null && (node.Kind() == SyntaxKind.IdentifierName || node.Kind() == SyntaxKind.GenericName))
{
switch (parent.Kind())
{
case SyntaxKind.QualifiedName:
var qualifiedName = (QualifiedNameSyntax)parent;
if (qualifiedName.Right == node)
{
return qualifiedName;
}
break;
case SyntaxKind.AliasQualifiedName:
var aliasQualifiedName = (AliasQualifiedNameSyntax)parent;
if (aliasQualifiedName.Name == node)
{
return aliasQualifiedName;
}
break;
}
}
}
return node;
}
/// <summary>
/// Gets the containing expression that is actually a language expression and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// </summary>
public static ExpressionSyntax GetStandaloneExpression(ExpressionSyntax expression)
{
return SyntaxFactory.GetStandaloneNode(expression) as ExpressionSyntax ?? expression;
}
/// <summary>
/// Gets the containing expression that is actually a language expression (or something that
/// GetSymbolInfo can be applied to) and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// Similarly, if the input node is a cref part that is not independently meaningful, then
/// the result will be the full cref. Besides an expression, an input that is a NameSyntax
/// of a SubpatternSyntax, e.g. in `name: 3` may cause this method to return the enclosing
/// SubpatternSyntax.
/// </summary>
internal static CSharpSyntaxNode? GetStandaloneNode(CSharpSyntaxNode? node)
{
if (node == null || !(node is ExpressionSyntax || node is CrefSyntax))
{
return node;
}
switch (node.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
case SyntaxKind.NameMemberCref:
case SyntaxKind.IndexerMemberCref:
case SyntaxKind.OperatorMemberCref:
case SyntaxKind.ConversionOperatorMemberCref:
case SyntaxKind.ArrayType:
case SyntaxKind.NullableType:
// Adjustment may be required.
break;
default:
return node;
}
CSharpSyntaxNode? parent = node.Parent;
if (parent == null)
{
return node;
}
switch (parent.Kind())
{
case SyntaxKind.QualifiedName:
if (((QualifiedNameSyntax)parent).Right == node)
{
return parent;
}
break;
case SyntaxKind.AliasQualifiedName:
if (((AliasQualifiedNameSyntax)parent).Name == node)
{
return parent;
}
break;
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
if (((MemberAccessExpressionSyntax)parent).Name == node)
{
return parent;
}
break;
case SyntaxKind.MemberBindingExpression:
{
if (((MemberBindingExpressionSyntax)parent).Name == node)
{
return parent;
}
break;
}
// Only care about name member crefs because the other cref members
// are identifier by keywords, not syntax nodes.
case SyntaxKind.NameMemberCref:
if (((NameMemberCrefSyntax)parent).Name == node)
{
CSharpSyntaxNode? grandparent = parent.Parent;
return grandparent != null && grandparent.Kind() == SyntaxKind.QualifiedCref
? grandparent
: parent;
}
break;
case SyntaxKind.QualifiedCref:
if (((QualifiedCrefSyntax)parent).Member == node)
{
return parent;
}
break;
case SyntaxKind.ArrayCreationExpression:
if (((ArrayCreationExpressionSyntax)parent).Type == node)
{
return parent;
}
break;
case SyntaxKind.ObjectCreationExpression:
if (node.Kind() == SyntaxKind.NullableType && ((ObjectCreationExpressionSyntax)parent).Type == node)
{
return parent;
}
break;
case SyntaxKind.StackAllocArrayCreationExpression:
if (((StackAllocArrayCreationExpressionSyntax)parent).Type == node)
{
return parent;
}
break;
case SyntaxKind.NameColon:
if (parent.Parent.IsKind(SyntaxKind.Subpattern))
{
return parent.Parent;
}
break;
}
return node;
}
/// <summary>
/// Given a conditional binding expression, find corresponding conditional access node.
/// </summary>
internal static ConditionalAccessExpressionSyntax? FindConditionalAccessNodeForBinding(CSharpSyntaxNode node)
{
var currentNode = node;
Debug.Assert(currentNode.Kind() == SyntaxKind.MemberBindingExpression ||
currentNode.Kind() == SyntaxKind.ElementBindingExpression);
// In a well formed tree, the corresponding access node should be one of the ancestors
// and its "?" token should precede the binding syntax.
while (currentNode != null)
{
currentNode = currentNode.Parent;
Debug.Assert(currentNode != null, "binding should be enclosed in a conditional access");
if (currentNode.Kind() == SyntaxKind.ConditionalAccessExpression)
{
var condAccess = (ConditionalAccessExpressionSyntax)currentNode;
if (condAccess.OperatorToken.EndPosition == node.Position)
{
return condAccess;
}
}
}
return null;
}
/// <summary>
/// Converts a generic name expression into one without the generic arguments.
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static ExpressionSyntax? GetNonGenericExpression(ExpressionSyntax expression)
{
if (expression != null)
{
switch (expression.Kind())
{
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
var max = (MemberAccessExpressionSyntax)expression;
if (max.Name.Kind() == SyntaxKind.GenericName)
{
var gn = (GenericNameSyntax)max.Name;
return SyntaxFactory.BinaryExpression(expression.Kind(), max.Expression, max.OperatorToken, SyntaxFactory.IdentifierName(gn.Identifier));
}
break;
case SyntaxKind.QualifiedName:
var qn = (QualifiedNameSyntax)expression;
if (qn.Right.Kind() == SyntaxKind.GenericName)
{
var gn = (GenericNameSyntax)qn.Right;
return SyntaxFactory.QualifiedName(qn.Left, qn.DotToken, SyntaxFactory.IdentifierName(gn.Identifier));
}
break;
case SyntaxKind.AliasQualifiedName:
var an = (AliasQualifiedNameSyntax)expression;
if (an.Name.Kind() == SyntaxKind.GenericName)
{
var gn = (GenericNameSyntax)an.Name;
return SyntaxFactory.AliasQualifiedName(an.Alias, an.ColonColonToken, SyntaxFactory.IdentifierName(gn.Identifier));
}
break;
}
}
return expression;
}
/// <summary>
/// Determines whether the given text is considered a syntactically complete submission.
/// Throws <see cref="ArgumentException"/> if the tree was not compiled as an interactive submission.
/// </summary>
public static bool IsCompleteSubmission(SyntaxTree tree)
{
if (tree == null)
{
throw new ArgumentNullException(nameof(tree));
}
if (tree.Options.Kind != SourceCodeKind.Script)
{
throw new ArgumentException(CSharpResources.SyntaxTreeIsNotASubmission);
}
if (!tree.HasCompilationUnitRoot)
{
return false;
}
var compilation = (CompilationUnitSyntax)tree.GetRoot();
if (!compilation.HasErrors)
{
return true;
}
foreach (var error in compilation.EndOfFileToken.GetDiagnostics())
{
switch ((ErrorCode)error.Code)
{
case ErrorCode.ERR_OpenEndedComment:
case ErrorCode.ERR_EndifDirectiveExpected:
case ErrorCode.ERR_EndRegionDirectiveExpected:
return false;
}
}
var lastNode = compilation.ChildNodes().LastOrDefault();
if (lastNode == null)
{
return true;
}
// unterminated multi-line comment:
if (lastNode.HasTrailingTrivia && lastNode.ContainsDiagnostics && HasUnterminatedMultiLineComment(lastNode.GetTrailingTrivia()))
{
return false;
}
if (lastNode.IsKind(SyntaxKind.IncompleteMember))
{
return false;
}
// All top-level constructs but global statement (i.e. extern alias, using directive, global attribute, and declarations)
// should have a closing token (semicolon, closing brace or bracket) to be complete.
if (!lastNode.IsKind(SyntaxKind.GlobalStatement))
{
var closingToken = lastNode.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
return !closingToken.IsMissing;
}
var globalStatement = (GlobalStatementSyntax)lastNode;
var token = lastNode.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
if (token.IsMissing)
{
// expression statement terminating semicolon might be missing in script code:
if (tree.Options.Kind == SourceCodeKind.Regular ||
!globalStatement.Statement.IsKind(SyntaxKind.ExpressionStatement) ||
!token.IsKind(SyntaxKind.SemicolonToken))
{
return false;
}
token = token.GetPreviousToken(predicate: SyntaxToken.Any, stepInto: CodeAnalysis.SyntaxTrivia.Any);
if (token.IsMissing)
{
return false;
}
}
foreach (var error in token.GetDiagnostics())
{
switch ((ErrorCode)error.Code)
{
// unterminated character or string literal:
case ErrorCode.ERR_NewlineInConst:
// unterminated verbatim string literal:
case ErrorCode.ERR_UnterminatedStringLit:
// unexpected token following a global statement:
case ErrorCode.ERR_GlobalDefinitionOrStatementExpected:
case ErrorCode.ERR_EOFExpected:
return false;
}
}
return true;
}
private static bool HasUnterminatedMultiLineComment(SyntaxTriviaList triviaList)
{
foreach (var trivia in triviaList)
{
if (trivia.ContainsDiagnostics && trivia.Kind() == SyntaxKind.MultiLineCommentTrivia)
{
return true;
}
}
return false;
}
/// <summary>Creates a new CaseSwitchLabelSyntax instance.</summary>
public static CaseSwitchLabelSyntax CaseSwitchLabel(ExpressionSyntax value)
{
return SyntaxFactory.CaseSwitchLabel(SyntaxFactory.Token(SyntaxKind.CaseKeyword), value, SyntaxFactory.Token(SyntaxKind.ColonToken));
}
/// <summary>Creates a new DefaultSwitchLabelSyntax instance.</summary>
public static DefaultSwitchLabelSyntax DefaultSwitchLabel()
{
return SyntaxFactory.DefaultSwitchLabel(SyntaxFactory.Token(SyntaxKind.DefaultKeyword), SyntaxFactory.Token(SyntaxKind.ColonToken));
}
/// <summary>Creates a new BlockSyntax instance.</summary>
public static BlockSyntax Block(params StatementSyntax[] statements)
{
return Block(List(statements));
}
/// <summary>Creates a new BlockSyntax instance.</summary>
public static BlockSyntax Block(IEnumerable<StatementSyntax> statements)
{
return Block(List(statements));
}
public static PropertyDeclarationSyntax PropertyDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax type,
ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier,
SyntaxToken identifier,
AccessorListSyntax accessorList)
{
return SyntaxFactory.PropertyDeclaration(
attributeLists,
modifiers,
type,
explicitInterfaceSpecifier,
identifier,
accessorList,
expressionBody: null,
initializer: null);
}
public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
SyntaxToken implicitOrExplicitKeyword,
SyntaxToken operatorKeyword,
TypeSyntax type,
ParameterListSyntax parameterList,
BlockSyntax body,
SyntaxToken semicolonToken)
{
return SyntaxFactory.ConversionOperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
implicitOrExplicitKeyword: implicitOrExplicitKeyword,
operatorKeyword: operatorKeyword,
type: type,
parameterList: parameterList,
body: body,
expressionBody: null,
semicolonToken: semicolonToken);
}
public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers,
SyntaxToken implicitOrExplicitKeyword,
SyntaxToken operatorKeyword,
TypeSyntax type,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody,
SyntaxToken semicolonToken)
{
return SyntaxFactory.ConversionOperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
implicitOrExplicitKeyword: implicitOrExplicitKeyword,
explicitInterfaceSpecifier: null,
operatorKeyword: operatorKeyword,
type: type,
parameterList: parameterList,
body: body,
expressionBody: expressionBody,
semicolonToken: semicolonToken);
}
public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
SyntaxToken implicitOrExplicitKeyword,
TypeSyntax type,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody)
{
return SyntaxFactory.ConversionOperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
implicitOrExplicitKeyword: implicitOrExplicitKeyword,
explicitInterfaceSpecifier: null,
type: type,
parameterList: parameterList,
body: body,
expressionBody: expressionBody);
}
/// <summary>Creates a new OperatorDeclarationSyntax instance.</summary>
public static OperatorDeclarationSyntax OperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
SyntaxToken operatorKeyword,
SyntaxToken operatorToken,
ParameterListSyntax parameterList,
BlockSyntax body,
SyntaxToken semicolonToken)
{
return SyntaxFactory.OperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
returnType: returnType,
operatorKeyword: operatorKeyword,
operatorToken: operatorToken,
parameterList: parameterList,
body: body,
expressionBody: null,
semicolonToken: semicolonToken);
}
/// <summary>Creates a new OperatorDeclarationSyntax instance.</summary>
public static OperatorDeclarationSyntax OperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
SyntaxToken operatorKeyword,
SyntaxToken operatorToken,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody,
SyntaxToken semicolonToken)
{
return SyntaxFactory.OperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
returnType: returnType,
explicitInterfaceSpecifier: null,
operatorKeyword: operatorKeyword,
operatorToken: operatorToken,
parameterList: parameterList,
body: body,
expressionBody: expressionBody,
semicolonToken: semicolonToken);
}
/// <summary>Creates a new OperatorDeclarationSyntax instance.</summary>
public static OperatorDeclarationSyntax OperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
SyntaxToken operatorToken,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody)
{
return SyntaxFactory.OperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
returnType: returnType,
explicitInterfaceSpecifier: null,
operatorToken: operatorToken,
parameterList: parameterList,
body: body,
expressionBody: expressionBody);
}
/// <summary>Creates a new UsingDirectiveSyntax instance.</summary>
public static UsingDirectiveSyntax UsingDirective(NameEqualsSyntax alias, NameSyntax name)
{
return UsingDirective(
usingKeyword: Token(SyntaxKind.UsingKeyword),
staticKeyword: default(SyntaxToken),
alias: alias,
name: name,
semicolonToken: Token(SyntaxKind.SemicolonToken));
}
public static UsingDirectiveSyntax UsingDirective(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken)
{
return UsingDirective(globalKeyword: default(SyntaxToken), usingKeyword, staticKeyword, alias, name, semicolonToken);
}
/// <summary>Creates a new ClassOrStructConstraintSyntax instance.</summary>
public static ClassOrStructConstraintSyntax ClassOrStructConstraint(SyntaxKind kind, SyntaxToken classOrStructKeyword)
{
return ClassOrStructConstraint(kind, classOrStructKeyword, questionToken: default(SyntaxToken));
}
// backwards compatibility for extended API
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, BlockSyntax body)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, body, expressionBody: null);
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, BlockSyntax body, SyntaxToken semicolonToken)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, keyword, body, expressionBody: null, semicolonToken);
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, body: null, expressionBody);
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, keyword, body: null, expressionBody, semicolonToken);
public static EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken identifier, EqualsValueClauseSyntax equalsValue)
=> EnumMemberDeclaration(attributeLists, modifiers: default,
identifier, equalsValue);
public static NamespaceDeclarationSyntax NamespaceDeclaration(NameSyntax name, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members)
=> NamespaceDeclaration(attributeLists: default, modifiers: default,
name, externs, usings, members);
public static NamespaceDeclarationSyntax NamespaceDeclaration(SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken)
=> NamespaceDeclaration(attributeLists: default, modifiers: default,
namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken);
/// <summary>Creates a new EventDeclarationSyntax instance.</summary>
public static EventDeclarationSyntax EventDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList)
{
return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken: default);
}
/// <summary>Creates a new EventDeclarationSyntax instance.</summary>
public static EventDeclarationSyntax EventDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, SyntaxToken semicolonToken)
{
return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList: null, semicolonToken);
}
/// <summary>Creates a new SwitchStatementSyntax instance.</summary>
public static SwitchStatementSyntax SwitchStatement(ExpressionSyntax expression, SyntaxList<SwitchSectionSyntax> sections)
{
bool needsParens = !(expression is TupleExpressionSyntax);
var openParen = needsParens ? SyntaxFactory.Token(SyntaxKind.OpenParenToken) : default;
var closeParen = needsParens ? SyntaxFactory.Token(SyntaxKind.CloseParenToken) : default;
return SyntaxFactory.SwitchStatement(
attributeLists: default,
SyntaxFactory.Token(SyntaxKind.SwitchKeyword),
openParen,
expression,
closeParen,
SyntaxFactory.Token(SyntaxKind.OpenBraceToken),
sections,
SyntaxFactory.Token(SyntaxKind.CloseBraceToken));
}
/// <summary>Creates a new SwitchStatementSyntax instance.</summary>
public static SwitchStatementSyntax SwitchStatement(ExpressionSyntax expression)
{
return SyntaxFactory.SwitchStatement(expression, default(SyntaxList<SwitchSectionSyntax>));
}
public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(ParameterSyntax parameter, CSharpSyntaxNode body)
=> body is BlockSyntax block
? SimpleLambdaExpression(parameter, block, null)
: SimpleLambdaExpression(parameter, null, (ExpressionSyntax)body);
public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body)
=> body is BlockSyntax block
? SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, block, null)
: SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, null, (ExpressionSyntax)body);
public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(CSharpSyntaxNode body)
=> ParenthesizedLambdaExpression(ParameterList(), body);
public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(ParameterListSyntax parameterList, CSharpSyntaxNode body)
=> body is BlockSyntax block
? ParenthesizedLambdaExpression(parameterList, block, null)
: ParenthesizedLambdaExpression(parameterList, null, (ExpressionSyntax)body);
public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxToken asyncKeyword, ParameterListSyntax parameterList, SyntaxToken arrowToken, CSharpSyntaxNode body)
=> body is BlockSyntax block
? ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, block, null)
: ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, null, (ExpressionSyntax)body);
public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(CSharpSyntaxNode body)
=> AnonymousMethodExpression(parameterList: null, body);
public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(ParameterListSyntax? parameterList, CSharpSyntaxNode body)
=> body is BlockSyntax block
? AnonymousMethodExpression(default(SyntaxTokenList), SyntaxFactory.Token(SyntaxKind.DelegateKeyword), parameterList, block, null)
: throw new ArgumentException(nameof(body));
public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(SyntaxToken asyncKeyword, SyntaxToken delegateKeyword, ParameterListSyntax parameterList, CSharpSyntaxNode body)
=> body is BlockSyntax block
? AnonymousMethodExpression(asyncKeyword, delegateKeyword, parameterList, block, null)
: throw new ArgumentException(nameof(body));
// BACK COMPAT OVERLOAD DO NOT MODIFY
[Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static SyntaxTree ParseSyntaxTree(
string text,
ParseOptions? options,
string path,
Encoding? encoding,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
CancellationToken cancellationToken)
{
return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken);
}
// BACK COMPAT OVERLOAD DO NOT MODIFY
[Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static SyntaxTree ParseSyntaxTree(
SourceText text,
ParseOptions? options,
string path,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
CancellationToken cancellationToken)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken);
}
// BACK COMPAT OVERLOAD DO NOT MODIFY
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public static SyntaxTree ParseSyntaxTree(
string text,
ParseOptions? options,
string path,
Encoding? encoding,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
bool? isGeneratedCode,
CancellationToken cancellationToken)
{
return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode, cancellationToken);
}
// BACK COMPAT OVERLOAD DO NOT MODIFY
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public static SyntaxTree ParseSyntaxTree(
SourceText text,
ParseOptions? options,
string path,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
bool? isGeneratedCode,
CancellationToken cancellationToken)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, diagnosticOptions, isGeneratedCode, cancellationToken);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A class containing factory methods for constructing syntax nodes, tokens and trivia.
/// </summary>
public static partial class SyntaxFactory
{
/// <summary>
/// A trivia with kind EndOfLineTrivia containing both the carriage return and line feed characters.
/// </summary>
public static SyntaxTrivia CarriageReturnLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.CarriageReturnLineFeed;
/// <summary>
/// A trivia with kind EndOfLineTrivia containing a single line feed character.
/// </summary>
public static SyntaxTrivia LineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.LineFeed;
/// <summary>
/// A trivia with kind EndOfLineTrivia containing a single carriage return character.
/// </summary>
public static SyntaxTrivia CarriageReturn { get; } = Syntax.InternalSyntax.SyntaxFactory.CarriageReturn;
/// <summary>
/// A trivia with kind WhitespaceTrivia containing a single space character.
/// </summary>
public static SyntaxTrivia Space { get; } = Syntax.InternalSyntax.SyntaxFactory.Space;
/// <summary>
/// A trivia with kind WhitespaceTrivia containing a single tab character.
/// </summary>
public static SyntaxTrivia Tab { get; } = Syntax.InternalSyntax.SyntaxFactory.Tab;
/// <summary>
/// An elastic trivia with kind EndOfLineTrivia containing both the carriage return and line feed characters.
/// Elastic trivia are used to denote trivia that was not produced by parsing source text, and are usually not
/// preserved during formatting.
/// </summary>
public static SyntaxTrivia ElasticCarriageReturnLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturnLineFeed;
/// <summary>
/// An elastic trivia with kind EndOfLineTrivia containing a single line feed character. Elastic trivia are used
/// to denote trivia that was not produced by parsing source text, and are usually not preserved during
/// formatting.
/// </summary>
public static SyntaxTrivia ElasticLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticLineFeed;
/// <summary>
/// An elastic trivia with kind EndOfLineTrivia containing a single carriage return character. Elastic trivia
/// are used to denote trivia that was not produced by parsing source text, and are usually not preserved during
/// formatting.
/// </summary>
public static SyntaxTrivia ElasticCarriageReturn { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturn;
/// <summary>
/// An elastic trivia with kind WhitespaceTrivia containing a single space character. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
public static SyntaxTrivia ElasticSpace { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticSpace;
/// <summary>
/// An elastic trivia with kind WhitespaceTrivia containing a single tab character. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
public static SyntaxTrivia ElasticTab { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticTab;
/// <summary>
/// An elastic trivia with kind WhitespaceTrivia containing no characters. Elastic marker trivia are included
/// automatically by factory methods when trivia is not specified. Syntax formatting will replace elastic
/// markers with appropriate trivia.
/// </summary>
public static SyntaxTrivia ElasticMarker { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticZeroSpace;
/// <summary>
/// Creates a trivia with kind EndOfLineTrivia containing the specified text.
/// </summary>
/// <param name="text">The text of the end of line. Any text can be specified here, however only carriage return and
/// line feed characters are recognized by the parser as end of line.</param>
public static SyntaxTrivia EndOfLine(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: false);
}
/// <summary>
/// Creates a trivia with kind EndOfLineTrivia containing the specified text. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
/// <param name="text">The text of the end of line. Any text can be specified here, however only carriage return and
/// line feed characters are recognized by the parser as end of line.</param>
public static SyntaxTrivia ElasticEndOfLine(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: true);
}
[Obsolete("Use SyntaxFactory.EndOfLine or SyntaxFactory.ElasticEndOfLine")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static SyntaxTrivia EndOfLine(string text, bool elastic)
{
return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic);
}
/// <summary>
/// Creates a trivia with kind WhitespaceTrivia containing the specified text.
/// </summary>
/// <param name="text">The text of the whitespace. Any text can be specified here, however only specific
/// whitespace characters are recognized by the parser.</param>
public static SyntaxTrivia Whitespace(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic: false);
}
/// <summary>
/// Creates a trivia with kind WhitespaceTrivia containing the specified text. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
/// <param name="text">The text of the whitespace. Any text can be specified here, however only specific
/// whitespace characters are recognized by the parser.</param>
public static SyntaxTrivia ElasticWhitespace(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic: false);
}
[Obsolete("Use SyntaxFactory.Whitespace or SyntaxFactory.ElasticWhitespace")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static SyntaxTrivia Whitespace(string text, bool elastic)
{
return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic);
}
/// <summary>
/// Creates a trivia with kind either SingleLineCommentTrivia or MultiLineCommentTrivia containing the specified
/// text.
/// </summary>
/// <param name="text">The entire text of the comment including the leading '//' token for single line comments
/// or stop or start tokens for multiline comments.</param>
public static SyntaxTrivia Comment(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.Comment(text);
}
/// <summary>
/// Creates a trivia with kind DisabledTextTrivia. Disabled text corresponds to any text between directives that
/// is not considered active.
/// </summary>
public static SyntaxTrivia DisabledText(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.DisabledText(text);
}
/// <summary>
/// Creates a trivia with kind PreprocessingMessageTrivia.
/// </summary>
public static SyntaxTrivia PreprocessingMessage(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.PreprocessingMessage(text);
}
/// <summary>
/// Trivia nodes represent parts of the program text that are not parts of the
/// syntactic grammar, such as spaces, newlines, comments, preprocessor
/// directives, and disabled code.
/// </summary>
/// <param name="kind">
/// A <see cref="SyntaxKind"/> representing the specific kind of <see cref="SyntaxTrivia"/>. One of
/// <see cref="SyntaxKind.WhitespaceTrivia"/>, <see cref="SyntaxKind.EndOfLineTrivia"/>,
/// <see cref="SyntaxKind.SingleLineCommentTrivia"/>, <see cref="SyntaxKind.MultiLineCommentTrivia"/>,
/// <see cref="SyntaxKind.DocumentationCommentExteriorTrivia"/>, <see cref="SyntaxKind.DisabledTextTrivia"/>
/// </param>
/// <param name="text">
/// The actual text of this token.
/// </param>
public static SyntaxTrivia SyntaxTrivia(SyntaxKind kind, string text)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
switch (kind)
{
case SyntaxKind.DisabledTextTrivia:
case SyntaxKind.DocumentationCommentExteriorTrivia:
case SyntaxKind.EndOfLineTrivia:
case SyntaxKind.MultiLineCommentTrivia:
case SyntaxKind.SingleLineCommentTrivia:
case SyntaxKind.WhitespaceTrivia:
return new SyntaxTrivia(default(SyntaxToken), new Syntax.InternalSyntax.SyntaxTrivia(kind, text, null, null), 0, 0);
default:
throw new ArgumentException("kind");
}
}
/// <summary>
/// Creates a token corresponding to a syntax kind. This method can be used for token syntax kinds whose text
/// can be inferred by the kind alone.
/// </summary>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <returns></returns>
public static SyntaxToken Token(SyntaxKind kind)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(ElasticMarker.UnderlyingNode, kind, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token corresponding to syntax kind. This method can be used for token syntax kinds whose text can
/// be inferred by the kind alone.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(leading.Node, kind, trailing.Node));
}
/// <summary>
/// Creates a token corresponding to syntax kind. This method gives control over token Text and ValueText.
///
/// For example, consider the text '<see cref="operator &#43;"/>'. To create a token for the value of
/// the operator symbol (&#43;), one would call
/// Token(default(SyntaxTriviaList), SyntaxKind.PlusToken, "&#43;", "+", default(SyntaxTriviaList)).
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <param name="text">The text from which this token was created (e.g. lexed).</param>
/// <param name="valueText">How C# should interpret the text of this token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, string text, string valueText, SyntaxTriviaList trailing)
{
switch (kind)
{
case SyntaxKind.IdentifierToken:
// Have a different representation.
throw new ArgumentException(CSharpResources.UseVerbatimIdentifier, nameof(kind));
case SyntaxKind.CharacterLiteralToken:
// Value should not have type string.
throw new ArgumentException(CSharpResources.UseLiteralForTokens, nameof(kind));
case SyntaxKind.NumericLiteralToken:
// Value should not have type string.
throw new ArgumentException(CSharpResources.UseLiteralForNumeric, nameof(kind));
}
if (!SyntaxFacts.IsAnyToken(kind))
{
throw new ArgumentException(string.Format(CSharpResources.ThisMethodCanOnlyBeUsedToCreateTokens, kind), nameof(kind));
}
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(leading.Node, kind, text, valueText, trailing.Node));
}
/// <summary>
/// Creates a missing token corresponding to syntax kind. A missing token is produced by the parser when an
/// expected token is not found. A missing token has no text and normally has associated diagnostics.
/// </summary>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
public static SyntaxToken MissingToken(SyntaxKind kind)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.MissingToken(ElasticMarker.UnderlyingNode, kind, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a missing token corresponding to syntax kind. A missing token is produced by the parser when an
/// expected token is not found. A missing token has no text and normally has associated diagnostics.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken MissingToken(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.MissingToken(leading.Node, kind, trailing.Node));
}
/// <summary>
/// Creates a token with kind IdentifierToken containing the specified text.
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character.</param>
/// </summary>
public static SyntaxToken Identifier(string text)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(ElasticMarker.UnderlyingNode, text, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind IdentifierToken containing the specified text.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Identifier(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(leading.Node, text, trailing.Node));
}
/// <summary>
/// Creates a verbatim token with kind IdentifierToken containing the specified text.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character as it is in source.</param>
/// <param name="valueText">The canonical value of the token's text.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken VerbatimIdentifier(SyntaxTriviaList leading, string text, string valueText, SyntaxTriviaList trailing)
{
if (text.StartsWith("@", StringComparison.Ordinal))
{
throw new ArgumentException("text should not start with an @ character.");
}
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(SyntaxKind.IdentifierName, leading.Node, "@" + text, valueText, trailing.Node));
}
/// <summary>
/// Creates a token with kind IdentifierToken containing the specified text.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="contextualKind">An alternative SyntaxKind that can be inferred for this token in special
/// contexts. These are usually keywords.</param>
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character.</param>
/// <param name="valueText">The text of the identifier name without escapes or leading '@' character.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
/// <returns></returns>
public static SyntaxToken Identifier(SyntaxTriviaList leading, SyntaxKind contextualKind, string text, string valueText, SyntaxTriviaList trailing)
{
return new SyntaxToken(InternalSyntax.SyntaxFactory.Identifier(contextualKind, leading.Node, text, valueText, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a 4-byte signed integer value.
/// </summary>
/// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(int value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte signed integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, int value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte signed integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, int value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a 4-byte unsigned integer value.
/// </summary>
/// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(uint value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte unsigned integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, uint value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte unsigned integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, uint value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from an 8-byte signed integer value.
/// </summary>
/// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(long value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte signed integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, long value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte signed integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, long value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from an 8-byte unsigned integer value.
/// </summary>
/// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(ulong value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte unsigned integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, ulong value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte unsigned integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, ulong value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a 4-byte floating point value.
/// </summary>
/// <param name="value">The 4-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(float value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte floating point value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, float value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte floating point value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte floating point value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, float value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from an 8-byte floating point value.
/// </summary>
/// <param name="value">The 8-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(double value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte floating point value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, double value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte floating point value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte floating point value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, double value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a decimal value.
/// </summary>
/// <param name="value">The decimal value to be represented by the returned token.</param>
public static SyntaxToken Literal(decimal value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding decimal value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The decimal value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, decimal value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding decimal value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The decimal value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, decimal value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind StringLiteralToken from a string value.
/// </summary>
/// <param name="value">The string value to be represented by the returned token.</param>
public static SyntaxToken Literal(string value)
{
return Literal(SymbolDisplay.FormatLiteral(value, quote: true), value);
}
/// <summary>
/// Creates a token with kind StringLiteralToken from the text and corresponding string value.
/// </summary>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The string value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, string value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind StringLiteralToken from the text and corresponding string value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The string value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind CharacterLiteralToken from a character value.
/// </summary>
/// <param name="value">The character value to be represented by the returned token.</param>
public static SyntaxToken Literal(char value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters), value);
}
/// <summary>
/// Creates a token with kind CharacterLiteralToken from the text and corresponding character value.
/// </summary>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The character value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, char value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind CharacterLiteralToken from the text and corresponding character value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The character value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, char value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind BadToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the bad token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken BadToken(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.BadToken(leading.Node, text, trailing.Node));
}
/// <summary>
/// Creates a token with kind XmlTextLiteralToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The xml text value.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken XmlTextLiteral(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind XmlEntityLiteralToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The xml entity value.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken XmlEntity(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlEntity(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates an xml documentation comment that abstracts xml syntax creation.
/// </summary>
/// <param name="content">
/// A list of xml node syntax that will be the content within the xml documentation comment
/// (e.g. a summary element, a returns element, exception element and so on).
/// </param>
public static DocumentationCommentTriviaSyntax DocumentationComment(params XmlNodeSyntax[] content)
{
return DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia, List(content))
.WithLeadingTrivia(DocumentationCommentExterior("/// "))
.WithTrailingTrivia(EndOfLine(""));
}
/// <summary>
/// Creates a summary element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the summary element.</param>
public static XmlElementSyntax XmlSummaryElement(params XmlNodeSyntax[] content)
{
return XmlSummaryElement(List(content));
}
/// <summary>
/// Creates a summary element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the summary element.</param>
public static XmlElementSyntax XmlSummaryElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.SummaryElementName, content);
}
/// <summary>
/// Creates a see element within an xml documentation comment.
/// </summary>
/// <param name="cref">A cref syntax node that points to the referenced item (e.g. a class, struct).</param>
public static XmlEmptyElementSyntax XmlSeeElement(CrefSyntax cref)
{
return XmlEmptyElement(DocumentationCommentXmlNames.SeeElementName).AddAttributes(XmlCrefAttribute(cref));
}
/// <summary>
/// Creates a seealso element within an xml documentation comment.
/// </summary>
/// <param name="cref">A cref syntax node that points to the referenced item (e.g. a class, struct).</param>
public static XmlEmptyElementSyntax XmlSeeAlsoElement(CrefSyntax cref)
{
return XmlEmptyElement(DocumentationCommentXmlNames.SeeAlsoElementName).AddAttributes(XmlCrefAttribute(cref));
}
/// <summary>
/// Creates a seealso element within an xml documentation comment.
/// </summary>
/// <param name="linkAddress">The uri of the referenced item.</param>
/// <param name="linkText">A list of xml node syntax that will be used as the link text for the referenced item.</param>
public static XmlElementSyntax XmlSeeAlsoElement(Uri linkAddress, SyntaxList<XmlNodeSyntax> linkText)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.SeeAlsoElementName, linkText);
return element.WithStartTag(element.StartTag.AddAttributes(XmlTextAttribute(DocumentationCommentXmlNames.CrefAttributeName, linkAddress.ToString())));
}
/// <summary>
/// Creates a threadsafety element within an xml documentation comment.
/// </summary>
public static XmlEmptyElementSyntax XmlThreadSafetyElement()
{
return XmlThreadSafetyElement(true, false);
}
/// <summary>
/// Creates a threadsafety element within an xml documentation comment.
/// </summary>
/// <param name="isStatic">Indicates whether static member of this type are safe for multi-threaded operations.</param>
/// <param name="isInstance">Indicates whether instance members of this type are safe for multi-threaded operations.</param>
public static XmlEmptyElementSyntax XmlThreadSafetyElement(bool isStatic, bool isInstance)
{
return XmlEmptyElement(DocumentationCommentXmlNames.ThreadSafetyElementName).AddAttributes(
XmlTextAttribute(DocumentationCommentXmlNames.StaticAttributeName, isStatic.ToString().ToLowerInvariant()),
XmlTextAttribute(DocumentationCommentXmlNames.InstanceAttributeName, isInstance.ToString().ToLowerInvariant()));
}
/// <summary>
/// Creates a syntax node for a name attribute in a xml element within a xml documentation comment.
/// </summary>
/// <param name="parameterName">The value of the name attribute.</param>
public static XmlNameAttributeSyntax XmlNameAttribute(string parameterName)
{
return XmlNameAttribute(
XmlName(DocumentationCommentXmlNames.NameAttributeName),
Token(SyntaxKind.DoubleQuoteToken),
parameterName,
Token(SyntaxKind.DoubleQuoteToken))
.WithLeadingTrivia(Whitespace(" "));
}
/// <summary>
/// Creates a syntax node for a preliminary element within a xml documentation comment.
/// </summary>
public static XmlEmptyElementSyntax XmlPreliminaryElement()
{
return XmlEmptyElement(DocumentationCommentXmlNames.PreliminaryElementName);
}
/// <summary>
/// Creates a syntax node for a cref attribute within a xml documentation comment.
/// </summary>
/// <param name="cref">The <see cref="CrefSyntax"/> used for the xml cref attribute syntax.</param>
public static XmlCrefAttributeSyntax XmlCrefAttribute(CrefSyntax cref)
{
return XmlCrefAttribute(cref, SyntaxKind.DoubleQuoteToken);
}
/// <summary>
/// Creates a syntax node for a cref attribute within a xml documentation comment.
/// </summary>
/// <param name="cref">The <see cref="CrefSyntax"/> used for the xml cref attribute syntax.</param>
/// <param name="quoteKind">The kind of the quote for the referenced item in the cref attribute.</param>
public static XmlCrefAttributeSyntax XmlCrefAttribute(CrefSyntax cref, SyntaxKind quoteKind)
{
cref = cref.ReplaceTokens(cref.DescendantTokens(), XmlReplaceBracketTokens);
return XmlCrefAttribute(
XmlName(DocumentationCommentXmlNames.CrefAttributeName),
Token(quoteKind),
cref,
Token(quoteKind))
.WithLeadingTrivia(Whitespace(" "));
}
/// <summary>
/// Creates a remarks element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the remarks element.</param>
public static XmlElementSyntax XmlRemarksElement(params XmlNodeSyntax[] content)
{
return XmlRemarksElement(List(content));
}
/// <summary>
/// Creates a remarks element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the remarks element.</param>
public static XmlElementSyntax XmlRemarksElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.RemarksElementName, content);
}
/// <summary>
/// Creates a returns element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the returns element.</param>
public static XmlElementSyntax XmlReturnsElement(params XmlNodeSyntax[] content)
{
return XmlReturnsElement(List(content));
}
/// <summary>
/// Creates a returns element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the returns element.</param>
public static XmlElementSyntax XmlReturnsElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.ReturnsElementName, content);
}
/// <summary>
/// Creates the syntax representation of an xml value element (e.g. for xml documentation comments).
/// </summary>
/// <param name="content">A list of xml syntax nodes that represents the content of the value element.</param>
public static XmlElementSyntax XmlValueElement(params XmlNodeSyntax[] content)
{
return XmlValueElement(List(content));
}
/// <summary>
/// Creates the syntax representation of an xml value element (e.g. for xml documentation comments).
/// </summary>
/// <param name="content">A list of xml syntax nodes that represents the content of the value element.</param>
public static XmlElementSyntax XmlValueElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.ValueElementName, content);
}
/// <summary>
/// Creates the syntax representation of an exception element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the exception type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the exception element.</param>
public static XmlElementSyntax XmlExceptionElement(CrefSyntax cref, params XmlNodeSyntax[] content)
{
return XmlExceptionElement(cref, List(content));
}
/// <summary>
/// Creates the syntax representation of an exception element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the exception type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the exception element.</param>
public static XmlElementSyntax XmlExceptionElement(CrefSyntax cref, SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ExceptionElementName, content);
return element.WithStartTag(element.StartTag.AddAttributes(XmlCrefAttribute(cref)));
}
/// <summary>
/// Creates the syntax representation of a permission element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the permission type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the permission element.</param>
public static XmlElementSyntax XmlPermissionElement(CrefSyntax cref, params XmlNodeSyntax[] content)
{
return XmlPermissionElement(cref, List(content));
}
/// <summary>
/// Creates the syntax representation of a permission element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the permission type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the permission element.</param>
public static XmlElementSyntax XmlPermissionElement(CrefSyntax cref, SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.PermissionElementName, content);
return element.WithStartTag(element.StartTag.AddAttributes(XmlCrefAttribute(cref)));
}
/// <summary>
/// Creates the syntax representation of an example element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the example element.</param>
public static XmlElementSyntax XmlExampleElement(params XmlNodeSyntax[] content)
{
return XmlExampleElement(List(content));
}
/// <summary>
/// Creates the syntax representation of an example element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the example element.</param>
public static XmlElementSyntax XmlExampleElement(SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ExampleElementName, content);
return element.WithStartTag(element.StartTag);
}
/// <summary>
/// Creates the syntax representation of a para element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the para element.</param>
public static XmlElementSyntax XmlParaElement(params XmlNodeSyntax[] content)
{
return XmlParaElement(List(content));
}
/// <summary>
/// Creates the syntax representation of a para element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the para element.</param>
public static XmlElementSyntax XmlParaElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(DocumentationCommentXmlNames.ParaElementName, content);
}
/// <summary>
/// Creates the syntax representation of a param element within xml documentation comments (e.g. for
/// documentation of method parameters).
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="content">A list of syntax nodes that represents the content of the param element (e.g.
/// the description and meaning of the parameter).</param>
public static XmlElementSyntax XmlParamElement(string parameterName, params XmlNodeSyntax[] content)
{
return XmlParamElement(parameterName, List(content));
}
/// <summary>
/// Creates the syntax representation of a param element within xml documentation comments (e.g. for
/// documentation of method parameters).
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="content">A list of syntax nodes that represents the content of the param element (e.g.
/// the description and meaning of the parameter).</param>
public static XmlElementSyntax XmlParamElement(string parameterName, SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ParameterElementName, content);
return element.WithStartTag(element.StartTag.AddAttributes(XmlNameAttribute(parameterName)));
}
/// <summary>
/// Creates the syntax representation of a paramref element within xml documentation comments (e.g. for
/// referencing particular parameters of a method).
/// </summary>
/// <param name="parameterName">The name of the referenced parameter.</param>
public static XmlEmptyElementSyntax XmlParamRefElement(string parameterName)
{
return XmlEmptyElement(DocumentationCommentXmlNames.ParameterReferenceElementName).AddAttributes(XmlNameAttribute(parameterName));
}
/// <summary>
/// Creates the syntax representation of a see element within xml documentation comments,
/// that points to the 'null' language keyword.
/// </summary>
public static XmlEmptyElementSyntax XmlNullKeywordElement()
{
return XmlKeywordElement("null");
}
/// <summary>
/// Creates the syntax representation of a see element within xml documentation comments,
/// that points to a language keyword.
/// </summary>
/// <param name="keyword">The language keyword to which the see element points to.</param>
private static XmlEmptyElementSyntax XmlKeywordElement(string keyword)
{
return XmlEmptyElement(DocumentationCommentXmlNames.SeeElementName).AddAttributes(
XmlTextAttribute(DocumentationCommentXmlNames.LangwordAttributeName, keyword));
}
/// <summary>
/// Creates the syntax representation of a placeholder element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the placeholder element.</param>
public static XmlElementSyntax XmlPlaceholderElement(params XmlNodeSyntax[] content)
{
return XmlPlaceholderElement(List(content));
}
/// <summary>
/// Creates the syntax representation of a placeholder element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the placeholder element.</param>
public static XmlElementSyntax XmlPlaceholderElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(DocumentationCommentXmlNames.PlaceholderElementName, content);
}
/// <summary>
/// Creates the syntax representation of a named empty xml element within xml documentation comments.
/// </summary>
/// <param name="localName">The name of the empty xml element.</param>
public static XmlEmptyElementSyntax XmlEmptyElement(string localName)
{
return XmlEmptyElement(XmlName(localName));
}
/// <summary>
/// Creates the syntax representation of a named xml element within xml documentation comments.
/// </summary>
/// <param name="localName">The name of the empty xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml element.</param>
public static XmlElementSyntax XmlElement(string localName, SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(XmlName(localName), content);
}
/// <summary>
/// Creates the syntax representation of a named xml element within xml documentation comments.
/// </summary>
/// <param name="name">The name of the empty xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml element.</param>
public static XmlElementSyntax XmlElement(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(
XmlElementStartTag(name),
content,
XmlElementEndTag(name));
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="value">The value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(string name, string value)
{
return XmlTextAttribute(name, XmlTextLiteral(value));
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(string name, params SyntaxToken[] textTokens)
{
return XmlTextAttribute(XmlName(name), SyntaxKind.DoubleQuoteToken, TokenList(textTokens));
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="quoteKind">The kind of the quote token to be used to quote the value (e.g. " or ').</param>
/// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(string name, SyntaxKind quoteKind, SyntaxTokenList textTokens)
{
return XmlTextAttribute(XmlName(name), quoteKind, textTokens);
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="quoteKind">The kind of the quote token to be used to quote the value (e.g. " or ').</param>
/// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(XmlNameSyntax name, SyntaxKind quoteKind, SyntaxTokenList textTokens)
{
return XmlTextAttribute(name, Token(quoteKind), textTokens, Token(quoteKind))
.WithLeadingTrivia(Whitespace(" "));
}
/// <summary>
/// Creates the syntax representation of an xml element that spans multiple text lines.
/// </summary>
/// <param name="localName">The name of the xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml multi line element.</param>
public static XmlElementSyntax XmlMultiLineElement(string localName, SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(XmlName(localName), content);
}
/// <summary>
/// Creates the syntax representation of an xml element that spans multiple text lines.
/// </summary>
/// <param name="name">The name of the xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml multi line element.</param>
public static XmlElementSyntax XmlMultiLineElement(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(
XmlElementStartTag(name),
content,
XmlElementEndTag(name));
}
/// <summary>
/// Creates the syntax representation of an xml text that contains a newline token with a documentation comment
/// exterior trivia at the end (continued documentation comment).
/// </summary>
/// <param name="text">The raw text within the new line.</param>
public static XmlTextSyntax XmlNewLine(string text)
{
return XmlText(XmlTextNewLine(text));
}
/// <summary>
/// Creates the syntax representation of an xml newline token with a documentation comment exterior trivia at
/// the end (continued documentation comment).
/// </summary>
/// <param name="text">The raw text within the new line.</param>
public static SyntaxToken XmlTextNewLine(string text)
{
return XmlTextNewLine(text, true);
}
/// <summary>
/// Creates a token with kind XmlTextLiteralNewLineToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The xml text new line value.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken XmlTextNewLine(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(
InternalSyntax.SyntaxFactory.XmlTextNewLine(
leading.Node,
text,
value,
trailing.Node));
}
/// <summary>
/// Creates the syntax representation of an xml newline token for xml documentation comments.
/// </summary>
/// <param name="text">The raw text within the new line.</param>
/// <param name="continueXmlDocumentationComment">
/// If set to true, a documentation comment exterior token will be added to the trailing trivia
/// of the new token.</param>
public static SyntaxToken XmlTextNewLine(string text, bool continueXmlDocumentationComment)
{
var token = new SyntaxToken(
InternalSyntax.SyntaxFactory.XmlTextNewLine(
ElasticMarker.UnderlyingNode,
text,
text,
ElasticMarker.UnderlyingNode));
if (continueXmlDocumentationComment)
token = token.WithTrailingTrivia(token.TrailingTrivia.Add(DocumentationCommentExterior("/// ")));
return token;
}
/// <summary>
/// Generates the syntax representation of a xml text node (e.g. for xml documentation comments).
/// </summary>
/// <param name="value">The string literal used as the text of the xml text node.</param>
public static XmlTextSyntax XmlText(string value)
{
return XmlText(XmlTextLiteral(value));
}
/// <summary>
/// Generates the syntax representation of a xml text node (e.g. for xml documentation comments).
/// </summary>
/// <param name="textTokens">A list of text tokens used as the text of the xml text node.</param>
public static XmlTextSyntax XmlText(params SyntaxToken[] textTokens)
{
return XmlText(TokenList(textTokens));
}
/// <summary>
/// Generates the syntax representation of an xml text literal.
/// </summary>
/// <param name="value">The text used within the xml text literal.</param>
public static SyntaxToken XmlTextLiteral(string value)
{
// TODO: [RobinSedlaczek] It is no compiler hot path here I think. But the contribution guide
// states to avoid LINQ (https://github.com/dotnet/roslyn/wiki/Contributing-Code). With
// XText we have a reference to System.Xml.Linq. Isn't this rule valid here?
string encoded = new XText(value).ToString();
return XmlTextLiteral(
TriviaList(),
encoded,
value,
TriviaList());
}
/// <summary>
/// Generates the syntax representation of an xml text literal.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The text used within the xml text literal.</param>
public static SyntaxToken XmlTextLiteral(string text, string value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Helper method that replaces less-than and greater-than characters with brackets.
/// </summary>
/// <param name="originalToken">The original token that is to be replaced.</param>
/// <param name="rewrittenToken">The new rewritten token.</param>
/// <returns>Returns the new rewritten token with replaced characters.</returns>
private static SyntaxToken XmlReplaceBracketTokens(SyntaxToken originalToken, SyntaxToken rewrittenToken)
{
if (rewrittenToken.IsKind(SyntaxKind.LessThanToken) && string.Equals("<", rewrittenToken.Text, StringComparison.Ordinal))
return Token(rewrittenToken.LeadingTrivia, SyntaxKind.LessThanToken, "{", rewrittenToken.ValueText, rewrittenToken.TrailingTrivia);
if (rewrittenToken.IsKind(SyntaxKind.GreaterThanToken) && string.Equals(">", rewrittenToken.Text, StringComparison.Ordinal))
return Token(rewrittenToken.LeadingTrivia, SyntaxKind.GreaterThanToken, "}", rewrittenToken.ValueText, rewrittenToken.TrailingTrivia);
return rewrittenToken;
}
/// <summary>
/// Creates a trivia with kind DocumentationCommentExteriorTrivia.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
public static SyntaxTrivia DocumentationCommentExterior(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.DocumentationCommentExteriorTrivia(text);
}
/// <summary>
/// Creates an empty list of syntax nodes.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
public static SyntaxList<TNode> List<TNode>() where TNode : SyntaxNode
{
return default(SyntaxList<TNode>);
}
/// <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>
/// <returns></returns>
public static SyntaxList<TNode> SingletonList<TNode>(TNode node) where TNode : SyntaxNode
{
return new SyntaxList<TNode>(node);
}
/// <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 static SyntaxList<TNode> List<TNode>(IEnumerable<TNode> nodes) where TNode : SyntaxNode
{
return new SyntaxList<TNode>(nodes);
}
/// <summary>
/// Creates an empty list of tokens.
/// </summary>
public static SyntaxTokenList TokenList()
{
return default(SyntaxTokenList);
}
/// <summary>
/// Creates a singleton list of tokens.
/// </summary>
/// <param name="token">The single token.</param>
public static SyntaxTokenList TokenList(SyntaxToken token)
{
return new SyntaxTokenList(token);
}
/// <summary>
/// Creates a list of tokens.
/// </summary>
/// <param name="tokens">An array of tokens.</param>
public static SyntaxTokenList TokenList(params SyntaxToken[] tokens)
{
return new SyntaxTokenList(tokens);
}
/// <summary>
/// Creates a list of tokens.
/// </summary>
/// <param name="tokens"></param>
/// <returns></returns>
public static SyntaxTokenList TokenList(IEnumerable<SyntaxToken> tokens)
{
return new SyntaxTokenList(tokens);
}
/// <summary>
/// Creates a trivia from a StructuredTriviaSyntax node.
/// </summary>
public static SyntaxTrivia Trivia(StructuredTriviaSyntax node)
{
return new SyntaxTrivia(default(SyntaxToken), node.Green, position: 0, index: 0);
}
/// <summary>
/// Creates an empty list of trivia.
/// </summary>
public static SyntaxTriviaList TriviaList()
{
return default(SyntaxTriviaList);
}
/// <summary>
/// Creates a singleton list of trivia.
/// </summary>
/// <param name="trivia">A single trivia.</param>
public static SyntaxTriviaList TriviaList(SyntaxTrivia trivia)
{
return new SyntaxTriviaList(trivia);
}
/// <summary>
/// Creates a list of trivia.
/// </summary>
/// <param name="trivias">An array of trivia.</param>
public static SyntaxTriviaList TriviaList(params SyntaxTrivia[] trivias)
=> new SyntaxTriviaList(trivias);
/// <summary>
/// Creates a list of trivia.
/// </summary>
/// <param name="trivias">A sequence of trivia.</param>
public static SyntaxTriviaList TriviaList(IEnumerable<SyntaxTrivia> trivias)
=> new SyntaxTriviaList(trivias);
/// <summary>
/// Creates an empty separated list.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>() where TNode : SyntaxNode
{
return default(SeparatedSyntaxList<TNode>);
}
/// <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 static SeparatedSyntaxList<TNode> SingletonSeparatedList<TNode>(TNode node) where TNode : SyntaxNode
{
return new SeparatedSyntaxList<TNode>(new SyntaxNodeOrTokenList(node, index: 0));
}
/// <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 static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<TNode>? nodes) where TNode : SyntaxNode
{
if (nodes == null)
{
return default(SeparatedSyntaxList<TNode>);
}
var collection = nodes as ICollection<TNode>;
if (collection != null && collection.Count == 0)
{
return default(SeparatedSyntaxList<TNode>);
}
using (var enumerator = nodes.GetEnumerator())
{
if (!enumerator.MoveNext())
{
return default(SeparatedSyntaxList<TNode>);
}
var firstNode = enumerator.Current;
if (!enumerator.MoveNext())
{
return SingletonSeparatedList<TNode>(firstNode);
}
var builder = new SeparatedSyntaxListBuilder<TNode>(collection != null ? collection.Count : 3);
builder.Add(firstNode);
var commaToken = Token(SyntaxKind.CommaToken);
do
{
builder.AddSeparator(commaToken);
builder.Add(enumerator.Current);
}
while (enumerator.MoveNext());
return builder.ToList();
}
}
/// <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 static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<TNode>? nodes, IEnumerable<SyntaxToken>? separators) where TNode : SyntaxNode
{
// Interleave the nodes and the separators. The number of separators must be equal to or 1 less than the number of nodes or
// an argument exception is thrown.
if (nodes != null)
{
IEnumerator<TNode> enumerator = nodes.GetEnumerator();
SeparatedSyntaxListBuilder<TNode> builder = SeparatedSyntaxListBuilder<TNode>.Create();
if (separators != null)
{
foreach (SyntaxToken token in separators)
{
if (!enumerator.MoveNext())
{
throw new ArgumentException($"{nameof(nodes)} must not be empty.", nameof(nodes));
}
builder.Add(enumerator.Current);
builder.AddSeparator(token);
}
}
if (enumerator.MoveNext())
{
builder.Add(enumerator.Current);
if (enumerator.MoveNext())
{
throw new ArgumentException($"{nameof(separators)} must have 1 fewer element than {nameof(nodes)}", nameof(separators));
}
}
return builder.ToList();
}
if (separators != null)
{
throw new ArgumentException($"When {nameof(nodes)} is null, {nameof(separators)} must also be null.", nameof(separators));
}
return default(SeparatedSyntaxList<TNode>);
}
/// <summary>
/// Creates a separated list from a sequence of nodes and tokens, starting with a node and alternating between additional nodes and separator tokens.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="nodesAndTokens">A sequence of nodes or tokens, alternating between nodes and separator tokens.</param>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<SyntaxNodeOrToken> nodesAndTokens) where TNode : SyntaxNode
{
return SeparatedList<TNode>(NodeOrTokenList(nodesAndTokens));
}
/// <summary>
/// Creates a separated list from a <see cref="SyntaxNodeOrTokenList"/>, where the list elements start with a node and then alternate between
/// additional nodes and separator tokens.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="nodesAndTokens">The list of nodes and tokens.</param>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(SyntaxNodeOrTokenList nodesAndTokens) where TNode : SyntaxNode
{
if (!HasSeparatedNodeTokenPattern(nodesAndTokens))
{
throw new ArgumentException(CodeAnalysisResources.NodeOrTokenOutOfSequence);
}
if (!NodesAreCorrectType<TNode>(nodesAndTokens))
{
throw new ArgumentException(CodeAnalysisResources.UnexpectedTypeOfNodeInList);
}
return new SeparatedSyntaxList<TNode>(nodesAndTokens);
}
private static bool NodesAreCorrectType<TNode>(SyntaxNodeOrTokenList list)
{
for (int i = 0, n = list.Count; i < n; i++)
{
var element = list[i];
if (element.IsNode && !(element.AsNode() is TNode))
{
return false;
}
}
return true;
}
private static bool HasSeparatedNodeTokenPattern(SyntaxNodeOrTokenList list)
{
for (int i = 0, n = list.Count; i < n; i++)
{
var element = list[i];
if (element.IsToken == ((i & 1) == 0))
{
return false;
}
}
return true;
}
/// <summary>
/// Creates an empty <see cref="SyntaxNodeOrTokenList"/>.
/// </summary>
public static SyntaxNodeOrTokenList NodeOrTokenList()
{
return default(SyntaxNodeOrTokenList);
}
/// <summary>
/// Create a <see cref="SyntaxNodeOrTokenList"/> from a sequence of <see cref="SyntaxNodeOrToken"/>.
/// </summary>
/// <param name="nodesAndTokens">The sequence of nodes and tokens</param>
public static SyntaxNodeOrTokenList NodeOrTokenList(IEnumerable<SyntaxNodeOrToken> nodesAndTokens)
{
return new SyntaxNodeOrTokenList(nodesAndTokens);
}
/// <summary>
/// Create a <see cref="SyntaxNodeOrTokenList"/> from one or more <see cref="SyntaxNodeOrToken"/>.
/// </summary>
/// <param name="nodesAndTokens">The nodes and tokens</param>
public static SyntaxNodeOrTokenList NodeOrTokenList(params SyntaxNodeOrToken[] nodesAndTokens)
{
return new SyntaxNodeOrTokenList(nodesAndTokens);
}
/// <summary>
/// Creates an IdentifierNameSyntax node.
/// </summary>
/// <param name="name">The identifier name.</param>
public static IdentifierNameSyntax IdentifierName(string name)
{
return IdentifierName(Identifier(name));
}
// direct access to parsing for common grammar areas
/// <summary>
/// Create a new syntax tree from a syntax node.
/// </summary>
public static SyntaxTree SyntaxTree(SyntaxNode root, ParseOptions? options = null, string path = "", Encoding? encoding = null)
{
return CSharpSyntaxTree.Create((CSharpSyntaxNode)root, (CSharpParseOptions?)options, path, encoding);
}
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
#pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads.
/// <inheritdoc cref="CSharpSyntaxTree.ParseText(string, CSharpParseOptions?, string, Encoding?, CancellationToken)"/>
public static SyntaxTree ParseSyntaxTree(
string text,
ParseOptions? options = null,
string path = "",
Encoding? encoding = null,
CancellationToken cancellationToken = default)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, encoding, cancellationToken);
}
/// <inheritdoc cref="CSharpSyntaxTree.ParseText(SourceText, CSharpParseOptions?, string, CancellationToken)"/>
public static SyntaxTree ParseSyntaxTree(
SourceText text,
ParseOptions? options = null,
string path = "",
CancellationToken cancellationToken = default)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, cancellationToken);
}
#pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads.
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Parse a list of trivia rules for leading trivia.
/// </summary>
public static SyntaxTriviaList ParseLeadingTrivia(string text, int offset = 0)
{
return ParseLeadingTrivia(text, CSharpParseOptions.Default, offset);
}
/// <summary>
/// Parse a list of trivia rules for leading trivia.
/// </summary>
internal static SyntaxTriviaList ParseLeadingTrivia(string text, CSharpParseOptions? options, int offset = 0)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), options))
{
return lexer.LexSyntaxLeadingTrivia();
}
}
/// <summary>
/// Parse a list of trivia using the parsing rules for trailing trivia.
/// </summary>
public static SyntaxTriviaList ParseTrailingTrivia(string text, int offset = 0)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default))
{
return lexer.LexSyntaxTrailingTrivia();
}
}
// TODO: If this becomes a real API, we'll need to add an offset parameter to
// match the pattern followed by the other ParseX methods.
internal static CrefSyntax? ParseCref(string text)
{
// NOTE: Conceivably, we could introduce a new code path that directly calls
// DocumentationCommentParser.ParseCrefAttributeValue, but that method won't
// work unless the lexer makes the appropriate mode transitions. Rather than
// introducing a new code path that will have to be kept in sync with other
// mode changes distributed throughout Lexer, SyntaxParser, and
// DocumentationCommentParser, we'll just wrap the text in some lexable syntax
// and then extract the piece we want.
string commentText = string.Format(@"/// <see cref=""{0}""/>", text);
SyntaxTriviaList leadingTrivia = ParseLeadingTrivia(commentText, CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose));
Debug.Assert(leadingTrivia.Count == 1);
SyntaxTrivia trivia = leadingTrivia.First();
DocumentationCommentTriviaSyntax structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure()!;
Debug.Assert(structure.Content.Count == 2);
XmlEmptyElementSyntax elementSyntax = (XmlEmptyElementSyntax)structure.Content[1];
Debug.Assert(elementSyntax.Attributes.Count == 1);
XmlAttributeSyntax attributeSyntax = (XmlAttributeSyntax)elementSyntax.Attributes[0];
return attributeSyntax.Kind() == SyntaxKind.XmlCrefAttribute ? ((XmlCrefAttributeSyntax)attributeSyntax).Cref : null;
}
/// <summary>
/// Parse a C# language token.
/// </summary>
/// <param name="text">The text of the token including leading and trailing trivia.</param>
/// <param name="offset">Optional offset into text.</param>
public static SyntaxToken ParseToken(string text, int offset = 0)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default))
{
return new SyntaxToken(lexer.Lex(InternalSyntax.LexerMode.Syntax));
}
}
/// <summary>
/// Parse a sequence of C# language tokens.
/// </summary>
/// <param name="text">The text of all the tokens.</param>
/// <param name="initialTokenPosition">An integer to use as the starting position of the first token.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">Parse options.</param>
public static IEnumerable<SyntaxToken> ParseTokens(string text, int offset = 0, int initialTokenPosition = 0, CSharpParseOptions? options = null)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), options ?? CSharpParseOptions.Default))
{
var position = initialTokenPosition;
while (true)
{
var token = lexer.Lex(InternalSyntax.LexerMode.Syntax);
yield return new SyntaxToken(parent: null, token: token, position: position, index: 0);
position += token.FullWidth;
if (token.Kind == SyntaxKind.EndOfFileToken)
{
break;
}
}
}
}
/// <summary>
/// Parse a NameSyntax node using the grammar rule for names.
/// </summary>
public static NameSyntax ParseName(string text, int offset = 0, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseName();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (NameSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a TypeNameSyntax node using the grammar rule for type names.
/// </summary>
// Backcompat overload, do not remove
[EditorBrowsable(EditorBrowsableState.Never)]
public static TypeSyntax ParseTypeName(string text, int offset, bool consumeFullText)
{
return ParseTypeName(text, offset, options: null, consumeFullText);
}
/// <summary>
/// Parse a TypeNameSyntax node using the grammar rule for type names.
/// </summary>
public static TypeSyntax ParseTypeName(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseTypeName();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (TypeSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse an ExpressionSyntax node using the lowest precedence grammar rule for expressions.
/// </summary>
/// <param name="text">The text of the expression.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static ExpressionSyntax ParseExpression(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseExpression();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (ExpressionSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a StatementSyntaxNode using grammar rule for statements.
/// </summary>
/// <param name="text">The text of the statement.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static StatementSyntax ParseStatement(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseStatement();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (StatementSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a MemberDeclarationSyntax. This includes all of the kinds of members that could occur in a type declaration.
/// If nothing resembling a valid member declaration is found in the input, returns null.
/// </summary>
/// <param name="text">The text of the declaration.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input following a declaration should be treated as an error</param>
public static MemberDeclarationSyntax? ParseMemberDeclaration(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseMemberDeclaration();
if (node == null)
{
return null;
}
return (MemberDeclarationSyntax)(consumeFullText ? parser.ConsumeUnexpectedTokens(node) : node).CreateRed();
}
}
/// <summary>
/// Parse a CompilationUnitSyntax using the grammar rule for an entire compilation unit (file). To produce a
/// SyntaxTree instance, use CSharpSyntaxTree.ParseText instead.
/// </summary>
/// <param name="text">The text of the compilation unit.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
public static CompilationUnitSyntax ParseCompilationUnit(string text, int offset = 0, CSharpParseOptions? options = null)
{
// note that we do not need a "consumeFullText" parameter, because parsing a compilation unit always must
// consume input until the end-of-file
using (var lexer = MakeLexer(text, offset, options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseCompilationUnit();
return (CompilationUnitSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a ParameterListSyntax node.
/// </summary>
/// <param name="text">The text of the parenthesized parameter list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static ParameterListSyntax ParseParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseParenthesizedParameterList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (ParameterListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a BracketedParameterListSyntax node.
/// </summary>
/// <param name="text">The text of the bracketed parameter list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static BracketedParameterListSyntax ParseBracketedParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseBracketedParameterList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (BracketedParameterListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse an ArgumentListSyntax node.
/// </summary>
/// <param name="text">The text of the parenthesized argument list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static ArgumentListSyntax ParseArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseParenthesizedArgumentList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (ArgumentListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a BracketedArgumentListSyntax node.
/// </summary>
/// <param name="text">The text of the bracketed argument list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static BracketedArgumentListSyntax ParseBracketedArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseBracketedArgumentList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (BracketedArgumentListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse an AttributeArgumentListSyntax node.
/// </summary>
/// <param name="text">The text of the attribute argument list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static AttributeArgumentListSyntax ParseAttributeArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseAttributeArgumentList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (AttributeArgumentListSyntax)node.CreateRed();
}
}
/// <summary>
/// Helper method for wrapping a string in a SourceText.
/// </summary>
private static SourceText MakeSourceText(string text, int offset)
{
return SourceText.From(text, Encoding.UTF8).GetSubText(offset);
}
private static InternalSyntax.Lexer MakeLexer(string text, int offset, CSharpParseOptions? options = null)
{
return new InternalSyntax.Lexer(
text: MakeSourceText(text, offset),
options: options ?? CSharpParseOptions.Default);
}
private static InternalSyntax.LanguageParser MakeParser(InternalSyntax.Lexer lexer)
{
return new InternalSyntax.LanguageParser(lexer, oldTree: null, changes: null);
}
/// <summary>
/// Determines if two trees are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldTree">The original tree.</param>
/// <param name="newTree">The new tree.</param>
/// <param name="topLevel">
/// If true then the trees are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent(SyntaxTree? oldTree, SyntaxTree? newTree, bool topLevel)
{
if (oldTree == null && newTree == null)
{
return true;
}
if (oldTree == null || newTree == null)
{
return false;
}
return SyntaxEquivalence.AreEquivalent(oldTree, newTree, ignoreChildNode: null, topLevel: topLevel);
}
/// <summary>
/// Determines if two syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldNode">The old node.</param>
/// <param name="newNode">The new node.</param>
/// <param name="topLevel">
/// If true then the nodes are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, bool topLevel)
{
return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode: null, topLevel: topLevel);
}
/// <summary>
/// Determines if two syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldNode">The old node.</param>
/// <param name="newNode">The new node.</param>
/// <param name="ignoreChildNode">
/// If specified called for every child syntax node (not token) that is visited during the comparison.
/// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded.
/// </param>
public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, Func<SyntaxKind, bool>? ignoreChildNode = null)
{
return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode: ignoreChildNode, topLevel: false);
}
/// <summary>
/// Determines if two syntax tokens are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldToken">The old token.</param>
/// <param name="newToken">The new token.</param>
public static bool AreEquivalent(SyntaxToken oldToken, SyntaxToken newToken)
{
return SyntaxEquivalence.AreEquivalent(oldToken, newToken);
}
/// <summary>
/// Determines if two lists of tokens are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old token list.</param>
/// <param name="newList">The new token list.</param>
public static bool AreEquivalent(SyntaxTokenList oldList, SyntaxTokenList newList)
{
return SyntaxEquivalence.AreEquivalent(oldList, newList);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="topLevel">
/// If true then the nodes are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent<TNode>(SyntaxList<TNode> oldList, SyntaxList<TNode> newList, bool topLevel)
where TNode : CSharpSyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="ignoreChildNode">
/// If specified called for every child syntax node (not token) that is visited during the comparison.
/// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded.
/// </param>
public static bool AreEquivalent<TNode>(SyntaxList<TNode> oldList, SyntaxList<TNode> newList, Func<SyntaxKind, bool>? ignoreChildNode = null)
where TNode : SyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="topLevel">
/// If true then the nodes are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent<TNode>(SeparatedSyntaxList<TNode> oldList, SeparatedSyntaxList<TNode> newList, bool topLevel)
where TNode : SyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="ignoreChildNode">
/// If specified called for every child syntax node (not token) that is visited during the comparison.
/// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded.
/// </param>
public static bool AreEquivalent<TNode>(SeparatedSyntaxList<TNode> oldList, SeparatedSyntaxList<TNode> newList, Func<SyntaxKind, bool>? ignoreChildNode = null)
where TNode : SyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false);
}
internal static TypeSyntax? GetStandaloneType(TypeSyntax? node)
{
if (node != null)
{
var parent = node.Parent as ExpressionSyntax;
if (parent != null && (node.Kind() == SyntaxKind.IdentifierName || node.Kind() == SyntaxKind.GenericName))
{
switch (parent.Kind())
{
case SyntaxKind.QualifiedName:
var qualifiedName = (QualifiedNameSyntax)parent;
if (qualifiedName.Right == node)
{
return qualifiedName;
}
break;
case SyntaxKind.AliasQualifiedName:
var aliasQualifiedName = (AliasQualifiedNameSyntax)parent;
if (aliasQualifiedName.Name == node)
{
return aliasQualifiedName;
}
break;
}
}
}
return node;
}
/// <summary>
/// Gets the containing expression that is actually a language expression and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// </summary>
public static ExpressionSyntax GetStandaloneExpression(ExpressionSyntax expression)
{
return SyntaxFactory.GetStandaloneNode(expression) as ExpressionSyntax ?? expression;
}
/// <summary>
/// Gets the containing expression that is actually a language expression (or something that
/// GetSymbolInfo can be applied to) and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// Similarly, if the input node is a cref part that is not independently meaningful, then
/// the result will be the full cref. Besides an expression, an input that is a NameSyntax
/// of a SubpatternSyntax, e.g. in `name: 3` may cause this method to return the enclosing
/// SubpatternSyntax.
/// </summary>
internal static CSharpSyntaxNode? GetStandaloneNode(CSharpSyntaxNode? node)
{
if (node == null || !(node is ExpressionSyntax || node is CrefSyntax))
{
return node;
}
switch (node.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
case SyntaxKind.NameMemberCref:
case SyntaxKind.IndexerMemberCref:
case SyntaxKind.OperatorMemberCref:
case SyntaxKind.ConversionOperatorMemberCref:
case SyntaxKind.ArrayType:
case SyntaxKind.NullableType:
// Adjustment may be required.
break;
default:
return node;
}
CSharpSyntaxNode? parent = node.Parent;
if (parent == null)
{
return node;
}
switch (parent.Kind())
{
case SyntaxKind.QualifiedName:
if (((QualifiedNameSyntax)parent).Right == node)
{
return parent;
}
break;
case SyntaxKind.AliasQualifiedName:
if (((AliasQualifiedNameSyntax)parent).Name == node)
{
return parent;
}
break;
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
if (((MemberAccessExpressionSyntax)parent).Name == node)
{
return parent;
}
break;
case SyntaxKind.MemberBindingExpression:
{
if (((MemberBindingExpressionSyntax)parent).Name == node)
{
return parent;
}
break;
}
// Only care about name member crefs because the other cref members
// are identifier by keywords, not syntax nodes.
case SyntaxKind.NameMemberCref:
if (((NameMemberCrefSyntax)parent).Name == node)
{
CSharpSyntaxNode? grandparent = parent.Parent;
return grandparent != null && grandparent.Kind() == SyntaxKind.QualifiedCref
? grandparent
: parent;
}
break;
case SyntaxKind.QualifiedCref:
if (((QualifiedCrefSyntax)parent).Member == node)
{
return parent;
}
break;
case SyntaxKind.ArrayCreationExpression:
if (((ArrayCreationExpressionSyntax)parent).Type == node)
{
return parent;
}
break;
case SyntaxKind.ObjectCreationExpression:
if (node.Kind() == SyntaxKind.NullableType && ((ObjectCreationExpressionSyntax)parent).Type == node)
{
return parent;
}
break;
case SyntaxKind.StackAllocArrayCreationExpression:
if (((StackAllocArrayCreationExpressionSyntax)parent).Type == node)
{
return parent;
}
break;
case SyntaxKind.NameColon:
if (parent.Parent.IsKind(SyntaxKind.Subpattern))
{
return parent.Parent;
}
break;
}
return node;
}
/// <summary>
/// Given a conditional binding expression, find corresponding conditional access node.
/// </summary>
internal static ConditionalAccessExpressionSyntax? FindConditionalAccessNodeForBinding(CSharpSyntaxNode node)
{
var currentNode = node;
Debug.Assert(currentNode.Kind() == SyntaxKind.MemberBindingExpression ||
currentNode.Kind() == SyntaxKind.ElementBindingExpression);
// In a well formed tree, the corresponding access node should be one of the ancestors
// and its "?" token should precede the binding syntax.
while (currentNode != null)
{
currentNode = currentNode.Parent;
Debug.Assert(currentNode != null, "binding should be enclosed in a conditional access");
if (currentNode.Kind() == SyntaxKind.ConditionalAccessExpression)
{
var condAccess = (ConditionalAccessExpressionSyntax)currentNode;
if (condAccess.OperatorToken.EndPosition == node.Position)
{
return condAccess;
}
}
}
return null;
}
/// <summary>
/// Converts a generic name expression into one without the generic arguments.
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static ExpressionSyntax? GetNonGenericExpression(ExpressionSyntax expression)
{
if (expression != null)
{
switch (expression.Kind())
{
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
var max = (MemberAccessExpressionSyntax)expression;
if (max.Name.Kind() == SyntaxKind.GenericName)
{
var gn = (GenericNameSyntax)max.Name;
return SyntaxFactory.BinaryExpression(expression.Kind(), max.Expression, max.OperatorToken, SyntaxFactory.IdentifierName(gn.Identifier));
}
break;
case SyntaxKind.QualifiedName:
var qn = (QualifiedNameSyntax)expression;
if (qn.Right.Kind() == SyntaxKind.GenericName)
{
var gn = (GenericNameSyntax)qn.Right;
return SyntaxFactory.QualifiedName(qn.Left, qn.DotToken, SyntaxFactory.IdentifierName(gn.Identifier));
}
break;
case SyntaxKind.AliasQualifiedName:
var an = (AliasQualifiedNameSyntax)expression;
if (an.Name.Kind() == SyntaxKind.GenericName)
{
var gn = (GenericNameSyntax)an.Name;
return SyntaxFactory.AliasQualifiedName(an.Alias, an.ColonColonToken, SyntaxFactory.IdentifierName(gn.Identifier));
}
break;
}
}
return expression;
}
/// <summary>
/// Determines whether the given text is considered a syntactically complete submission.
/// Throws <see cref="ArgumentException"/> if the tree was not compiled as an interactive submission.
/// </summary>
public static bool IsCompleteSubmission(SyntaxTree tree)
{
if (tree == null)
{
throw new ArgumentNullException(nameof(tree));
}
if (tree.Options.Kind != SourceCodeKind.Script)
{
throw new ArgumentException(CSharpResources.SyntaxTreeIsNotASubmission);
}
if (!tree.HasCompilationUnitRoot)
{
return false;
}
var compilation = (CompilationUnitSyntax)tree.GetRoot();
if (!compilation.HasErrors)
{
return true;
}
foreach (var error in compilation.EndOfFileToken.GetDiagnostics())
{
switch ((ErrorCode)error.Code)
{
case ErrorCode.ERR_OpenEndedComment:
case ErrorCode.ERR_EndifDirectiveExpected:
case ErrorCode.ERR_EndRegionDirectiveExpected:
return false;
}
}
var lastNode = compilation.ChildNodes().LastOrDefault();
if (lastNode == null)
{
return true;
}
// unterminated multi-line comment:
if (lastNode.HasTrailingTrivia && lastNode.ContainsDiagnostics && HasUnterminatedMultiLineComment(lastNode.GetTrailingTrivia()))
{
return false;
}
if (lastNode.IsKind(SyntaxKind.IncompleteMember))
{
return false;
}
// All top-level constructs but global statement (i.e. extern alias, using directive, global attribute, and declarations)
// should have a closing token (semicolon, closing brace or bracket) to be complete.
if (!lastNode.IsKind(SyntaxKind.GlobalStatement))
{
var closingToken = lastNode.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
return !closingToken.IsMissing;
}
var globalStatement = (GlobalStatementSyntax)lastNode;
var token = lastNode.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
if (token.IsMissing)
{
// expression statement terminating semicolon might be missing in script code:
if (tree.Options.Kind == SourceCodeKind.Regular ||
!globalStatement.Statement.IsKind(SyntaxKind.ExpressionStatement) ||
!token.IsKind(SyntaxKind.SemicolonToken))
{
return false;
}
token = token.GetPreviousToken(predicate: SyntaxToken.Any, stepInto: CodeAnalysis.SyntaxTrivia.Any);
if (token.IsMissing)
{
return false;
}
}
foreach (var error in token.GetDiagnostics())
{
switch ((ErrorCode)error.Code)
{
// unterminated character or string literal:
case ErrorCode.ERR_NewlineInConst:
// unterminated verbatim string literal:
case ErrorCode.ERR_UnterminatedStringLit:
// unexpected token following a global statement:
case ErrorCode.ERR_GlobalDefinitionOrStatementExpected:
case ErrorCode.ERR_EOFExpected:
return false;
}
}
return true;
}
private static bool HasUnterminatedMultiLineComment(SyntaxTriviaList triviaList)
{
foreach (var trivia in triviaList)
{
if (trivia.ContainsDiagnostics && trivia.Kind() == SyntaxKind.MultiLineCommentTrivia)
{
return true;
}
}
return false;
}
/// <summary>Creates a new CaseSwitchLabelSyntax instance.</summary>
public static CaseSwitchLabelSyntax CaseSwitchLabel(ExpressionSyntax value)
{
return SyntaxFactory.CaseSwitchLabel(SyntaxFactory.Token(SyntaxKind.CaseKeyword), value, SyntaxFactory.Token(SyntaxKind.ColonToken));
}
/// <summary>Creates a new DefaultSwitchLabelSyntax instance.</summary>
public static DefaultSwitchLabelSyntax DefaultSwitchLabel()
{
return SyntaxFactory.DefaultSwitchLabel(SyntaxFactory.Token(SyntaxKind.DefaultKeyword), SyntaxFactory.Token(SyntaxKind.ColonToken));
}
/// <summary>Creates a new BlockSyntax instance.</summary>
public static BlockSyntax Block(params StatementSyntax[] statements)
{
return Block(List(statements));
}
/// <summary>Creates a new BlockSyntax instance.</summary>
public static BlockSyntax Block(IEnumerable<StatementSyntax> statements)
{
return Block(List(statements));
}
public static PropertyDeclarationSyntax PropertyDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax type,
ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier,
SyntaxToken identifier,
AccessorListSyntax accessorList)
{
return SyntaxFactory.PropertyDeclaration(
attributeLists,
modifiers,
type,
explicitInterfaceSpecifier,
identifier,
accessorList,
expressionBody: null,
initializer: null);
}
public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
SyntaxToken implicitOrExplicitKeyword,
SyntaxToken operatorKeyword,
TypeSyntax type,
ParameterListSyntax parameterList,
BlockSyntax body,
SyntaxToken semicolonToken)
{
return SyntaxFactory.ConversionOperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
implicitOrExplicitKeyword: implicitOrExplicitKeyword,
operatorKeyword: operatorKeyword,
type: type,
parameterList: parameterList,
body: body,
expressionBody: null,
semicolonToken: semicolonToken);
}
public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers,
SyntaxToken implicitOrExplicitKeyword,
SyntaxToken operatorKeyword,
TypeSyntax type,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody,
SyntaxToken semicolonToken)
{
return SyntaxFactory.ConversionOperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
implicitOrExplicitKeyword: implicitOrExplicitKeyword,
explicitInterfaceSpecifier: null,
operatorKeyword: operatorKeyword,
type: type,
parameterList: parameterList,
body: body,
expressionBody: expressionBody,
semicolonToken: semicolonToken);
}
public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
SyntaxToken implicitOrExplicitKeyword,
TypeSyntax type,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody)
{
return SyntaxFactory.ConversionOperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
implicitOrExplicitKeyword: implicitOrExplicitKeyword,
explicitInterfaceSpecifier: null,
type: type,
parameterList: parameterList,
body: body,
expressionBody: expressionBody);
}
/// <summary>Creates a new OperatorDeclarationSyntax instance.</summary>
public static OperatorDeclarationSyntax OperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
SyntaxToken operatorKeyword,
SyntaxToken operatorToken,
ParameterListSyntax parameterList,
BlockSyntax body,
SyntaxToken semicolonToken)
{
return SyntaxFactory.OperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
returnType: returnType,
operatorKeyword: operatorKeyword,
operatorToken: operatorToken,
parameterList: parameterList,
body: body,
expressionBody: null,
semicolonToken: semicolonToken);
}
/// <summary>Creates a new OperatorDeclarationSyntax instance.</summary>
public static OperatorDeclarationSyntax OperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
SyntaxToken operatorKeyword,
SyntaxToken operatorToken,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody,
SyntaxToken semicolonToken)
{
return SyntaxFactory.OperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
returnType: returnType,
explicitInterfaceSpecifier: null,
operatorKeyword: operatorKeyword,
operatorToken: operatorToken,
parameterList: parameterList,
body: body,
expressionBody: expressionBody,
semicolonToken: semicolonToken);
}
/// <summary>Creates a new OperatorDeclarationSyntax instance.</summary>
public static OperatorDeclarationSyntax OperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
SyntaxToken operatorToken,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody)
{
return SyntaxFactory.OperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
returnType: returnType,
explicitInterfaceSpecifier: null,
operatorToken: operatorToken,
parameterList: parameterList,
body: body,
expressionBody: expressionBody);
}
/// <summary>Creates a new UsingDirectiveSyntax instance.</summary>
public static UsingDirectiveSyntax UsingDirective(NameEqualsSyntax alias, NameSyntax name)
{
return UsingDirective(
usingKeyword: Token(SyntaxKind.UsingKeyword),
staticKeyword: default(SyntaxToken),
alias: alias,
name: name,
semicolonToken: Token(SyntaxKind.SemicolonToken));
}
public static UsingDirectiveSyntax UsingDirective(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken)
{
return UsingDirective(globalKeyword: default(SyntaxToken), usingKeyword, staticKeyword, alias, name, semicolonToken);
}
/// <summary>Creates a new ClassOrStructConstraintSyntax instance.</summary>
public static ClassOrStructConstraintSyntax ClassOrStructConstraint(SyntaxKind kind, SyntaxToken classOrStructKeyword)
{
return ClassOrStructConstraint(kind, classOrStructKeyword, questionToken: default(SyntaxToken));
}
// backwards compatibility for extended API
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, BlockSyntax body)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, body, expressionBody: null);
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, BlockSyntax body, SyntaxToken semicolonToken)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, keyword, body, expressionBody: null, semicolonToken);
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, body: null, expressionBody);
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, keyword, body: null, expressionBody, semicolonToken);
public static EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken identifier, EqualsValueClauseSyntax equalsValue)
=> EnumMemberDeclaration(attributeLists, modifiers: default,
identifier, equalsValue);
public static NamespaceDeclarationSyntax NamespaceDeclaration(NameSyntax name, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members)
=> NamespaceDeclaration(attributeLists: default, modifiers: default,
name, externs, usings, members);
public static NamespaceDeclarationSyntax NamespaceDeclaration(SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken)
=> NamespaceDeclaration(attributeLists: default, modifiers: default,
namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken);
/// <summary>Creates a new EventDeclarationSyntax instance.</summary>
public static EventDeclarationSyntax EventDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList)
{
return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken: default);
}
/// <summary>Creates a new EventDeclarationSyntax instance.</summary>
public static EventDeclarationSyntax EventDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, SyntaxToken semicolonToken)
{
return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList: null, semicolonToken);
}
/// <summary>Creates a new SwitchStatementSyntax instance.</summary>
public static SwitchStatementSyntax SwitchStatement(ExpressionSyntax expression, SyntaxList<SwitchSectionSyntax> sections)
{
bool needsParens = !(expression is TupleExpressionSyntax);
var openParen = needsParens ? SyntaxFactory.Token(SyntaxKind.OpenParenToken) : default;
var closeParen = needsParens ? SyntaxFactory.Token(SyntaxKind.CloseParenToken) : default;
return SyntaxFactory.SwitchStatement(
attributeLists: default,
SyntaxFactory.Token(SyntaxKind.SwitchKeyword),
openParen,
expression,
closeParen,
SyntaxFactory.Token(SyntaxKind.OpenBraceToken),
sections,
SyntaxFactory.Token(SyntaxKind.CloseBraceToken));
}
/// <summary>Creates a new SwitchStatementSyntax instance.</summary>
public static SwitchStatementSyntax SwitchStatement(ExpressionSyntax expression)
{
return SyntaxFactory.SwitchStatement(expression, default(SyntaxList<SwitchSectionSyntax>));
}
public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(ParameterSyntax parameter, CSharpSyntaxNode body)
=> body is BlockSyntax block
? SimpleLambdaExpression(parameter, block, null)
: SimpleLambdaExpression(parameter, null, (ExpressionSyntax)body);
public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body)
=> body is BlockSyntax block
? SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, block, null)
: SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, null, (ExpressionSyntax)body);
public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(CSharpSyntaxNode body)
=> ParenthesizedLambdaExpression(ParameterList(), body);
public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(ParameterListSyntax parameterList, CSharpSyntaxNode body)
=> body is BlockSyntax block
? ParenthesizedLambdaExpression(parameterList, block, null)
: ParenthesizedLambdaExpression(parameterList, null, (ExpressionSyntax)body);
public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxToken asyncKeyword, ParameterListSyntax parameterList, SyntaxToken arrowToken, CSharpSyntaxNode body)
=> body is BlockSyntax block
? ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, block, null)
: ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, null, (ExpressionSyntax)body);
public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(CSharpSyntaxNode body)
=> AnonymousMethodExpression(parameterList: null, body);
public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(ParameterListSyntax? parameterList, CSharpSyntaxNode body)
=> body is BlockSyntax block
? AnonymousMethodExpression(default(SyntaxTokenList), SyntaxFactory.Token(SyntaxKind.DelegateKeyword), parameterList, block, null)
: throw new ArgumentException(nameof(body));
public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(SyntaxToken asyncKeyword, SyntaxToken delegateKeyword, ParameterListSyntax parameterList, CSharpSyntaxNode body)
=> body is BlockSyntax block
? AnonymousMethodExpression(asyncKeyword, delegateKeyword, parameterList, block, null)
: throw new ArgumentException(nameof(body));
// BACK COMPAT OVERLOAD DO NOT MODIFY
[Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static SyntaxTree ParseSyntaxTree(
string text,
ParseOptions? options,
string path,
Encoding? encoding,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
CancellationToken cancellationToken)
{
return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken);
}
// BACK COMPAT OVERLOAD DO NOT MODIFY
[Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static SyntaxTree ParseSyntaxTree(
SourceText text,
ParseOptions? options,
string path,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
CancellationToken cancellationToken)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken);
}
// BACK COMPAT OVERLOAD DO NOT MODIFY
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public static SyntaxTree ParseSyntaxTree(
string text,
ParseOptions? options,
string path,
Encoding? encoding,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
bool? isGeneratedCode,
CancellationToken cancellationToken)
{
return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode, cancellationToken);
}
// BACK COMPAT OVERLOAD DO NOT MODIFY
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public static SyntaxTree ParseSyntaxTree(
SourceText text,
ParseOptions? options,
string path,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
bool? isGeneratedCode,
CancellationToken cancellationToken)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, diagnosticOptions, isGeneratedCode, 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/Compilers/Core/Portable/FileSystem/FileUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.IO;
namespace Roslyn.Utilities
{
internal static class FileUtilities
{
/// <summary>
/// Resolves relative path and returns absolute path.
/// The method depends only on values of its parameters and their implementation (for fileExists).
/// It doesn't itself depend on the state of the current process (namely on the current drive directories) or
/// the state of file system.
/// </summary>
/// <param name="path">
/// Path to resolve.
/// </param>
/// <param name="basePath">
/// Base file path to resolve CWD-relative paths against. Null if not available.
/// </param>
/// <param name="baseDirectory">
/// Base directory to resolve CWD-relative paths against if <paramref name="basePath"/> isn't specified.
/// Must be absolute path.
/// Null if not available.
/// </param>
/// <param name="searchPaths">
/// Sequence of paths used to search for unqualified relative paths.
/// </param>
/// <param name="fileExists">
/// Method that tests existence of a file.
/// </param>
/// <returns>
/// The resolved path or null if the path can't be resolved or does not exist.
/// </returns>
internal static string? ResolveRelativePath(
string path,
string? basePath,
string? baseDirectory,
IEnumerable<string> searchPaths,
Func<string, bool> fileExists)
{
Debug.Assert(baseDirectory == null || searchPaths != null || PathUtilities.IsAbsolute(baseDirectory));
RoslynDebug.Assert(searchPaths != null);
RoslynDebug.Assert(fileExists != null);
string? combinedPath;
var kind = PathUtilities.GetPathKind(path);
if (kind == PathKind.Relative)
{
// first, look in the base directory:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory != null)
{
combinedPath = PathUtilities.CombinePathsUnchecked(baseDirectory, path);
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
// try search paths:
foreach (var searchPath in searchPaths)
{
combinedPath = PathUtilities.CombinePathsUnchecked(searchPath, path);
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
return null;
}
combinedPath = ResolveRelativePath(kind, path, basePath, baseDirectory);
if (combinedPath != null)
{
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
return null;
}
internal static string? ResolveRelativePath(string? path, string? baseDirectory)
{
return ResolveRelativePath(path, null, baseDirectory);
}
internal static string? ResolveRelativePath(string? path, string? basePath, string? baseDirectory)
{
Debug.Assert(baseDirectory == null || PathUtilities.IsAbsolute(baseDirectory));
return ResolveRelativePath(PathUtilities.GetPathKind(path), path, basePath, baseDirectory);
}
private static string? ResolveRelativePath(PathKind kind, string? path, string? basePath, string? baseDirectory)
{
Debug.Assert(PathUtilities.GetPathKind(path) == kind);
switch (kind)
{
case PathKind.Empty:
return null;
case PathKind.Relative:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
// with no search paths relative paths are relative to the base directory:
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
case PathKind.RelativeToCurrentDirectory:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
if (path!.Length == 1)
{
// "."
return baseDirectory;
}
else
{
// ".\path"
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
}
case PathKind.RelativeToCurrentParent:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
// ".."
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
case PathKind.RelativeToCurrentRoot:
string? baseRoot;
if (basePath != null)
{
baseRoot = PathUtilities.GetPathRoot(basePath);
}
else if (baseDirectory != null)
{
baseRoot = PathUtilities.GetPathRoot(baseDirectory);
}
else
{
return null;
}
if (RoslynString.IsNullOrEmpty(baseRoot))
{
return null;
}
Debug.Assert(PathUtilities.IsDirectorySeparator(path![0]));
Debug.Assert(path.Length == 1 || !PathUtilities.IsDirectorySeparator(path[1]));
return PathUtilities.CombinePathsUnchecked(baseRoot, path.Substring(1));
case PathKind.RelativeToDriveDirectory:
// drive relative paths not supported, can't resolve:
return null;
case PathKind.Absolute:
return path;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private static string? GetBaseDirectory(string? basePath, string? baseDirectory)
{
// relative base paths are relative to the base directory:
string? resolvedBasePath = ResolveRelativePath(basePath, baseDirectory);
if (resolvedBasePath == null)
{
return baseDirectory;
}
// Note: Path.GetDirectoryName doesn't normalize the path and so it doesn't depend on the process state.
Debug.Assert(PathUtilities.IsAbsolute(resolvedBasePath));
try
{
return Path.GetDirectoryName(resolvedBasePath);
}
catch (Exception)
{
return null;
}
}
private static readonly char[] s_invalidPathChars = Path.GetInvalidPathChars();
internal static string? NormalizeRelativePath(string path, string? basePath, string? baseDirectory)
{
// Does this look like a URI at all or does it have any invalid path characters? If so, just use it as is.
if (path.IndexOf("://", StringComparison.Ordinal) >= 0 || path.IndexOfAny(s_invalidPathChars) >= 0)
{
return null;
}
string? resolvedPath = ResolveRelativePath(path, basePath, baseDirectory);
if (resolvedPath == null)
{
return null;
}
string? normalizedPath = TryNormalizeAbsolutePath(resolvedPath);
if (normalizedPath == null)
{
return null;
}
return normalizedPath;
}
/// <summary>
/// Normalizes an absolute path.
/// </summary>
/// <param name="path">Path to normalize.</param>
/// <exception cref="IOException"/>
/// <returns>Normalized path.</returns>
internal static string NormalizeAbsolutePath(string path)
{
// we can only call GetFullPath on an absolute path to avoid dependency on process state (current directory):
Debug.Assert(PathUtilities.IsAbsolute(path));
try
{
return Path.GetFullPath(path);
}
catch (ArgumentException e)
{
throw new IOException(e.Message, e);
}
catch (System.Security.SecurityException e)
{
throw new IOException(e.Message, e);
}
catch (NotSupportedException e)
{
throw new IOException(e.Message, e);
}
}
internal static string NormalizeDirectoryPath(string path)
{
return NormalizeAbsolutePath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
internal static string? TryNormalizeAbsolutePath(string path)
{
Debug.Assert(PathUtilities.IsAbsolute(path));
try
{
return Path.GetFullPath(path);
}
catch
{
return null;
}
}
internal static Stream OpenRead(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
internal static Stream OpenAsyncRead(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
return RethrowExceptionsAsIOException(() => new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous));
}
internal static T RethrowExceptionsAsIOException<T>(Func<T> operation)
{
try
{
return operation();
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <summary>
/// Used to create a file given a path specified by the user.
/// paramName - Provided by the Public surface APIs to have a clearer message. Internal API just rethrow the exception
/// </summary>
internal static Stream CreateFileStreamChecked(Func<string, Stream> factory, string path, string? paramName = null)
{
try
{
return factory(path);
}
catch (ArgumentNullException)
{
if (paramName == null)
{
throw;
}
else
{
throw new ArgumentNullException(paramName);
}
}
catch (ArgumentException e)
{
if (paramName == null)
{
throw;
}
else
{
throw new ArgumentException(e.Message, paramName);
}
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <exception cref="IOException"/>
internal static DateTime GetFileTimeStamp(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
return File.GetLastWriteTimeUtc(fullPath);
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <exception cref="IOException"/>
internal static long GetFileLength(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
var info = new FileInfo(fullPath);
return info.Length;
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.IO;
namespace Roslyn.Utilities
{
internal static class FileUtilities
{
/// <summary>
/// Resolves relative path and returns absolute path.
/// The method depends only on values of its parameters and their implementation (for fileExists).
/// It doesn't itself depend on the state of the current process (namely on the current drive directories) or
/// the state of file system.
/// </summary>
/// <param name="path">
/// Path to resolve.
/// </param>
/// <param name="basePath">
/// Base file path to resolve CWD-relative paths against. Null if not available.
/// </param>
/// <param name="baseDirectory">
/// Base directory to resolve CWD-relative paths against if <paramref name="basePath"/> isn't specified.
/// Must be absolute path.
/// Null if not available.
/// </param>
/// <param name="searchPaths">
/// Sequence of paths used to search for unqualified relative paths.
/// </param>
/// <param name="fileExists">
/// Method that tests existence of a file.
/// </param>
/// <returns>
/// The resolved path or null if the path can't be resolved or does not exist.
/// </returns>
internal static string? ResolveRelativePath(
string path,
string? basePath,
string? baseDirectory,
IEnumerable<string> searchPaths,
Func<string, bool> fileExists)
{
Debug.Assert(baseDirectory == null || searchPaths != null || PathUtilities.IsAbsolute(baseDirectory));
RoslynDebug.Assert(searchPaths != null);
RoslynDebug.Assert(fileExists != null);
string? combinedPath;
var kind = PathUtilities.GetPathKind(path);
if (kind == PathKind.Relative)
{
// first, look in the base directory:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory != null)
{
combinedPath = PathUtilities.CombinePathsUnchecked(baseDirectory, path);
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
// try search paths:
foreach (var searchPath in searchPaths)
{
combinedPath = PathUtilities.CombinePathsUnchecked(searchPath, path);
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
return null;
}
combinedPath = ResolveRelativePath(kind, path, basePath, baseDirectory);
if (combinedPath != null)
{
Debug.Assert(PathUtilities.IsAbsolute(combinedPath));
if (fileExists(combinedPath))
{
return combinedPath;
}
}
return null;
}
internal static string? ResolveRelativePath(string? path, string? baseDirectory)
{
return ResolveRelativePath(path, null, baseDirectory);
}
internal static string? ResolveRelativePath(string? path, string? basePath, string? baseDirectory)
{
Debug.Assert(baseDirectory == null || PathUtilities.IsAbsolute(baseDirectory));
return ResolveRelativePath(PathUtilities.GetPathKind(path), path, basePath, baseDirectory);
}
private static string? ResolveRelativePath(PathKind kind, string? path, string? basePath, string? baseDirectory)
{
Debug.Assert(PathUtilities.GetPathKind(path) == kind);
switch (kind)
{
case PathKind.Empty:
return null;
case PathKind.Relative:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
// with no search paths relative paths are relative to the base directory:
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
case PathKind.RelativeToCurrentDirectory:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
if (path!.Length == 1)
{
// "."
return baseDirectory;
}
else
{
// ".\path"
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
}
case PathKind.RelativeToCurrentParent:
baseDirectory = GetBaseDirectory(basePath, baseDirectory);
if (baseDirectory == null)
{
return null;
}
// ".."
return PathUtilities.CombinePathsUnchecked(baseDirectory, path);
case PathKind.RelativeToCurrentRoot:
string? baseRoot;
if (basePath != null)
{
baseRoot = PathUtilities.GetPathRoot(basePath);
}
else if (baseDirectory != null)
{
baseRoot = PathUtilities.GetPathRoot(baseDirectory);
}
else
{
return null;
}
if (RoslynString.IsNullOrEmpty(baseRoot))
{
return null;
}
Debug.Assert(PathUtilities.IsDirectorySeparator(path![0]));
Debug.Assert(path.Length == 1 || !PathUtilities.IsDirectorySeparator(path[1]));
return PathUtilities.CombinePathsUnchecked(baseRoot, path.Substring(1));
case PathKind.RelativeToDriveDirectory:
// drive relative paths not supported, can't resolve:
return null;
case PathKind.Absolute:
return path;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private static string? GetBaseDirectory(string? basePath, string? baseDirectory)
{
// relative base paths are relative to the base directory:
string? resolvedBasePath = ResolveRelativePath(basePath, baseDirectory);
if (resolvedBasePath == null)
{
return baseDirectory;
}
// Note: Path.GetDirectoryName doesn't normalize the path and so it doesn't depend on the process state.
Debug.Assert(PathUtilities.IsAbsolute(resolvedBasePath));
try
{
return Path.GetDirectoryName(resolvedBasePath);
}
catch (Exception)
{
return null;
}
}
private static readonly char[] s_invalidPathChars = Path.GetInvalidPathChars();
internal static string? NormalizeRelativePath(string path, string? basePath, string? baseDirectory)
{
// Does this look like a URI at all or does it have any invalid path characters? If so, just use it as is.
if (path.IndexOf("://", StringComparison.Ordinal) >= 0 || path.IndexOfAny(s_invalidPathChars) >= 0)
{
return null;
}
string? resolvedPath = ResolveRelativePath(path, basePath, baseDirectory);
if (resolvedPath == null)
{
return null;
}
string? normalizedPath = TryNormalizeAbsolutePath(resolvedPath);
if (normalizedPath == null)
{
return null;
}
return normalizedPath;
}
/// <summary>
/// Normalizes an absolute path.
/// </summary>
/// <param name="path">Path to normalize.</param>
/// <exception cref="IOException"/>
/// <returns>Normalized path.</returns>
internal static string NormalizeAbsolutePath(string path)
{
// we can only call GetFullPath on an absolute path to avoid dependency on process state (current directory):
Debug.Assert(PathUtilities.IsAbsolute(path));
try
{
return Path.GetFullPath(path);
}
catch (ArgumentException e)
{
throw new IOException(e.Message, e);
}
catch (System.Security.SecurityException e)
{
throw new IOException(e.Message, e);
}
catch (NotSupportedException e)
{
throw new IOException(e.Message, e);
}
}
internal static string NormalizeDirectoryPath(string path)
{
return NormalizeAbsolutePath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
internal static string? TryNormalizeAbsolutePath(string path)
{
Debug.Assert(PathUtilities.IsAbsolute(path));
try
{
return Path.GetFullPath(path);
}
catch
{
return null;
}
}
internal static Stream OpenRead(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
internal static Stream OpenAsyncRead(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
return RethrowExceptionsAsIOException(() => new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous));
}
internal static T RethrowExceptionsAsIOException<T>(Func<T> operation)
{
try
{
return operation();
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <summary>
/// Used to create a file given a path specified by the user.
/// paramName - Provided by the Public surface APIs to have a clearer message. Internal API just rethrow the exception
/// </summary>
internal static Stream CreateFileStreamChecked(Func<string, Stream> factory, string path, string? paramName = null)
{
try
{
return factory(path);
}
catch (ArgumentNullException)
{
if (paramName == null)
{
throw;
}
else
{
throw new ArgumentNullException(paramName);
}
}
catch (ArgumentException e)
{
if (paramName == null)
{
throw;
}
else
{
throw new ArgumentException(e.Message, paramName);
}
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <exception cref="IOException"/>
internal static DateTime GetFileTimeStamp(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
return File.GetLastWriteTimeUtc(fullPath);
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
/// <exception cref="IOException"/>
internal static long GetFileLength(string fullPath)
{
Debug.Assert(PathUtilities.IsAbsolute(fullPath));
try
{
var info = new FileInfo(fullPath);
return info.Length;
}
catch (IOException)
{
throw;
}
catch (Exception e)
{
throw new IOException(e.Message, e);
}
}
}
}
| -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/Extensions/SyntaxTriviaListExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class SyntaxTriviaListExtensions
{
public static bool Any(this SyntaxTriviaList triviaList, params SyntaxKind[] kinds)
{
foreach (var trivia in triviaList)
{
if (trivia.MatchesKind(kinds))
{
return true;
}
}
return false;
}
public static SyntaxTrivia? GetFirstNewLine(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.Kind() == SyntaxKind.EndOfLineTrivia)
.FirstOrNull();
}
public static SyntaxTrivia? GetLastComment(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.IsRegularComment())
.LastOrNull();
}
public static SyntaxTrivia? GetLastCommentOrWhitespace(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.MatchesKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia, SyntaxKind.WhitespaceTrivia))
.LastOrNull();
}
public static IEnumerable<SyntaxTrivia> SkipInitialWhitespace(this SyntaxTriviaList triviaList)
=> triviaList.SkipWhile(t => t.Kind() == SyntaxKind.WhitespaceTrivia);
private static ImmutableArray<ImmutableArray<SyntaxTrivia>> GetLeadingBlankLines(SyntaxTriviaList triviaList)
{
using var result = TemporaryArray<ImmutableArray<SyntaxTrivia>>.Empty;
using var currentLine = TemporaryArray<SyntaxTrivia>.Empty;
foreach (var trivia in triviaList)
{
currentLine.Add(trivia);
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
var currentLineIsBlank = currentLine.All(static t =>
t.Kind() == SyntaxKind.EndOfLineTrivia ||
t.Kind() == SyntaxKind.WhitespaceTrivia);
if (!currentLineIsBlank)
{
break;
}
result.Add(currentLine.ToImmutableAndClear());
}
}
return result.ToImmutableAndClear();
}
public static SyntaxTriviaList WithoutLeadingBlankLines(this SyntaxTriviaList triviaList)
{
var triviaInLeadingBlankLines = GetLeadingBlankLines(triviaList).SelectMany(l => l);
return new SyntaxTriviaList(triviaList.Skip(triviaInLeadingBlankLines.Count()));
}
/// <summary>
/// Takes an INCLUSIVE range of trivia from the trivia list.
/// </summary>
public static IEnumerable<SyntaxTrivia> TakeRange(this SyntaxTriviaList triviaList, int start, int end)
{
while (start <= end)
{
yield return triviaList[start++];
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class SyntaxTriviaListExtensions
{
public static bool Any(this SyntaxTriviaList triviaList, params SyntaxKind[] kinds)
{
foreach (var trivia in triviaList)
{
if (trivia.MatchesKind(kinds))
{
return true;
}
}
return false;
}
public static SyntaxTrivia? GetFirstNewLine(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.Kind() == SyntaxKind.EndOfLineTrivia)
.FirstOrNull();
}
public static SyntaxTrivia? GetLastComment(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.IsRegularComment())
.LastOrNull();
}
public static SyntaxTrivia? GetLastCommentOrWhitespace(this SyntaxTriviaList triviaList)
{
return triviaList
.Where(t => t.MatchesKind(SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia, SyntaxKind.WhitespaceTrivia))
.LastOrNull();
}
public static IEnumerable<SyntaxTrivia> SkipInitialWhitespace(this SyntaxTriviaList triviaList)
=> triviaList.SkipWhile(t => t.Kind() == SyntaxKind.WhitespaceTrivia);
private static ImmutableArray<ImmutableArray<SyntaxTrivia>> GetLeadingBlankLines(SyntaxTriviaList triviaList)
{
using var result = TemporaryArray<ImmutableArray<SyntaxTrivia>>.Empty;
using var currentLine = TemporaryArray<SyntaxTrivia>.Empty;
foreach (var trivia in triviaList)
{
currentLine.Add(trivia);
if (trivia.Kind() == SyntaxKind.EndOfLineTrivia)
{
var currentLineIsBlank = currentLine.All(static t =>
t.Kind() == SyntaxKind.EndOfLineTrivia ||
t.Kind() == SyntaxKind.WhitespaceTrivia);
if (!currentLineIsBlank)
{
break;
}
result.Add(currentLine.ToImmutableAndClear());
}
}
return result.ToImmutableAndClear();
}
public static SyntaxTriviaList WithoutLeadingBlankLines(this SyntaxTriviaList triviaList)
{
var triviaInLeadingBlankLines = GetLeadingBlankLines(triviaList).SelectMany(l => l);
return new SyntaxTriviaList(triviaList.Skip(triviaInLeadingBlankLines.Count()));
}
/// <summary>
/// Takes an INCLUSIVE range of trivia from the trivia list.
/// </summary>
public static IEnumerable<SyntaxTrivia> TakeRange(this SyntaxTriviaList triviaList, int start, int end)
{
while (start <= end)
{
yield return triviaList[start++];
}
}
}
}
| -1 |
dotnet/roslyn | 55,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/CSharp/SplitComment/CSharpSplitCommentService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.Implementation.SplitComment;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.CSharp.SplitComment
{
[ExportLanguageService(typeof(ISplitCommentService), LanguageNames.CSharp), Shared]
internal class CSharpSplitCommentService : ISplitCommentService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpSplitCommentService()
{
}
public string CommentStart => "//";
public bool IsAllowed(SyntaxNode root, SyntaxTrivia trivia)
=> true;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.Implementation.SplitComment;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.CSharp.SplitComment
{
[ExportLanguageService(typeof(ISplitCommentService), LanguageNames.CSharp), Shared]
internal class CSharpSplitCommentService : ISplitCommentService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpSplitCommentService()
{
}
public string CommentStart => "//";
public bool IsAllowed(SyntaxNode root, SyntaxTrivia trivia)
=> 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/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Serialization.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class SymbolTreeInfo : IObjectWritable
{
private const string PrefixMetadataSymbolTreeInfo = "<SymbolTreeInfo>";
private static readonly Checksum SerializationFormatChecksum = Checksum.Create("22");
/// <summary>
/// Loads the SpellChecker for a given assembly symbol (metadata or project). If the
/// info can't be loaded, it will be created (and persisted if possible).
/// </summary>
private static Task<SpellChecker> LoadOrCreateSpellCheckerAsync(
Workspace workspace,
SolutionKey solutionKey,
Checksum checksum,
string filePath,
ImmutableArray<Node> sortedNodes)
{
var result = TryLoadOrCreateAsync(
workspace,
solutionKey,
checksum,
loadOnly: false,
createAsync: () => CreateSpellCheckerAsync(checksum, sortedNodes),
keySuffix: "_SpellChecker_" + filePath,
tryReadObject: SpellChecker.TryReadFrom,
cancellationToken: CancellationToken.None);
Contract.ThrowIfNull(result, "Result should never be null as we passed 'loadOnly: false'.");
return result;
}
/// <summary>
/// Generalized function for loading/creating/persisting data. Used as the common core
/// code for serialization of SymbolTreeInfos and SpellCheckers.
/// </summary>
private static async Task<T> TryLoadOrCreateAsync<T>(
Workspace workspace,
SolutionKey solutionKey,
Checksum checksum,
bool loadOnly,
Func<Task<T>> createAsync,
string keySuffix,
Func<ObjectReader, T> tryReadObject,
CancellationToken cancellationToken) where T : class, IObjectWritable, IChecksummedObject
{
using (Logger.LogBlock(FunctionId.SymbolTreeInfo_TryLoadOrCreate, cancellationToken))
{
if (checksum == null)
{
return loadOnly ? null : await CreateWithLoggingAsync().ConfigureAwait(false);
}
// Ok, we can use persistence. First try to load from the persistence service.
var persistentStorageService = (IChecksummedPersistentStorageService)workspace.Services.GetService<IPersistentStorageService>();
var storage = await persistentStorageService.GetStorageAsync(
workspace, solutionKey, checkBranchId: false, cancellationToken).ConfigureAwait(false);
await using var _ = storage.ConfigureAwait(false);
// Get the unique key to identify our data.
var key = PrefixMetadataSymbolTreeInfo + keySuffix;
using (var stream = await storage.ReadStreamAsync(key, checksum, cancellationToken).ConfigureAwait(false))
using (var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken))
{
if (reader != null)
{
// We have some previously persisted data. Attempt to read it back.
// If we're able to, and the version of the persisted data matches
// our version, then we can reuse this instance.
var read = tryReadObject(reader);
if (read != null)
{
// If we were able to read something in, it's checksum better
// have matched the checksum we expected.
Debug.Assert(read.Checksum == checksum);
return read;
}
}
}
cancellationToken.ThrowIfCancellationRequested();
// Couldn't read from the persistence service. If we've been asked to only load
// data and not create new instances in their absence, then there's nothing left
// to do at this point.
if (loadOnly)
{
return null;
}
// Now, try to create a new instance and write it to the persistence service.
var result = await CreateWithLoggingAsync().ConfigureAwait(false);
Contract.ThrowIfNull(result);
using (var stream = SerializableBytes.CreateWritableStream())
{
using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken))
{
result.WriteTo(writer);
}
stream.Position = 0;
await storage.WriteStreamAsync(key, stream, checksum, cancellationToken).ConfigureAwait(false);
}
return result;
}
async Task<T> CreateWithLoggingAsync()
{
using (Logger.LogBlock(FunctionId.SymbolTreeInfo_Create, cancellationToken))
{
return await createAsync().ConfigureAwait(false);
}
}
}
bool IObjectWritable.ShouldReuseInSerialization => true;
public void WriteTo(ObjectWriter writer)
{
writer.WriteInt32(_nodes.Length);
foreach (var group in GroupByName(_nodes.AsMemory()))
{
writer.WriteString(group.Span[0].Name);
writer.WriteInt32(group.Length);
foreach (var item in group.Span)
{
writer.WriteInt32(item.ParentIndex);
}
}
writer.WriteInt32(_inheritanceMap.Keys.Count);
foreach (var kvp in _inheritanceMap)
{
writer.WriteInt32(kvp.Key);
writer.WriteInt32(kvp.Value.Count);
foreach (var v in kvp.Value)
{
writer.WriteInt32(v);
}
}
if (_receiverTypeNameToExtensionMethodMap == null)
{
writer.WriteInt32(0);
}
else
{
writer.WriteInt32(_receiverTypeNameToExtensionMethodMap.Count);
foreach (var key in _receiverTypeNameToExtensionMethodMap.Keys)
{
writer.WriteString(key);
var values = _receiverTypeNameToExtensionMethodMap[key];
writer.WriteInt32(values.Count);
foreach (var value in values)
{
writer.WriteString(value.FullyQualifiedContainerName);
writer.WriteString(value.Name);
}
}
}
// sortedNodes is an array of Node instances which is often sorted by Node.Name by the caller. This method
// produces a sequence of spans within sortedNodes for Node instances that all have the same Name, allowing
// serialization to record the string once followed by the remaining properties for the nodes in the group.
static IEnumerable<ReadOnlyMemory<Node>> GroupByName(ReadOnlyMemory<Node> sortedNodes)
{
if (sortedNodes.IsEmpty)
yield break;
var startIndex = 0;
var currentName = sortedNodes.Span[0].Name;
for (var i = 1; i < sortedNodes.Length; i++)
{
var node = sortedNodes.Span[i];
if (node.Name != currentName)
{
yield return sortedNodes[startIndex..i];
startIndex = i;
}
}
yield return sortedNodes[startIndex..sortedNodes.Length];
}
}
private static SymbolTreeInfo TryReadSymbolTreeInfo(
ObjectReader reader,
Checksum checksum,
Func<ImmutableArray<Node>, Task<SpellChecker>> createSpellCheckerTask)
{
try
{
var nodeCount = reader.ReadInt32();
var nodes = ArrayBuilder<Node>.GetInstance(nodeCount);
while (nodes.Count < nodeCount)
{
var name = reader.ReadString();
var groupCount = reader.ReadInt32();
for (var i = 0; i < groupCount; i++)
{
var parentIndex = reader.ReadInt32();
nodes.Add(new Node(name, parentIndex));
}
}
var inheritanceMap = new OrderPreservingMultiDictionary<int, int>();
var inheritanceMapKeyCount = reader.ReadInt32();
for (var i = 0; i < inheritanceMapKeyCount; i++)
{
var key = reader.ReadInt32();
var valueCount = reader.ReadInt32();
for (var j = 0; j < valueCount; j++)
{
var value = reader.ReadInt32();
inheritanceMap.Add(key, value);
}
}
MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToExtensionMethodMap;
var keyCount = reader.ReadInt32();
if (keyCount == 0)
{
receiverTypeNameToExtensionMethodMap = null;
}
else
{
receiverTypeNameToExtensionMethodMap = new MultiDictionary<string, ExtensionMethodInfo>();
for (var i = 0; i < keyCount; i++)
{
var typeName = reader.ReadString();
var valueCount = reader.ReadInt32();
for (var j = 0; j < valueCount; j++)
{
var containerName = reader.ReadString();
var name = reader.ReadString();
receiverTypeNameToExtensionMethodMap.Add(typeName, new ExtensionMethodInfo(containerName, name));
}
}
}
var nodeArray = nodes.ToImmutableAndFree();
var spellCheckerTask = createSpellCheckerTask(nodeArray);
return new SymbolTreeInfo(
checksum, nodeArray, spellCheckerTask, inheritanceMap,
receiverTypeNameToExtensionMethodMap);
}
catch
{
Logger.Log(FunctionId.SymbolTreeInfo_ExceptionInCacheRead);
}
return null;
}
internal readonly partial struct TestAccessor
{
internal static SymbolTreeInfo ReadSymbolTreeInfo(
ObjectReader reader, Checksum checksum)
{
return TryReadSymbolTreeInfo(reader, checksum,
nodes => Task.FromResult(new SpellChecker(checksum, nodes.Select(n => n.Name.AsMemory()))));
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PersistentStorage;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class SymbolTreeInfo : IObjectWritable
{
private const string PrefixMetadataSymbolTreeInfo = "<SymbolTreeInfo>";
private static readonly Checksum SerializationFormatChecksum = Checksum.Create("22");
/// <summary>
/// Loads the SpellChecker for a given assembly symbol (metadata or project). If the
/// info can't be loaded, it will be created (and persisted if possible).
/// </summary>
private static Task<SpellChecker> LoadOrCreateSpellCheckerAsync(
Workspace workspace,
SolutionKey solutionKey,
Checksum checksum,
string filePath,
ImmutableArray<Node> sortedNodes)
{
var result = TryLoadOrCreateAsync(
workspace,
solutionKey,
checksum,
loadOnly: false,
createAsync: () => CreateSpellCheckerAsync(checksum, sortedNodes),
keySuffix: "_SpellChecker_" + filePath,
tryReadObject: SpellChecker.TryReadFrom,
cancellationToken: CancellationToken.None);
Contract.ThrowIfNull(result, "Result should never be null as we passed 'loadOnly: false'.");
return result;
}
/// <summary>
/// Generalized function for loading/creating/persisting data. Used as the common core
/// code for serialization of SymbolTreeInfos and SpellCheckers.
/// </summary>
private static async Task<T> TryLoadOrCreateAsync<T>(
Workspace workspace,
SolutionKey solutionKey,
Checksum checksum,
bool loadOnly,
Func<Task<T>> createAsync,
string keySuffix,
Func<ObjectReader, T> tryReadObject,
CancellationToken cancellationToken) where T : class, IObjectWritable, IChecksummedObject
{
using (Logger.LogBlock(FunctionId.SymbolTreeInfo_TryLoadOrCreate, cancellationToken))
{
if (checksum == null)
{
return loadOnly ? null : await CreateWithLoggingAsync().ConfigureAwait(false);
}
// Ok, we can use persistence. First try to load from the persistence service.
var persistentStorageService = (IChecksummedPersistentStorageService)workspace.Services.GetService<IPersistentStorageService>();
var storage = await persistentStorageService.GetStorageAsync(
workspace, solutionKey, checkBranchId: false, cancellationToken).ConfigureAwait(false);
await using var _ = storage.ConfigureAwait(false);
// Get the unique key to identify our data.
var key = PrefixMetadataSymbolTreeInfo + keySuffix;
using (var stream = await storage.ReadStreamAsync(key, checksum, cancellationToken).ConfigureAwait(false))
using (var reader = ObjectReader.TryGetReader(stream, cancellationToken: cancellationToken))
{
if (reader != null)
{
// We have some previously persisted data. Attempt to read it back.
// If we're able to, and the version of the persisted data matches
// our version, then we can reuse this instance.
var read = tryReadObject(reader);
if (read != null)
{
// If we were able to read something in, it's checksum better
// have matched the checksum we expected.
Debug.Assert(read.Checksum == checksum);
return read;
}
}
}
cancellationToken.ThrowIfCancellationRequested();
// Couldn't read from the persistence service. If we've been asked to only load
// data and not create new instances in their absence, then there's nothing left
// to do at this point.
if (loadOnly)
{
return null;
}
// Now, try to create a new instance and write it to the persistence service.
var result = await CreateWithLoggingAsync().ConfigureAwait(false);
Contract.ThrowIfNull(result);
using (var stream = SerializableBytes.CreateWritableStream())
{
using (var writer = new ObjectWriter(stream, leaveOpen: true, cancellationToken))
{
result.WriteTo(writer);
}
stream.Position = 0;
await storage.WriteStreamAsync(key, stream, checksum, cancellationToken).ConfigureAwait(false);
}
return result;
}
async Task<T> CreateWithLoggingAsync()
{
using (Logger.LogBlock(FunctionId.SymbolTreeInfo_Create, cancellationToken))
{
return await createAsync().ConfigureAwait(false);
}
}
}
bool IObjectWritable.ShouldReuseInSerialization => true;
public void WriteTo(ObjectWriter writer)
{
writer.WriteInt32(_nodes.Length);
foreach (var group in GroupByName(_nodes.AsMemory()))
{
writer.WriteString(group.Span[0].Name);
writer.WriteInt32(group.Length);
foreach (var item in group.Span)
{
writer.WriteInt32(item.ParentIndex);
}
}
writer.WriteInt32(_inheritanceMap.Keys.Count);
foreach (var kvp in _inheritanceMap)
{
writer.WriteInt32(kvp.Key);
writer.WriteInt32(kvp.Value.Count);
foreach (var v in kvp.Value)
{
writer.WriteInt32(v);
}
}
if (_receiverTypeNameToExtensionMethodMap == null)
{
writer.WriteInt32(0);
}
else
{
writer.WriteInt32(_receiverTypeNameToExtensionMethodMap.Count);
foreach (var key in _receiverTypeNameToExtensionMethodMap.Keys)
{
writer.WriteString(key);
var values = _receiverTypeNameToExtensionMethodMap[key];
writer.WriteInt32(values.Count);
foreach (var value in values)
{
writer.WriteString(value.FullyQualifiedContainerName);
writer.WriteString(value.Name);
}
}
}
// sortedNodes is an array of Node instances which is often sorted by Node.Name by the caller. This method
// produces a sequence of spans within sortedNodes for Node instances that all have the same Name, allowing
// serialization to record the string once followed by the remaining properties for the nodes in the group.
static IEnumerable<ReadOnlyMemory<Node>> GroupByName(ReadOnlyMemory<Node> sortedNodes)
{
if (sortedNodes.IsEmpty)
yield break;
var startIndex = 0;
var currentName = sortedNodes.Span[0].Name;
for (var i = 1; i < sortedNodes.Length; i++)
{
var node = sortedNodes.Span[i];
if (node.Name != currentName)
{
yield return sortedNodes[startIndex..i];
startIndex = i;
}
}
yield return sortedNodes[startIndex..sortedNodes.Length];
}
}
private static SymbolTreeInfo TryReadSymbolTreeInfo(
ObjectReader reader,
Checksum checksum,
Func<ImmutableArray<Node>, Task<SpellChecker>> createSpellCheckerTask)
{
try
{
var nodeCount = reader.ReadInt32();
var nodes = ArrayBuilder<Node>.GetInstance(nodeCount);
while (nodes.Count < nodeCount)
{
var name = reader.ReadString();
var groupCount = reader.ReadInt32();
for (var i = 0; i < groupCount; i++)
{
var parentIndex = reader.ReadInt32();
nodes.Add(new Node(name, parentIndex));
}
}
var inheritanceMap = new OrderPreservingMultiDictionary<int, int>();
var inheritanceMapKeyCount = reader.ReadInt32();
for (var i = 0; i < inheritanceMapKeyCount; i++)
{
var key = reader.ReadInt32();
var valueCount = reader.ReadInt32();
for (var j = 0; j < valueCount; j++)
{
var value = reader.ReadInt32();
inheritanceMap.Add(key, value);
}
}
MultiDictionary<string, ExtensionMethodInfo> receiverTypeNameToExtensionMethodMap;
var keyCount = reader.ReadInt32();
if (keyCount == 0)
{
receiverTypeNameToExtensionMethodMap = null;
}
else
{
receiverTypeNameToExtensionMethodMap = new MultiDictionary<string, ExtensionMethodInfo>();
for (var i = 0; i < keyCount; i++)
{
var typeName = reader.ReadString();
var valueCount = reader.ReadInt32();
for (var j = 0; j < valueCount; j++)
{
var containerName = reader.ReadString();
var name = reader.ReadString();
receiverTypeNameToExtensionMethodMap.Add(typeName, new ExtensionMethodInfo(containerName, name));
}
}
}
var nodeArray = nodes.ToImmutableAndFree();
var spellCheckerTask = createSpellCheckerTask(nodeArray);
return new SymbolTreeInfo(
checksum, nodeArray, spellCheckerTask, inheritanceMap,
receiverTypeNameToExtensionMethodMap);
}
catch
{
Logger.Log(FunctionId.SymbolTreeInfo_ExceptionInCacheRead);
}
return null;
}
internal readonly partial struct TestAccessor
{
internal static SymbolTreeInfo ReadSymbolTreeInfo(
ObjectReader reader, Checksum checksum)
{
return TryReadSymbolTreeInfo(reader, checksum,
nodes => Task.FromResult(new SpellChecker(checksum, nodes.Select(n => n.Name.AsMemory()))));
}
}
}
}
| -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/Core/Formatting/Engine/TreeData.StructuredTrivia.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract partial class TreeData
{
private class StructuredTrivia : TreeData
{
private readonly int _initialColumn;
private readonly SyntaxTrivia _trivia;
private readonly TreeData _treeData;
public StructuredTrivia(SyntaxTrivia trivia, int initialColumn)
: base(trivia.GetStructure()!)
{
Contract.ThrowIfFalse(trivia.HasStructure);
_trivia = trivia;
var root = trivia.GetStructure()!;
var text = GetText();
_initialColumn = initialColumn;
_treeData = (text == null) ? (TreeData)new Node(root) : new NodeAndText(root, text);
}
public override string GetTextBetween(SyntaxToken token1, SyntaxToken token2)
=> _treeData.GetTextBetween(token1, token2);
public override int GetOriginalColumn(int tabSize, SyntaxToken token)
{
if (_treeData is NodeAndText)
{
return _treeData.GetOriginalColumn(tabSize, token);
}
var text = _trivia.ToFullString().Substring(0, token.SpanStart - _trivia.FullSpan.Start);
return text.GetTextColumn(tabSize, _initialColumn);
}
private SourceText? GetText()
{
var root = _trivia.GetStructure()!;
if (root.SyntaxTree != null && root.SyntaxTree.GetText() != null)
{
return root.SyntaxTree.GetText();
}
var parent = _trivia.Token.Parent;
if (parent != null && parent.SyntaxTree != null && parent.SyntaxTree.GetText() != null)
{
return parent.SyntaxTree.GetText();
}
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 Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
internal abstract partial class TreeData
{
private class StructuredTrivia : TreeData
{
private readonly int _initialColumn;
private readonly SyntaxTrivia _trivia;
private readonly TreeData _treeData;
public StructuredTrivia(SyntaxTrivia trivia, int initialColumn)
: base(trivia.GetStructure()!)
{
Contract.ThrowIfFalse(trivia.HasStructure);
_trivia = trivia;
var root = trivia.GetStructure()!;
var text = GetText();
_initialColumn = initialColumn;
_treeData = (text == null) ? (TreeData)new Node(root) : new NodeAndText(root, text);
}
public override string GetTextBetween(SyntaxToken token1, SyntaxToken token2)
=> _treeData.GetTextBetween(token1, token2);
public override int GetOriginalColumn(int tabSize, SyntaxToken token)
{
if (_treeData is NodeAndText)
{
return _treeData.GetOriginalColumn(tabSize, token);
}
var text = _trivia.ToFullString().Substring(0, token.SpanStart - _trivia.FullSpan.Start);
return text.GetTextColumn(tabSize, _initialColumn);
}
private SourceText? GetText()
{
var root = _trivia.GetStructure()!;
if (root.SyntaxTree != null && root.SyntaxTree.GetText() != null)
{
return root.SyntaxTree.GetText();
}
var parent = _trivia.Token.Parent;
if (parent != null && parent.SyntaxTree != null && parent.SyntaxTree.GetText() != null)
{
return parent.SyntaxTree.GetText();
}
return null;
}
}
}
}
| -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/MetadataAsSource/IMetadataAsSourceFileService.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.MetadataAsSource
{
internal interface IMetadataAsSourceFileService
{
/// <summary>
/// Generates a file on disk containing general information about the symbol's containing
/// assembly, and the formatted source code for the public, protected, and
/// protected-or-internal interface of which the given ISymbol is or is a part of.
/// </summary>
/// <param name="project">The project from which the symbol to generate source for came
/// from.</param>
/// <param name="symbol">The symbol whose interface to generate source for</param>
/// <param name="allowDecompilation"><see langword="true"/> to allow a decompiler or other technology to show a
/// representation of the original sources; otherwise <see langword="false"/> to only show member
/// signatures.</param>
/// <param name="cancellationToken">To cancel project and document operations</param>
Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, bool allowDecompilation, CancellationToken cancellationToken = default);
bool TryAddDocumentToWorkspace(string filePath, SourceTextContainer buffer);
bool TryRemoveDocumentFromWorkspace(string filePath);
void CleanupGeneratedFiles();
bool IsNavigableMetadataSymbol(ISymbol symbol);
Workspace? TryGetWorkspace();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.MetadataAsSource
{
internal interface IMetadataAsSourceFileService
{
/// <summary>
/// Generates a file on disk containing general information about the symbol's containing
/// assembly, and the formatted source code for the public, protected, and
/// protected-or-internal interface of which the given ISymbol is or is a part of.
/// </summary>
/// <param name="project">The project from which the symbol to generate source for came
/// from.</param>
/// <param name="symbol">The symbol whose interface to generate source for</param>
/// <param name="allowDecompilation"><see langword="true"/> to allow a decompiler or other technology to show a
/// representation of the original sources; otherwise <see langword="false"/> to only show member
/// signatures.</param>
/// <param name="cancellationToken">To cancel project and document operations</param>
Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, bool allowDecompilation, CancellationToken cancellationToken = default);
bool TryAddDocumentToWorkspace(string filePath, SourceTextContainer buffer);
bool TryRemoveDocumentFromWorkspace(string filePath);
void CleanupGeneratedFiles();
bool IsNavigableMetadataSymbol(ISymbol symbol);
Workspace? TryGetWorkspace();
}
}
| -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/Test/Core/Mocks/TestSourceReferenceResolver.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.CodeAnalysis;
namespace Roslyn.Test.Utilities
{
public sealed class TestSourceReferenceResolver : SourceReferenceResolver
{
public static readonly SourceReferenceResolver Default = new TestSourceReferenceResolver(sources: null);
public static SourceReferenceResolver Create(params KeyValuePair<string, string>[] sources)
{
return new TestSourceReferenceResolver(sources.ToDictionary(p => p.Key, p => (object)p.Value));
}
public static SourceReferenceResolver Create(params KeyValuePair<string, object>[] sources)
{
return new TestSourceReferenceResolver(sources.ToDictionary(p => p.Key, p => p.Value));
}
public static SourceReferenceResolver Create(Dictionary<string, string> sources = null)
{
return new TestSourceReferenceResolver(sources.ToDictionary(p => p.Key, p => (object)p.Value));
}
private readonly Dictionary<string, object> _sources;
private TestSourceReferenceResolver(Dictionary<string, object> sources)
{
_sources = sources;
}
public override string NormalizePath(string path, string baseFilePath) => path;
public override string ResolveReference(string path, string baseFilePath) =>
_sources?.ContainsKey(path) == true ? path : null;
public override Stream OpenRead(string resolvedPath)
{
if (_sources != null && resolvedPath != null)
{
var data = _sources[resolvedPath];
return new MemoryStream((data is string) ? Encoding.UTF8.GetBytes((string)data) : (byte[])data);
}
else
{
throw new IOException();
}
}
public override bool Equals(object other) => ReferenceEquals(this, other);
public override int GetHashCode() => RuntimeHelpers.GetHashCode(this);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.CodeAnalysis;
namespace Roslyn.Test.Utilities
{
public sealed class TestSourceReferenceResolver : SourceReferenceResolver
{
public static readonly SourceReferenceResolver Default = new TestSourceReferenceResolver(sources: null);
public static SourceReferenceResolver Create(params KeyValuePair<string, string>[] sources)
{
return new TestSourceReferenceResolver(sources.ToDictionary(p => p.Key, p => (object)p.Value));
}
public static SourceReferenceResolver Create(params KeyValuePair<string, object>[] sources)
{
return new TestSourceReferenceResolver(sources.ToDictionary(p => p.Key, p => p.Value));
}
public static SourceReferenceResolver Create(Dictionary<string, string> sources = null)
{
return new TestSourceReferenceResolver(sources.ToDictionary(p => p.Key, p => (object)p.Value));
}
private readonly Dictionary<string, object> _sources;
private TestSourceReferenceResolver(Dictionary<string, object> sources)
{
_sources = sources;
}
public override string NormalizePath(string path, string baseFilePath) => path;
public override string ResolveReference(string path, string baseFilePath) =>
_sources?.ContainsKey(path) == true ? path : null;
public override Stream OpenRead(string resolvedPath)
{
if (_sources != null && resolvedPath != null)
{
var data = _sources[resolvedPath];
return new MemoryStream((data is string) ? Encoding.UTF8.GetBytes((string)data) : (byte[])data);
}
else
{
throw new IOException();
}
}
public override bool Equals(object other) => ReferenceEquals(this, other);
public override int GetHashCode() => RuntimeHelpers.GetHashCode(this);
}
}
| -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/Core/Def/ExternalAccess/VSTypeScript/Api/VSTypeScriptVisualStudioProjectWrapper.LSPContainedDocumentServiceProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Host;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
internal sealed partial class VSTypeScriptVisualStudioProjectWrapper
{
private sealed class LspContainedDocumentServiceProvider : IDocumentServiceProvider, IDocumentOperationService
{
private readonly VirtualDocumentPropertiesService _documentPropertiesService;
private LspContainedDocumentServiceProvider()
{
_documentPropertiesService = VirtualDocumentPropertiesService.Instance;
}
public static LspContainedDocumentServiceProvider Instance = new LspContainedDocumentServiceProvider();
bool IDocumentOperationService.CanApplyChange => true;
bool IDocumentOperationService.SupportDiagnostics => true;
TService? IDocumentServiceProvider.GetService<TService>() where TService : class
{
if (typeof(TService) == typeof(DocumentPropertiesService))
{
return (TService)(object)_documentPropertiesService;
}
return this as TService;
}
private sealed class VirtualDocumentPropertiesService : DocumentPropertiesService
{
private const string _lspClientName = "TypeScript";
private VirtualDocumentPropertiesService() { }
public static VirtualDocumentPropertiesService Instance = new VirtualDocumentPropertiesService();
public override string? DiagnosticsLspClientName => _lspClientName;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Host;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api
{
internal sealed partial class VSTypeScriptVisualStudioProjectWrapper
{
private sealed class LspContainedDocumentServiceProvider : IDocumentServiceProvider, IDocumentOperationService
{
private readonly VirtualDocumentPropertiesService _documentPropertiesService;
private LspContainedDocumentServiceProvider()
{
_documentPropertiesService = VirtualDocumentPropertiesService.Instance;
}
public static LspContainedDocumentServiceProvider Instance = new LspContainedDocumentServiceProvider();
bool IDocumentOperationService.CanApplyChange => true;
bool IDocumentOperationService.SupportDiagnostics => true;
TService? IDocumentServiceProvider.GetService<TService>() where TService : class
{
if (typeof(TService) == typeof(DocumentPropertiesService))
{
return (TService)(object)_documentPropertiesService;
}
return this as TService;
}
private sealed class VirtualDocumentPropertiesService : DocumentPropertiesService
{
private const string _lspClientName = "TypeScript";
private VirtualDocumentPropertiesService() { }
public static VirtualDocumentPropertiesService Instance = new VirtualDocumentPropertiesService();
public override string? DiagnosticsLspClientName => _lspClientName;
}
}
}
}
| -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/ExpressionEvaluator/CSharp/Source/ResultProvider/CSharpResultProvider.shproj | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project>
<PropertyGroup Label="Globals">
<ProjectGuid>3140fe61-0856-4367-9aa3-8081b9a80e36</ProjectGuid>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<PropertyGroup />
<Import Project="CSharpResultProvider.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project> | <?xml version="1.0" encoding="utf-8"?>
<!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. -->
<Project>
<PropertyGroup Label="Globals">
<ProjectGuid>3140fe61-0856-4367-9aa3-8081b9a80e36</ProjectGuid>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<PropertyGroup />
<Import Project="CSharpResultProvider.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</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/EditorFeatures/VisualBasic/xlf/VBEditorResources.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="../VBEditorResources.resx">
<body>
<trans-unit id="Add_Missing_Imports_on_Paste">
<source>Add Missing Imports on Paste</source>
<target state="translated">Beim Einfügen fehlende import-Anweisungen hinzufügen</target>
<note>"imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Adding_missing_imports">
<source>Adding missing imports...</source>
<target state="translated">Fehlende import-Anweisungen werden hinzugefügt...</target>
<note>Thread awaited dialog text. "imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Case_Correction">
<source>Case Correction</source>
<target state="translated">Fallkorrektur</target>
<note />
</trans-unit>
<trans-unit id="Correcting_word_casing">
<source>Correcting word casing...</source>
<target state="translated">Wortschreibweise wird korrigiert...</target>
<note />
</trans-unit>
<trans-unit id="This_call_is_required_by_the_designer">
<source>This call is required by the designer.</source>
<target state="translated">Dieser Aufruf ist für den Designer erforderlich.</target>
<note />
</trans-unit>
<trans-unit id="Add_any_initialization_after_the_InitializeComponent_call">
<source>Add any initialization after the InitializeComponent() call.</source>
<target state="translated">Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.</target>
<note />
</trans-unit>
<trans-unit id="End_Construct">
<source>End Construct</source>
<target state="translated">Endkonstrukt</target>
<note />
</trans-unit>
<trans-unit id="Smart_Indenting">
<source>Smart Indenting</source>
<target state="translated">Intelligenter Einzug</target>
<note />
</trans-unit>
<trans-unit id="Formatting_Document">
<source>Formatting Document...</source>
<target state="translated">Dokument wird formatiert...</target>
<note />
</trans-unit>
<trans-unit id="Insert_new_line">
<source>Insert new line</source>
<target state="translated">Neue Zeile einfügen</target>
<note />
</trans-unit>
<trans-unit id="Format_Paste">
<source>Format Paste</source>
<target state="translated">Format einfügen</target>
<note />
</trans-unit>
<trans-unit id="Formatting_pasted_text">
<source>Formatting pasted text...</source>
<target state="translated">Eingefügter Text wird formatiert...</target>
<note />
</trans-unit>
<trans-unit id="Paste">
<source>Paste</source>
<target state="translated">Einfügen</target>
<note />
</trans-unit>
<trans-unit id="Format_on_Save">
<source>Format on Save</source>
<target state="translated">Format wird gespeichert</target>
<note />
</trans-unit>
<trans-unit id="Committing_line">
<source>Committing line</source>
<target state="translated">Zeile wird committet</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_Pretty_List">
<source>Visual Basic Pretty List</source>
<target state="translated">Visual Basic - Automatische Strukturierung</target>
<note />
</trans-unit>
<trans-unit id="not_supported">
<source>not supported</source>
<target state="translated">nicht unterstützt</target>
<note />
</trans-unit>
<trans-unit id="Generate_Member">
<source>Generate Member</source>
<target state="translated">Mitglied generieren</target>
<note />
</trans-unit>
<trans-unit id="Line_commit">
<source>Line commit</source>
<target state="translated">Zeilencommit</target>
<note />
</trans-unit>
<trans-unit id="Implement_Abstract_Class_Or_Interface">
<source>Implement Abstract Class Or Interface</source>
<target state="translated">Abstrakte Klasse oder Schnittstelle implementieren</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="../VBEditorResources.resx">
<body>
<trans-unit id="Add_Missing_Imports_on_Paste">
<source>Add Missing Imports on Paste</source>
<target state="translated">Beim Einfügen fehlende import-Anweisungen hinzufügen</target>
<note>"imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Adding_missing_imports">
<source>Adding missing imports...</source>
<target state="translated">Fehlende import-Anweisungen werden hinzugefügt...</target>
<note>Thread awaited dialog text. "imports" is a language specific term and should not be localized</note>
</trans-unit>
<trans-unit id="Case_Correction">
<source>Case Correction</source>
<target state="translated">Fallkorrektur</target>
<note />
</trans-unit>
<trans-unit id="Correcting_word_casing">
<source>Correcting word casing...</source>
<target state="translated">Wortschreibweise wird korrigiert...</target>
<note />
</trans-unit>
<trans-unit id="This_call_is_required_by_the_designer">
<source>This call is required by the designer.</source>
<target state="translated">Dieser Aufruf ist für den Designer erforderlich.</target>
<note />
</trans-unit>
<trans-unit id="Add_any_initialization_after_the_InitializeComponent_call">
<source>Add any initialization after the InitializeComponent() call.</source>
<target state="translated">Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.</target>
<note />
</trans-unit>
<trans-unit id="End_Construct">
<source>End Construct</source>
<target state="translated">Endkonstrukt</target>
<note />
</trans-unit>
<trans-unit id="Smart_Indenting">
<source>Smart Indenting</source>
<target state="translated">Intelligenter Einzug</target>
<note />
</trans-unit>
<trans-unit id="Formatting_Document">
<source>Formatting Document...</source>
<target state="translated">Dokument wird formatiert...</target>
<note />
</trans-unit>
<trans-unit id="Insert_new_line">
<source>Insert new line</source>
<target state="translated">Neue Zeile einfügen</target>
<note />
</trans-unit>
<trans-unit id="Format_Paste">
<source>Format Paste</source>
<target state="translated">Format einfügen</target>
<note />
</trans-unit>
<trans-unit id="Formatting_pasted_text">
<source>Formatting pasted text...</source>
<target state="translated">Eingefügter Text wird formatiert...</target>
<note />
</trans-unit>
<trans-unit id="Paste">
<source>Paste</source>
<target state="translated">Einfügen</target>
<note />
</trans-unit>
<trans-unit id="Format_on_Save">
<source>Format on Save</source>
<target state="translated">Format wird gespeichert</target>
<note />
</trans-unit>
<trans-unit id="Committing_line">
<source>Committing line</source>
<target state="translated">Zeile wird committet</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_Pretty_List">
<source>Visual Basic Pretty List</source>
<target state="translated">Visual Basic - Automatische Strukturierung</target>
<note />
</trans-unit>
<trans-unit id="not_supported">
<source>not supported</source>
<target state="translated">nicht unterstützt</target>
<note />
</trans-unit>
<trans-unit id="Generate_Member">
<source>Generate Member</source>
<target state="translated">Mitglied generieren</target>
<note />
</trans-unit>
<trans-unit id="Line_commit">
<source>Line commit</source>
<target state="translated">Zeilencommit</target>
<note />
</trans-unit>
<trans-unit id="Implement_Abstract_Class_Or_Interface">
<source>Implement Abstract Class Or Interface</source>
<target state="translated">Abstrakte Klasse oder Schnittstelle implementieren</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/Workspaces/VisualBasic/Portable/CaseCorrection/VisualBasicCaseCorrectionService.Rewriter.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 System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CaseCorrection
Partial Friend Class VisualBasicCaseCorrectionService
Private Class Rewriter
Inherits VisualBasicSyntaxRewriter
Private ReadOnly _createAliasSet As Func(Of ImmutableHashSet(Of String)) =
Function()
Dim model = DirectCast(Me._semanticModel.GetOriginalSemanticModel(), SemanticModel)
' root should be already available
If Not model.SyntaxTree.HasCompilationUnitRoot Then
Return ImmutableHashSet.Create(Of String)()
End If
Dim root = model.SyntaxTree.GetCompilationUnitRoot()
Dim [set] = ImmutableHashSet.CreateBuilder(Of String)(StringComparer.OrdinalIgnoreCase)
For Each importsClause In root.GetAliasImportsClauses()
If Not String.IsNullOrWhiteSpace(importsClause.Alias.Identifier.ValueText) Then
[set].Add(importsClause.Alias.Identifier.ValueText)
End If
Next
For Each import In model.Compilation.AliasImports
[set].Add(import.Name)
Next
Return [set].ToImmutable()
End Function
Private ReadOnly _syntaxFactsService As ISyntaxFactsService
Private ReadOnly _semanticModel As SemanticModel
Private ReadOnly _aliasSet As Lazy(Of ImmutableHashSet(Of String))
Private ReadOnly _cancellationToken As CancellationToken
Public Sub New(syntaxFactsService As ISyntaxFactsService, semanticModel As SemanticModel, cancellationToken As CancellationToken)
MyBase.New(visitIntoStructuredTrivia:=True)
Me._syntaxFactsService = syntaxFactsService
Me._semanticModel = semanticModel
Me._aliasSet = New Lazy(Of ImmutableHashSet(Of String))(_createAliasSet)
Me._cancellationToken = cancellationToken
End Sub
Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken
Dim newToken = MyBase.VisitToken(token)
If _syntaxFactsService.IsIdentifier(newToken) Then
Return VisitIdentifier(token, newToken)
ElseIf _syntaxFactsService.IsReservedOrContextualKeyword(newToken) Then
Return VisitKeyword(newToken)
ElseIf token.IsNumericLiteral() Then
Return VisitNumericLiteral(newToken)
ElseIf token.IsCharacterLiteral() Then
Return VisitCharacterLiteral(newToken)
End If
Return newToken
End Function
Private Function VisitIdentifier(token As SyntaxToken, newToken As SyntaxToken) As SyntaxToken
If newToken.IsMissing OrElse TypeOf newToken.Parent Is ArgumentSyntax OrElse _semanticModel Is Nothing Then
Return newToken
End If
If token.Parent.IsPartOfStructuredTrivia() Then
Dim identifierSyntax = TryCast(token.Parent, IdentifierNameSyntax)
If identifierSyntax IsNot Nothing Then
Dim preprocessingSymbolInfo = _semanticModel.GetPreprocessingSymbolInfo(identifierSyntax)
If preprocessingSymbolInfo.Symbol IsNot Nothing Then
Dim name = preprocessingSymbolInfo.Symbol.Name
If Not String.IsNullOrEmpty(name) AndAlso name <> token.ValueText Then
' Name should differ only in case
Debug.Assert(name.Equals(token.ValueText, StringComparison.OrdinalIgnoreCase))
Return GetIdentifierWithCorrectedName(name, newToken)
End If
End If
End If
Return newToken
Else
Dim methodDeclaration = TryCast(token.Parent, MethodStatementSyntax)
If methodDeclaration IsNot Nothing Then
' If this is a partial method implementation part, then case correct the method name to match the partial method definition part.
Dim definitionPart As IMethodSymbol = Nothing
Dim otherPartOfPartial = GetOtherPartOfPartialMethod(methodDeclaration, definitionPart)
If otherPartOfPartial IsNot Nothing And Equals(otherPartOfPartial, definitionPart) Then
Return CaseCorrectIdentifierIfNamesDiffer(token, newToken, otherPartOfPartial)
End If
Else
Dim parameterSyntax = token.GetAncestor(Of ParameterSyntax)()
If parameterSyntax IsNot Nothing Then
' If this is a parameter declaration for a partial method implementation part,
' then case correct the parameter name to match the corresponding parameter in the partial method definition part.
methodDeclaration = parameterSyntax.GetAncestor(Of MethodStatementSyntax)()
If methodDeclaration IsNot Nothing Then
Dim definitionPart As IMethodSymbol = Nothing
Dim otherPartOfPartial = GetOtherPartOfPartialMethod(methodDeclaration, definitionPart)
If otherPartOfPartial IsNot Nothing And Equals(otherPartOfPartial, definitionPart) Then
Dim ordinal As Integer = 0
For Each param As SyntaxNode In methodDeclaration.ParameterList.Parameters
If param Is parameterSyntax Then
Exit For
End If
ordinal = ordinal + 1
Next
Debug.Assert(otherPartOfPartial.Parameters.Length > ordinal)
Dim otherPartParam = otherPartOfPartial.Parameters(ordinal)
' We don't want to rename the parameter if names are not equal ignoring case.
' Compiler will anyways generate an error for this case.
Return CaseCorrectIdentifierIfNamesDiffer(token, newToken, otherPartParam, namesMustBeEqualIgnoringCase:=True)
End If
End If
Else
' Named tuple expression
Dim nameColonEquals = TryCast(token.Parent?.Parent, NameColonEqualsSyntax)
If nameColonEquals IsNot Nothing AndAlso TypeOf nameColonEquals.Parent?.Parent Is TupleExpressionSyntax Then
Return newToken
End If
End If
End If
End If
Dim symbol = GetAliasOrAnySymbol(_semanticModel, token.Parent, _cancellationToken)
If symbol Is Nothing Then
Return newToken
End If
Dim expression = TryCast(token.Parent, ExpressionSyntax)
If expression IsNot Nothing AndAlso SyntaxFacts.IsInNamespaceOrTypeContext(expression) AndAlso Not IsNamespaceOrTypeRelatedSymbol(symbol) Then
Return newToken
End If
If TypeOf symbol Is ITypeSymbol AndAlso DirectCast(symbol, ITypeSymbol).TypeKind = TypeKind.Error Then
Return newToken
End If
' If it's a constructor we bind to, then we want to compare the name on the token to the
' name of the type. The name of the bound symbol will be something useless like '.ctor'.
' However, if it's an explicit New on the right side of a member access or qualified name, we want to use "New".
If symbol.IsConstructor Then
If token.IsNewOnRightSideOfDotOrBang() Then
Return SyntaxFactory.Identifier(newToken.LeadingTrivia, "New", newToken.TrailingTrivia)
End If
symbol = symbol.ContainingType
End If
Return CaseCorrectIdentifierIfNamesDiffer(token, newToken, symbol)
End Function
Private Shared Function IsNamespaceOrTypeRelatedSymbol(symbol As ISymbol) As Boolean
Return TypeOf symbol Is INamespaceOrTypeSymbol OrElse
(TypeOf symbol Is IAliasSymbol AndAlso TypeOf DirectCast(symbol, IAliasSymbol).Target Is INamespaceOrTypeSymbol) OrElse
(symbol.IsKind(SymbolKind.Method) AndAlso DirectCast(symbol, IMethodSymbol).MethodKind = MethodKind.Constructor)
End Function
Private Function GetAliasOrAnySymbol(model As SemanticModel, node As SyntaxNode, cancellationToken As CancellationToken) As ISymbol
Dim identifier = TryCast(node, IdentifierNameSyntax)
If identifier IsNot Nothing AndAlso Me._aliasSet.Value.Contains(identifier.Identifier.ValueText) Then
Dim [alias] = model.GetAliasInfo(identifier, cancellationToken)
If [alias] IsNot Nothing Then
Return [alias]
End If
End If
Return model.GetSymbolInfo(node, cancellationToken).GetAnySymbol()
End Function
Private Shared Function CaseCorrectIdentifierIfNamesDiffer(
token As SyntaxToken,
newToken As SyntaxToken,
symbol As ISymbol,
Optional namesMustBeEqualIgnoringCase As Boolean = False
) As SyntaxToken
If NamesDiffer(symbol, token) Then
If namesMustBeEqualIgnoringCase AndAlso Not String.Equals(symbol.Name, token.ValueText, StringComparison.OrdinalIgnoreCase) Then
Return newToken
End If
Dim correctedName = GetCorrectedName(token, symbol)
Return GetIdentifierWithCorrectedName(correctedName, newToken)
End If
Return newToken
End Function
Private Function GetOtherPartOfPartialMethod(methodDeclaration As MethodStatementSyntax, <Out> ByRef definitionPart As IMethodSymbol) As IMethodSymbol
Contract.ThrowIfNull(methodDeclaration)
Contract.ThrowIfNull(_semanticModel)
Dim methodSymbol = _semanticModel.GetDeclaredSymbol(methodDeclaration, _cancellationToken)
If methodSymbol IsNot Nothing Then
definitionPart = If(methodSymbol.PartialDefinitionPart, methodSymbol)
Return If(methodSymbol.PartialDefinitionPart, methodSymbol.PartialImplementationPart)
End If
Return Nothing
End Function
Private Shared Function GetCorrectedName(token As SyntaxToken, symbol As ISymbol) As String
If symbol.IsAttribute Then
If String.Equals(token.ValueText & s_attributeSuffix, symbol.Name, StringComparison.OrdinalIgnoreCase) Then
Return symbol.Name.Substring(0, symbol.Name.Length - s_attributeSuffix.Length)
End If
End If
Return symbol.Name
End Function
Private Shared Function GetIdentifierWithCorrectedName(correctedName As String, token As SyntaxToken) As SyntaxToken
If token.IsBracketed Then
Return SyntaxFactory.BracketedIdentifier(token.LeadingTrivia, correctedName, token.TrailingTrivia)
Else
Return SyntaxFactory.Identifier(token.LeadingTrivia, correctedName, token.TrailingTrivia)
End If
End Function
Private Shared Function NamesDiffer(symbol As ISymbol,
token As SyntaxToken) As Boolean
If String.IsNullOrEmpty(symbol.Name) Then
Return False
End If
If symbol.Name = token.ValueText Then
Return False
End If
If symbol.IsAttribute() Then
If symbol.Name = token.ValueText & s_attributeSuffix Then
Return False
End If
End If
Return True
End Function
Private Function VisitKeyword(token As SyntaxToken) As SyntaxToken
If Not token.IsMissing Then
Dim actualText = token.ToString()
Dim expectedText = _syntaxFactsService.GetText(token.Kind)
If Not String.IsNullOrWhiteSpace(expectedText) AndAlso actualText <> expectedText Then
Return SyntaxFactory.Token(token.LeadingTrivia, token.Kind, token.TrailingTrivia, expectedText)
End If
End If
Return token
End Function
Private Shared Function VisitNumericLiteral(token As SyntaxToken) As SyntaxToken
If Not token.IsMissing Then
' For any numeric literal, we simply case correct any letters to uppercase.
' The only letters allowed in a numeric literal are:
' * Type characters: S, US, I, UI, L, UL, D, F, R
' * Hex/Octal literals: H, O and A, B, C, D, E, F
' * Exponent: E
' * Time literals: AM, PM
Dim actualText = token.ToString()
Dim expectedText = actualText.ToUpperInvariant()
If actualText <> expectedText Then
Return SyntaxFactory.ParseToken(expectedText).WithLeadingTrivia(token.LeadingTrivia).WithTrailingTrivia(token.TrailingTrivia)
End If
End If
Return token
End Function
Private Shared Function VisitCharacterLiteral(token As SyntaxToken) As SyntaxToken
If Not token.IsMissing Then
' For character literals, we case correct the type character to "c".
Dim actualText = token.ToString()
If actualText.EndsWith("C", StringComparison.Ordinal) Then
Dim expectedText = actualText.Substring(0, actualText.Length - 1) & "c"
Return SyntaxFactory.ParseToken(expectedText).WithLeadingTrivia(token.LeadingTrivia).WithTrailingTrivia(token.TrailingTrivia)
End If
End If
Return token
End Function
Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia
trivia = MyBase.VisitTrivia(trivia)
If trivia.Kind = SyntaxKind.CommentTrivia AndAlso trivia.Width >= 3 Then
Dim remText = trivia.ToString().Substring(0, 3)
Dim remKeywordText As String = _syntaxFactsService.GetText(SyntaxKind.REMKeyword)
If remText <> remKeywordText AndAlso SyntaxFacts.GetKeywordKind(remText) = SyntaxKind.REMKeyword Then
Dim expectedText = remKeywordText & trivia.ToString().Substring(3)
Return SyntaxFactory.CommentTrivia(expectedText)
End If
End If
Return trivia
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CaseCorrection
Partial Friend Class VisualBasicCaseCorrectionService
Private Class Rewriter
Inherits VisualBasicSyntaxRewriter
Private ReadOnly _createAliasSet As Func(Of ImmutableHashSet(Of String)) =
Function()
Dim model = DirectCast(Me._semanticModel.GetOriginalSemanticModel(), SemanticModel)
' root should be already available
If Not model.SyntaxTree.HasCompilationUnitRoot Then
Return ImmutableHashSet.Create(Of String)()
End If
Dim root = model.SyntaxTree.GetCompilationUnitRoot()
Dim [set] = ImmutableHashSet.CreateBuilder(Of String)(StringComparer.OrdinalIgnoreCase)
For Each importsClause In root.GetAliasImportsClauses()
If Not String.IsNullOrWhiteSpace(importsClause.Alias.Identifier.ValueText) Then
[set].Add(importsClause.Alias.Identifier.ValueText)
End If
Next
For Each import In model.Compilation.AliasImports
[set].Add(import.Name)
Next
Return [set].ToImmutable()
End Function
Private ReadOnly _syntaxFactsService As ISyntaxFactsService
Private ReadOnly _semanticModel As SemanticModel
Private ReadOnly _aliasSet As Lazy(Of ImmutableHashSet(Of String))
Private ReadOnly _cancellationToken As CancellationToken
Public Sub New(syntaxFactsService As ISyntaxFactsService, semanticModel As SemanticModel, cancellationToken As CancellationToken)
MyBase.New(visitIntoStructuredTrivia:=True)
Me._syntaxFactsService = syntaxFactsService
Me._semanticModel = semanticModel
Me._aliasSet = New Lazy(Of ImmutableHashSet(Of String))(_createAliasSet)
Me._cancellationToken = cancellationToken
End Sub
Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken
Dim newToken = MyBase.VisitToken(token)
If _syntaxFactsService.IsIdentifier(newToken) Then
Return VisitIdentifier(token, newToken)
ElseIf _syntaxFactsService.IsReservedOrContextualKeyword(newToken) Then
Return VisitKeyword(newToken)
ElseIf token.IsNumericLiteral() Then
Return VisitNumericLiteral(newToken)
ElseIf token.IsCharacterLiteral() Then
Return VisitCharacterLiteral(newToken)
End If
Return newToken
End Function
Private Function VisitIdentifier(token As SyntaxToken, newToken As SyntaxToken) As SyntaxToken
If newToken.IsMissing OrElse TypeOf newToken.Parent Is ArgumentSyntax OrElse _semanticModel Is Nothing Then
Return newToken
End If
If token.Parent.IsPartOfStructuredTrivia() Then
Dim identifierSyntax = TryCast(token.Parent, IdentifierNameSyntax)
If identifierSyntax IsNot Nothing Then
Dim preprocessingSymbolInfo = _semanticModel.GetPreprocessingSymbolInfo(identifierSyntax)
If preprocessingSymbolInfo.Symbol IsNot Nothing Then
Dim name = preprocessingSymbolInfo.Symbol.Name
If Not String.IsNullOrEmpty(name) AndAlso name <> token.ValueText Then
' Name should differ only in case
Debug.Assert(name.Equals(token.ValueText, StringComparison.OrdinalIgnoreCase))
Return GetIdentifierWithCorrectedName(name, newToken)
End If
End If
End If
Return newToken
Else
Dim methodDeclaration = TryCast(token.Parent, MethodStatementSyntax)
If methodDeclaration IsNot Nothing Then
' If this is a partial method implementation part, then case correct the method name to match the partial method definition part.
Dim definitionPart As IMethodSymbol = Nothing
Dim otherPartOfPartial = GetOtherPartOfPartialMethod(methodDeclaration, definitionPart)
If otherPartOfPartial IsNot Nothing And Equals(otherPartOfPartial, definitionPart) Then
Return CaseCorrectIdentifierIfNamesDiffer(token, newToken, otherPartOfPartial)
End If
Else
Dim parameterSyntax = token.GetAncestor(Of ParameterSyntax)()
If parameterSyntax IsNot Nothing Then
' If this is a parameter declaration for a partial method implementation part,
' then case correct the parameter name to match the corresponding parameter in the partial method definition part.
methodDeclaration = parameterSyntax.GetAncestor(Of MethodStatementSyntax)()
If methodDeclaration IsNot Nothing Then
Dim definitionPart As IMethodSymbol = Nothing
Dim otherPartOfPartial = GetOtherPartOfPartialMethod(methodDeclaration, definitionPart)
If otherPartOfPartial IsNot Nothing And Equals(otherPartOfPartial, definitionPart) Then
Dim ordinal As Integer = 0
For Each param As SyntaxNode In methodDeclaration.ParameterList.Parameters
If param Is parameterSyntax Then
Exit For
End If
ordinal = ordinal + 1
Next
Debug.Assert(otherPartOfPartial.Parameters.Length > ordinal)
Dim otherPartParam = otherPartOfPartial.Parameters(ordinal)
' We don't want to rename the parameter if names are not equal ignoring case.
' Compiler will anyways generate an error for this case.
Return CaseCorrectIdentifierIfNamesDiffer(token, newToken, otherPartParam, namesMustBeEqualIgnoringCase:=True)
End If
End If
Else
' Named tuple expression
Dim nameColonEquals = TryCast(token.Parent?.Parent, NameColonEqualsSyntax)
If nameColonEquals IsNot Nothing AndAlso TypeOf nameColonEquals.Parent?.Parent Is TupleExpressionSyntax Then
Return newToken
End If
End If
End If
End If
Dim symbol = GetAliasOrAnySymbol(_semanticModel, token.Parent, _cancellationToken)
If symbol Is Nothing Then
Return newToken
End If
Dim expression = TryCast(token.Parent, ExpressionSyntax)
If expression IsNot Nothing AndAlso SyntaxFacts.IsInNamespaceOrTypeContext(expression) AndAlso Not IsNamespaceOrTypeRelatedSymbol(symbol) Then
Return newToken
End If
If TypeOf symbol Is ITypeSymbol AndAlso DirectCast(symbol, ITypeSymbol).TypeKind = TypeKind.Error Then
Return newToken
End If
' If it's a constructor we bind to, then we want to compare the name on the token to the
' name of the type. The name of the bound symbol will be something useless like '.ctor'.
' However, if it's an explicit New on the right side of a member access or qualified name, we want to use "New".
If symbol.IsConstructor Then
If token.IsNewOnRightSideOfDotOrBang() Then
Return SyntaxFactory.Identifier(newToken.LeadingTrivia, "New", newToken.TrailingTrivia)
End If
symbol = symbol.ContainingType
End If
Return CaseCorrectIdentifierIfNamesDiffer(token, newToken, symbol)
End Function
Private Shared Function IsNamespaceOrTypeRelatedSymbol(symbol As ISymbol) As Boolean
Return TypeOf symbol Is INamespaceOrTypeSymbol OrElse
(TypeOf symbol Is IAliasSymbol AndAlso TypeOf DirectCast(symbol, IAliasSymbol).Target Is INamespaceOrTypeSymbol) OrElse
(symbol.IsKind(SymbolKind.Method) AndAlso DirectCast(symbol, IMethodSymbol).MethodKind = MethodKind.Constructor)
End Function
Private Function GetAliasOrAnySymbol(model As SemanticModel, node As SyntaxNode, cancellationToken As CancellationToken) As ISymbol
Dim identifier = TryCast(node, IdentifierNameSyntax)
If identifier IsNot Nothing AndAlso Me._aliasSet.Value.Contains(identifier.Identifier.ValueText) Then
Dim [alias] = model.GetAliasInfo(identifier, cancellationToken)
If [alias] IsNot Nothing Then
Return [alias]
End If
End If
Return model.GetSymbolInfo(node, cancellationToken).GetAnySymbol()
End Function
Private Shared Function CaseCorrectIdentifierIfNamesDiffer(
token As SyntaxToken,
newToken As SyntaxToken,
symbol As ISymbol,
Optional namesMustBeEqualIgnoringCase As Boolean = False
) As SyntaxToken
If NamesDiffer(symbol, token) Then
If namesMustBeEqualIgnoringCase AndAlso Not String.Equals(symbol.Name, token.ValueText, StringComparison.OrdinalIgnoreCase) Then
Return newToken
End If
Dim correctedName = GetCorrectedName(token, symbol)
Return GetIdentifierWithCorrectedName(correctedName, newToken)
End If
Return newToken
End Function
Private Function GetOtherPartOfPartialMethod(methodDeclaration As MethodStatementSyntax, <Out> ByRef definitionPart As IMethodSymbol) As IMethodSymbol
Contract.ThrowIfNull(methodDeclaration)
Contract.ThrowIfNull(_semanticModel)
Dim methodSymbol = _semanticModel.GetDeclaredSymbol(methodDeclaration, _cancellationToken)
If methodSymbol IsNot Nothing Then
definitionPart = If(methodSymbol.PartialDefinitionPart, methodSymbol)
Return If(methodSymbol.PartialDefinitionPart, methodSymbol.PartialImplementationPart)
End If
Return Nothing
End Function
Private Shared Function GetCorrectedName(token As SyntaxToken, symbol As ISymbol) As String
If symbol.IsAttribute Then
If String.Equals(token.ValueText & s_attributeSuffix, symbol.Name, StringComparison.OrdinalIgnoreCase) Then
Return symbol.Name.Substring(0, symbol.Name.Length - s_attributeSuffix.Length)
End If
End If
Return symbol.Name
End Function
Private Shared Function GetIdentifierWithCorrectedName(correctedName As String, token As SyntaxToken) As SyntaxToken
If token.IsBracketed Then
Return SyntaxFactory.BracketedIdentifier(token.LeadingTrivia, correctedName, token.TrailingTrivia)
Else
Return SyntaxFactory.Identifier(token.LeadingTrivia, correctedName, token.TrailingTrivia)
End If
End Function
Private Shared Function NamesDiffer(symbol As ISymbol,
token As SyntaxToken) As Boolean
If String.IsNullOrEmpty(symbol.Name) Then
Return False
End If
If symbol.Name = token.ValueText Then
Return False
End If
If symbol.IsAttribute() Then
If symbol.Name = token.ValueText & s_attributeSuffix Then
Return False
End If
End If
Return True
End Function
Private Function VisitKeyword(token As SyntaxToken) As SyntaxToken
If Not token.IsMissing Then
Dim actualText = token.ToString()
Dim expectedText = _syntaxFactsService.GetText(token.Kind)
If Not String.IsNullOrWhiteSpace(expectedText) AndAlso actualText <> expectedText Then
Return SyntaxFactory.Token(token.LeadingTrivia, token.Kind, token.TrailingTrivia, expectedText)
End If
End If
Return token
End Function
Private Shared Function VisitNumericLiteral(token As SyntaxToken) As SyntaxToken
If Not token.IsMissing Then
' For any numeric literal, we simply case correct any letters to uppercase.
' The only letters allowed in a numeric literal are:
' * Type characters: S, US, I, UI, L, UL, D, F, R
' * Hex/Octal literals: H, O and A, B, C, D, E, F
' * Exponent: E
' * Time literals: AM, PM
Dim actualText = token.ToString()
Dim expectedText = actualText.ToUpperInvariant()
If actualText <> expectedText Then
Return SyntaxFactory.ParseToken(expectedText).WithLeadingTrivia(token.LeadingTrivia).WithTrailingTrivia(token.TrailingTrivia)
End If
End If
Return token
End Function
Private Shared Function VisitCharacterLiteral(token As SyntaxToken) As SyntaxToken
If Not token.IsMissing Then
' For character literals, we case correct the type character to "c".
Dim actualText = token.ToString()
If actualText.EndsWith("C", StringComparison.Ordinal) Then
Dim expectedText = actualText.Substring(0, actualText.Length - 1) & "c"
Return SyntaxFactory.ParseToken(expectedText).WithLeadingTrivia(token.LeadingTrivia).WithTrailingTrivia(token.TrailingTrivia)
End If
End If
Return token
End Function
Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia
trivia = MyBase.VisitTrivia(trivia)
If trivia.Kind = SyntaxKind.CommentTrivia AndAlso trivia.Width >= 3 Then
Dim remText = trivia.ToString().Substring(0, 3)
Dim remKeywordText As String = _syntaxFactsService.GetText(SyntaxKind.REMKeyword)
If remText <> remKeywordText AndAlso SyntaxFacts.GetKeywordKind(remText) = SyntaxKind.REMKeyword Then
Dim expectedText = remKeywordText & trivia.ToString().Substring(3)
Return SyntaxFactory.CommentTrivia(expectedText)
End If
End If
Return trivia
End Function
End Class
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/CoreTest/SemanticModelReuse/SemanticModelReuseTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.SemanticModelReuse
{
[UseExportProvider]
public class SemanticModelReuseTests
{
private static Document CreateDocument(string code, string language)
{
var solution = new AdhocWorkspace().CurrentSolution;
var projectId = ProjectId.CreateNewId();
var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId);
return project.AddMetadataReference(TestMetadata.Net40.mscorlib)
.AddDocument("Document", SourceText.From(code));
}
#region C# tests
[Fact]
public async Task NullBodyReturnsNormalSemanticModel1_CSharp()
{
var document = CreateDocument("", LanguageNames.CSharp);
// trying to get a model for null should return a non-speculative model
var model = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None);
Assert.False(model.IsSpeculativeSemanticModel);
}
[Fact]
public async Task NullBodyReturnsNormalSemanticModel2_CSharp()
{
var source = "class C { void M() { return; } }";
var document = CreateDocument(source, LanguageNames.CSharp);
// Even if we've primed things with a real location, getting a semantic model for null should return a
// non-speculative model.
var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
var model2 = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
Assert.False(model2.IsSpeculativeSemanticModel);
}
[Fact]
public async Task SameSyntaxTreeReturnsNonSpeculativeModel_CSharp()
{
var source = "class C { void M() { return; } }";
var document = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model. The next call will also use the
// same syntax tree, so it should get the same semantic model.
var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
var model2 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
Assert.False(model2.IsSpeculativeSemanticModel);
// Should be the same models.
Assert.Equal(model1, model2);
// Which also should be the normal model the document provides.
var actualModel = await document.GetSemanticModelAsync();
Assert.Equal(model1, actualModel);
}
[Fact]
public async Task InBodyEditShouldProduceCachedModel_CSharp()
{
var source = "class C { void M() { return; } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { void M() { return null; } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
}
[Fact]
public async Task OutOfBodyEditShouldProduceFreshModel_CSharp()
{
var source = "class C { void M() { return; } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { long M() { return; } }"));
// We changed the return type, so we can't reuse the previous model.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model2.IsSpeculativeSemanticModel);
var document3 = document2.WithText(SourceText.From("class C { long M() { return 0; } }"));
// We are now again only editing a method body so we should be able to get a speculative model.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact]
public async Task MultipleBodyEditsShouldProduceFreshModel_CSharp()
{
var source = "class C { void M() { return; } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { void M() { return 0; } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From("class C { void M() { return 1; } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")]
public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Property_CSharp()
{
var source = "class C { int M { get { return 0; } } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { int M { get { return 1; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From("class C { int M { get { return 2; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")]
public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Event_CSharp()
{
var source = "class C { event System.Action E { add { return 0; } } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { event System.Action E { add { return 1; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From("class C { event System.Action E { add { return 2; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")]
public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Indexer_CSharp()
{
var source = "class C { int this[int i] { get { return 0; } } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { int this[int i] { get { return 1; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From("class C { int this[int i] { get { return 2; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
#endregion
#region Visual Basic tests
[Fact]
public async Task NullBodyReturnsNormalSemanticModel1_VisualBasic()
{
var document = CreateDocument("", LanguageNames.VisualBasic);
// trying to get a model for null should return a non-speculative model
var model = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None);
Assert.False(model.IsSpeculativeSemanticModel);
}
[Fact]
public async Task NullBodyReturnsNormalSemanticModel2_VisualBasic()
{
var source = @"
class C
sub M()
return
end sub
end class";
var document = CreateDocument(source, LanguageNames.VisualBasic);
// Even if we've primed things with a real location, getting a semantic model for null should return a
// non-speculative model.
var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
var model2 = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
Assert.False(model2.IsSpeculativeSemanticModel);
}
[Fact]
public async Task SameSyntaxTreeReturnsNonSpeculativeModel_VisualBasic()
{
var source = @"
class C
sub M()
return
end sub
end class";
var document = CreateDocument(source, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model. The next call will also use the
// same syntax tree, so it should get the same semantic model.
var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
var model2 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
Assert.False(model2.IsSpeculativeSemanticModel);
// Should be the same models.
Assert.Equal(model1, model2);
// Which also should be the normal model the document provides.
var actualModel = await document.GetSemanticModelAsync();
Assert.Equal(model1, actualModel);
}
[Fact]
public async Task InBodyEditShouldProduceCachedModel_VisualBasic()
{
var source = @"
class C
sub M()
return
end sub
end class";
var document1 = CreateDocument(source, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From(@"
class C
sub M()
return nothing
end sub
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
}
[Fact]
public async Task OutOfBodyEditShouldProduceFreshModel_VisualBasic()
{
var source1 = @"
class C
sub M()
return
end sub
end class";
var document1 = CreateDocument(source1, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source1.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var source2 = @"
class C
function M() as long
return
end function
end class";
var document2 = document1.WithText(SourceText.From(source2));
// We changed the return type, so we can't reuse the previous model.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source2.IndexOf("return"), CancellationToken.None);
Assert.False(model2.IsSpeculativeSemanticModel);
var document3 = document2.WithText(SourceText.From(@"
class C
function M() as long
return 0
end function
end class"));
// We are now again only editing a method body so we should be able to get a speculative model.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source2.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact]
public async Task MultipleBodyEditsShouldProduceFreshModel_VisualBasic()
{
var source = @"class C
sub M()
return
end sub
end class";
var document1 = CreateDocument(source, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From(@"
class C
sub M()
return 0
end sub
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From(@"
class C
sub M()
return 1
end sub
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact]
public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Property_VisualBasic()
{
var source = @"
class C
readonly property M as integer
get
return 0
end get
end property
end class";
var document1 = CreateDocument(source, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From(@"
class C
readonly property M as integer
get
return 1
end get
end property
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From(@"
class C
readonly property M as integer
get
return 2
end get
end property
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact]
public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Event_VisualBasic()
{
var source = @"
class C
public custom event E as System.Action
addhandler(value as System.Action)
return 0
end addhandler
end event
end class";
var document1 = CreateDocument(source, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From(@"
class C
public custom event E as System.Action
addhandler(value as System.Action)
return 1
end addhandler
end event
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From(@"
class C
public custom event E as System.Action
addhandler(value as System.Action)
return 2
end addhandler
end event
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.SemanticModelReuse
{
[UseExportProvider]
public class SemanticModelReuseTests
{
private static Document CreateDocument(string code, string language)
{
var solution = new AdhocWorkspace().CurrentSolution;
var projectId = ProjectId.CreateNewId();
var project = solution.AddProject(projectId, "Project", "Project.dll", language).GetProject(projectId);
return project.AddMetadataReference(TestMetadata.Net40.mscorlib)
.AddDocument("Document", SourceText.From(code));
}
#region C# tests
[Fact]
public async Task NullBodyReturnsNormalSemanticModel1_CSharp()
{
var document = CreateDocument("", LanguageNames.CSharp);
// trying to get a model for null should return a non-speculative model
var model = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None);
Assert.False(model.IsSpeculativeSemanticModel);
}
[Fact]
public async Task NullBodyReturnsNormalSemanticModel2_CSharp()
{
var source = "class C { void M() { return; } }";
var document = CreateDocument(source, LanguageNames.CSharp);
// Even if we've primed things with a real location, getting a semantic model for null should return a
// non-speculative model.
var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
var model2 = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
Assert.False(model2.IsSpeculativeSemanticModel);
}
[Fact]
public async Task SameSyntaxTreeReturnsNonSpeculativeModel_CSharp()
{
var source = "class C { void M() { return; } }";
var document = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model. The next call will also use the
// same syntax tree, so it should get the same semantic model.
var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
var model2 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
Assert.False(model2.IsSpeculativeSemanticModel);
// Should be the same models.
Assert.Equal(model1, model2);
// Which also should be the normal model the document provides.
var actualModel = await document.GetSemanticModelAsync();
Assert.Equal(model1, actualModel);
}
[Fact]
public async Task InBodyEditShouldProduceCachedModel_CSharp()
{
var source = "class C { void M() { return; } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { void M() { return null; } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
}
[Fact]
public async Task OutOfBodyEditShouldProduceFreshModel_CSharp()
{
var source = "class C { void M() { return; } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { long M() { return; } }"));
// We changed the return type, so we can't reuse the previous model.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model2.IsSpeculativeSemanticModel);
var document3 = document2.WithText(SourceText.From("class C { long M() { return 0; } }"));
// We are now again only editing a method body so we should be able to get a speculative model.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact]
public async Task MultipleBodyEditsShouldProduceFreshModel_CSharp()
{
var source = "class C { void M() { return; } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { void M() { return 0; } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From("class C { void M() { return 1; } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")]
public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Property_CSharp()
{
var source = "class C { int M { get { return 0; } } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { int M { get { return 1; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From("class C { int M { get { return 2; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")]
public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Event_CSharp()
{
var source = "class C { event System.Action E { add { return 0; } } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { event System.Action E { add { return 1; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From("class C { event System.Action E { add { return 2; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact, WorkItem(1167540, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1167540")]
public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Indexer_CSharp()
{
var source = "class C { int this[int i] { get { return 0; } } }";
var document1 = CreateDocument(source, LanguageNames.CSharp);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From("class C { int this[int i] { get { return 1; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From("class C { int this[int i] { get { return 2; } } }"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
#endregion
#region Visual Basic tests
[Fact]
public async Task NullBodyReturnsNormalSemanticModel1_VisualBasic()
{
var document = CreateDocument("", LanguageNames.VisualBasic);
// trying to get a model for null should return a non-speculative model
var model = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None);
Assert.False(model.IsSpeculativeSemanticModel);
}
[Fact]
public async Task NullBodyReturnsNormalSemanticModel2_VisualBasic()
{
var source = @"
class C
sub M()
return
end sub
end class";
var document = CreateDocument(source, LanguageNames.VisualBasic);
// Even if we've primed things with a real location, getting a semantic model for null should return a
// non-speculative model.
var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
var model2 = await document.ReuseExistingSpeculativeModelAsync(null, CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
Assert.False(model2.IsSpeculativeSemanticModel);
}
[Fact]
public async Task SameSyntaxTreeReturnsNonSpeculativeModel_VisualBasic()
{
var source = @"
class C
sub M()
return
end sub
end class";
var document = CreateDocument(source, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model. The next call will also use the
// same syntax tree, so it should get the same semantic model.
var model1 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
var model2 = await document.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
Assert.False(model2.IsSpeculativeSemanticModel);
// Should be the same models.
Assert.Equal(model1, model2);
// Which also should be the normal model the document provides.
var actualModel = await document.GetSemanticModelAsync();
Assert.Equal(model1, actualModel);
}
[Fact]
public async Task InBodyEditShouldProduceCachedModel_VisualBasic()
{
var source = @"
class C
sub M()
return
end sub
end class";
var document1 = CreateDocument(source, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From(@"
class C
sub M()
return nothing
end sub
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
}
[Fact]
public async Task OutOfBodyEditShouldProduceFreshModel_VisualBasic()
{
var source1 = @"
class C
sub M()
return
end sub
end class";
var document1 = CreateDocument(source1, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source1.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var source2 = @"
class C
function M() as long
return
end function
end class";
var document2 = document1.WithText(SourceText.From(source2));
// We changed the return type, so we can't reuse the previous model.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source2.IndexOf("return"), CancellationToken.None);
Assert.False(model2.IsSpeculativeSemanticModel);
var document3 = document2.WithText(SourceText.From(@"
class C
function M() as long
return 0
end function
end class"));
// We are now again only editing a method body so we should be able to get a speculative model.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source2.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact]
public async Task MultipleBodyEditsShouldProduceFreshModel_VisualBasic()
{
var source = @"class C
sub M()
return
end sub
end class";
var document1 = CreateDocument(source, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From(@"
class C
sub M()
return 0
end sub
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From(@"
class C
sub M()
return 1
end sub
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact]
public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Property_VisualBasic()
{
var source = @"
class C
readonly property M as integer
get
return 0
end get
end property
end class";
var document1 = CreateDocument(source, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From(@"
class C
readonly property M as integer
get
return 1
end get
end property
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From(@"
class C
readonly property M as integer
get
return 2
end get
end property
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
[Fact]
public async Task MultipleBodyEditsShouldProduceFreshModel_Accessor_Event_VisualBasic()
{
var source = @"
class C
public custom event E as System.Action
addhandler(value as System.Action)
return 0
end addhandler
end event
end class";
var document1 = CreateDocument(source, LanguageNames.VisualBasic);
// First call will prime the cache to point at the real semantic model.
var model1 = await document1.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.False(model1.IsSpeculativeSemanticModel);
var document2 = document1.WithText(SourceText.From(@"
class C
public custom event E as System.Action
addhandler(value as System.Action)
return 1
end addhandler
end event
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model2 = await document2.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model2.IsSpeculativeSemanticModel);
var document3 = document1.WithText(SourceText.From(@"
class C
public custom event E as System.Action
addhandler(value as System.Action)
return 2
end addhandler
end event
end class"));
// This should be able to get a speculative model using the original model we primed the cache with.
var model3 = await document3.ReuseExistingSpeculativeModelAsync(source.IndexOf("return"), CancellationToken.None);
Assert.True(model3.IsSpeculativeSemanticModel);
}
#endregion
}
}
| -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/Test/Syntax/Parsing/AsyncParsingTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Roslyn.Test.Utilities;
using System;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AsyncParsingTests : ParsingTests
{
public AsyncParsingTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: (options ?? TestOptions.Regular).WithLanguageVersion(LanguageVersion.CSharp5));
}
protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options = null)
{
return SyntaxFactory.ParseExpression(text, options: (options ?? TestOptions.Regular).WithLanguageVersion(LanguageVersion.CSharp5));
}
private void TestVersions(Action<CSharpParseOptions> test)
{
foreach (LanguageVersion version in Enum.GetValues(typeof(LanguageVersion)))
{
test(new CSharpParseOptions(languageVersion: version));
}
}
[Fact]
public void SimpleAsyncMethod()
{
UsingTree(@"
class C
{
async void M() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodCalledAsync()
{
UsingTree(@"
class C
{
void async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodReturningAsync()
{
UsingTree(@"
class C
{
async M() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsync()
{
UsingTree(@"
class C
{
async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(13090, "https://github.com/dotnet/roslyn/issues/13090")]
[Fact]
public void MethodAsyncVarAsync()
{
UsingTree(
@"class C
{
static async void M(object async)
{
async.F();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
N(SyntaxKind.VoidKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
N(SyntaxKind.ObjectKeyword);
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void IncompleteAsync()
{
UsingTree(@"
class C
{
async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void IncompleteAsyncAsync()
{
UsingTree(@"
class C
{
async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsync1()
{
UsingTree(@"
class C
{
async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsync2()
{
UsingTree(@"
class C
{
async async = 1;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void IncompleteAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void IncompleteAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember01()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
async Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember02()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
async Tasks.Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember03()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
static async Tasks.Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember04()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async operator+
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken); // async
}
N(SyntaxKind.OperatorKeyword);
N(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember05()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async Task<T>
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember06()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async Task<T> f
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void PropertyAsyncAsync()
{
UsingTree(@"
class C
{
async async { get; set; }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.SetAccessorDeclaration);
{
N(SyntaxKind.SetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void PropertyAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async { get; set; }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.SetAccessorDeclaration);
{
N(SyntaxKind.SetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsync()
{
UsingTree(@"
class C
{
event async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsyncAsync1()
{
UsingTree(@"
class C
{
event async async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsyncAsync2()
{
UsingTree(@"
class C
{
async event async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void AsyncModifierOnDelegateDeclaration()
{
UsingTree(@"
class C
{
public async delegate void Goo();
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.DelegateDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void NonAsyncLambda()
{
TestVersions(options =>
{
UsingNode("async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncSimpleLambda()
{
TestVersions(options =>
{
UsingNode("async async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncAsyncAsyncAsyncSimpleLambda()
{
TestVersions(options =>
{
UsingNode("async async => async async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
}
});
}
[Fact]
public void NonAsyncParenthesizedLambda()
{
TestVersions(options =>
{
UsingNode("(async) => async", options);
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncParenthesizedLambda()
{
TestVersions(options =>
{
UsingNode("async (async) => async", options);
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncSimpleDelegate()
{
TestVersions(options =>
{
UsingNode("async delegate { }", options);
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
});
}
[Fact]
public void AsyncParenthesizedDelegate()
{
TestVersions(options =>
{
UsingNode("async delegate (int x) { }", options);
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
});
}
// Comment directly from CParser::IsAsyncMethod.
// ... 'async' [partial] <typedecl> ...
// ... 'async' [partial] <event> ...
// ... 'async' [partial] <implicit> <operator> ...
// ... 'async' [partial] <explicit> <operator> ...
// ... 'async' [partial] <typename> <operator> ...
// ... 'async' [partial] <typename> <membername> ...
// DEVNOTE: Although we parse async user defined conversions, operators, etc. here,
// anything other than async methods are detected as erroneous later, during the define phase
[Fact]
public void AsyncInterface()
{
// ... 'async' <typedecl> ...
UsingTree(@"
class C
{
async interface
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.InterfaceKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialClass()
{
// ... 'async' 'partial' <typedecl> ...
UsingTree(@"
class C
{
async partial class
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PartialKeyword);
N(SyntaxKind.ClassKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncEvent()
{
// ... 'async' <event> ...
UsingTree(@"
class C
{
async event
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.EventKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialEvent()
{
// ... 'async' 'partial' <event> ...
UsingTree(@"
class C
{
async partial event
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
}
N(SyntaxKind.EventDeclaration);
{
N(SyntaxKind.EventKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncImplicitOperator()
{
// ... 'async' <implicit> <operator> ...
UsingTree(@"
class C
{
async implicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ConversionOperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ImplicitKeyword);
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialImplicitOperator()
{
// ... 'async' 'partial' <implicit> <operator> ...
UsingTree(@"
class C
{
async partial implicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
M(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncExplicitOperator()
{
// ... 'async' <explicit> <operator> ...
UsingTree(@"
class C
{
async explicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ConversionOperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ExplicitKeyword);
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialExplicitOperator()
{
// ... 'async' 'partial' <explicit> <operator> ...
UsingTree(@"
class C
{
async partial explicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
M(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeOperator()
{
// ... 'async' <typename> <operator> ...
UsingTree(@"
class C
{
async C operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialTypeOperator()
{
// ... 'async' 'partial' <typename> <operator> ...
UsingTree(@"
class C
{
async partial int operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
}
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncField()
{
// ... 'async' <typename> <membername> ...
UsingTree(@"
class C
{
async C C
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "C");
}
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialIndexer()
{
// ... 'async' 'partial' <typename> <membername> ...
UsingTree(@"
class C
{
async partial C this
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PartialKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.ThisKeyword);
M(SyntaxKind.BracketedParameterList);
{
M(SyntaxKind.OpenBracketToken);
M(SyntaxKind.CloseBracketToken);
}
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeEndOfFile()
{
UsingTree("class C { async T");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeCloseCurly()
{
UsingTree("class C { async T }");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypePredefinedType()
{
UsingTree(
@"class C {
async T
int");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeModifier()
{
UsingTree(
@"class C {
async T
public");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PublicKeyword);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeFollowedByTypeDecl()
{
UsingTree(
@"class C {
async T
class");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeFollowedByNamespaceDecl()
{
UsingTree(
@"class C {
async T
namespace");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.NamespaceDeclaration);
{
N(SyntaxKind.NamespaceKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(18621, "https://github.com/dotnet/roslyn/issues/18621")]
public void AsyncGenericType()
{
UsingTree(
@"class Program
{
public async Task<IReadOnlyCollection<ProjectConfiguration>>
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "Task");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IReadOnlyCollection");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectConfiguration");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property_ExpressionBody()
{
UsingTree("class async { async async => null; }").GetDiagnostics().Verify(
// (1,27): error CS8026: Feature 'expression-bodied property' is not available in C# 5. Please use language version 6 or greater.
// class async { async async => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied property", "6").WithLocation(1, 27)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property()
{
UsingTree("class async { async async { get; } }").GetDiagnostics().Verify();
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Indexer_ExpressionBody_ErrorCase()
{
UsingTree("interface async { async this[async i] => null; }").GetDiagnostics().Verify(
// (1,39): error CS8026: Feature 'expression-bodied indexer' is not available in C# 5. Please use language version 6 or greater.
// interface async { async this[async i] => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied indexer", "6").WithLocation(1, 39)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.InterfaceKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ThisKeyword);
N(SyntaxKind.BracketedParameterList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Indexer()
{
UsingTree("interface async { async this[async i] { get; } }").GetDiagnostics().Verify();
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.InterfaceKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ThisKeyword);
N(SyntaxKind.BracketedParameterList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property_ExplicitInterface()
{
UsingTree("class async : async { async async.async => null; }").GetDiagnostics().Verify(
// (1,41): error CS8026: Feature 'expression-bodied property' is not available in C# 5. Please use language version 6 or greater.
// class async : async { async async.async => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied property", "6").WithLocation(1, 41)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.BaseList);
{
N(SyntaxKind.ColonToken);
N(SyntaxKind.SimpleBaseType);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ExplicitInterfaceSpecifier);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.DotToken);
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Roslyn.Test.Utilities;
using System;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class AsyncParsingTests : ParsingTests
{
public AsyncParsingTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: (options ?? TestOptions.Regular).WithLanguageVersion(LanguageVersion.CSharp5));
}
protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options = null)
{
return SyntaxFactory.ParseExpression(text, options: (options ?? TestOptions.Regular).WithLanguageVersion(LanguageVersion.CSharp5));
}
private void TestVersions(Action<CSharpParseOptions> test)
{
foreach (LanguageVersion version in Enum.GetValues(typeof(LanguageVersion)))
{
test(new CSharpParseOptions(languageVersion: version));
}
}
[Fact]
public void SimpleAsyncMethod()
{
UsingTree(@"
class C
{
async void M() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodCalledAsync()
{
UsingTree(@"
class C
{
void async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodReturningAsync()
{
UsingTree(@"
class C
{
async M() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsync()
{
UsingTree(@"
class C
{
async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void MethodAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async() { }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(13090, "https://github.com/dotnet/roslyn/issues/13090")]
[Fact]
public void MethodAsyncVarAsync()
{
UsingTree(
@"class C
{
static async void M(object async)
{
async.F();
}
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
N(SyntaxKind.VoidKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
N(SyntaxKind.ObjectKeyword);
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void IncompleteAsync()
{
UsingTree(@"
class C
{
async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void IncompleteAsyncAsync()
{
UsingTree(@"
class C
{
async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsync1()
{
UsingTree(@"
class C
{
async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsync2()
{
UsingTree(@"
class C
{
async async = 1;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void IncompleteAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void IncompleteAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void CompleteAsyncAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async async;
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
N(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember01()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
async Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember02()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
async Tasks.Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember03()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
UsingTree(@"
class C
{
static async Tasks.Task<
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.GreaterThanToken);
}
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember04()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async operator+
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken); // async
}
N(SyntaxKind.OperatorKeyword);
N(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember05()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async Task<T>
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(609912, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609912")]
[Fact]
public void IncompleteAsyncMember06()
{
// when parsing an incomplete member, treat 'async' as a modifier if it makes sense
// negative case
UsingTree(@"
class C
{
async Task<T> f
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void PropertyAsyncAsync()
{
UsingTree(@"
class C
{
async async { get; set; }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.SetAccessorDeclaration);
{
N(SyntaxKind.SetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void PropertyAsyncAsyncAsync()
{
UsingTree(@"
class C
{
async async async { get; set; }
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.SetAccessorDeclaration);
{
N(SyntaxKind.SetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsync()
{
UsingTree(@"
class C
{
event async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsyncAsync1()
{
UsingTree(@"
class C
{
event async async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void EventAsyncAsyncAsync2()
{
UsingTree(@"
class C
{
async event async async;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventFieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.EventKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void AsyncModifierOnDelegateDeclaration()
{
UsingTree(@"
class C
{
public async delegate void Goo();
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.DelegateDeclaration);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[Fact]
public void NonAsyncLambda()
{
TestVersions(options =>
{
UsingNode("async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncSimpleLambda()
{
TestVersions(options =>
{
UsingNode("async async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncAsyncAsyncAsyncSimpleLambda()
{
TestVersions(options =>
{
UsingNode("async async => async async => async", options);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.SimpleLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
}
});
}
[Fact]
public void NonAsyncParenthesizedLambda()
{
TestVersions(options =>
{
UsingNode("(async) => async", options);
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncAsyncParenthesizedLambda()
{
TestVersions(options =>
{
UsingNode("async (async) => async", options);
N(SyntaxKind.ParenthesizedLambdaExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken);
}
}
});
}
[Fact]
public void AsyncSimpleDelegate()
{
TestVersions(options =>
{
UsingNode("async delegate { }", options);
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
});
}
[Fact]
public void AsyncParenthesizedDelegate()
{
TestVersions(options =>
{
UsingNode("async delegate (int x) { }", options);
N(SyntaxKind.AnonymousMethodExpression);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.DelegateKeyword);
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
});
}
// Comment directly from CParser::IsAsyncMethod.
// ... 'async' [partial] <typedecl> ...
// ... 'async' [partial] <event> ...
// ... 'async' [partial] <implicit> <operator> ...
// ... 'async' [partial] <explicit> <operator> ...
// ... 'async' [partial] <typename> <operator> ...
// ... 'async' [partial] <typename> <membername> ...
// DEVNOTE: Although we parse async user defined conversions, operators, etc. here,
// anything other than async methods are detected as erroneous later, during the define phase
[Fact]
public void AsyncInterface()
{
// ... 'async' <typedecl> ...
UsingTree(@"
class C
{
async interface
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.InterfaceKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialClass()
{
// ... 'async' 'partial' <typedecl> ...
UsingTree(@"
class C
{
async partial class
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PartialKeyword);
N(SyntaxKind.ClassKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncEvent()
{
// ... 'async' <event> ...
UsingTree(@"
class C
{
async event
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.EventDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.EventKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialEvent()
{
// ... 'async' 'partial' <event> ...
UsingTree(@"
class C
{
async partial event
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
}
N(SyntaxKind.EventDeclaration);
{
N(SyntaxKind.EventKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncImplicitOperator()
{
// ... 'async' <implicit> <operator> ...
UsingTree(@"
class C
{
async implicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ConversionOperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ImplicitKeyword);
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialImplicitOperator()
{
// ... 'async' 'partial' <implicit> <operator> ...
UsingTree(@"
class C
{
async partial implicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
M(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncExplicitOperator()
{
// ... 'async' <explicit> <operator> ...
UsingTree(@"
class C
{
async explicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ConversionOperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.ExplicitKeyword);
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialExplicitOperator()
{
// ... 'async' 'partial' <explicit> <operator> ...
UsingTree(@"
class C
{
async partial explicit operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
M(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeOperator()
{
// ... 'async' <typename> <operator> ...
UsingTree(@"
class C
{
async C operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialTypeOperator()
{
// ... 'async' 'partial' <typename> <operator> ...
UsingTree(@"
class C
{
async partial int operator
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "partial");
}
}
N(SyntaxKind.OperatorDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.OperatorKeyword);
M(SyntaxKind.PlusToken);
M(SyntaxKind.ParameterList);
{
M(SyntaxKind.OpenParenToken);
M(SyntaxKind.CloseParenToken);
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncField()
{
// ... 'async' <typename> <membername> ...
UsingTree(@"
class C
{
async C C
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "C");
}
}
M(SyntaxKind.SemicolonToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncPartialIndexer()
{
// ... 'async' 'partial' <typename> <membername> ...
UsingTree(@"
class C
{
async partial C this
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PartialKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.ThisKeyword);
M(SyntaxKind.BracketedParameterList);
{
M(SyntaxKind.OpenBracketToken);
M(SyntaxKind.CloseBracketToken);
}
M(SyntaxKind.AccessorList);
{
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeEndOfFile()
{
UsingTree("class C { async T");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeCloseCurly()
{
UsingTree("class C { async T }");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypePredefinedType()
{
UsingTree(
@"class C {
async T
int");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeModifier()
{
UsingTree(
@"class C {
async T
public");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PublicKeyword);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeFollowedByTypeDecl()
{
UsingTree(
@"class C {
async T
class");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
M(SyntaxKind.IdentifierToken);
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void AsyncTypeFollowedByNamespaceDecl()
{
UsingTree(
@"class C {
async T
namespace");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "T");
}
}
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.NamespaceDeclaration);
{
N(SyntaxKind.NamespaceKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
M(SyntaxKind.OpenBraceToken);
M(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(18621, "https://github.com/dotnet/roslyn/issues/18621")]
public void AsyncGenericType()
{
UsingTree(
@"class Program
{
public async Task<IReadOnlyCollection<ProjectConfiguration>>
}");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IncompleteMember);
{
N(SyntaxKind.PublicKeyword);
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "Task");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "IReadOnlyCollection");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ProjectConfiguration");
}
N(SyntaxKind.GreaterThanToken);
}
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property_ExpressionBody()
{
UsingTree("class async { async async => null; }").GetDiagnostics().Verify(
// (1,27): error CS8026: Feature 'expression-bodied property' is not available in C# 5. Please use language version 6 or greater.
// class async { async async => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied property", "6").WithLocation(1, 27)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property()
{
UsingTree("class async { async async { get; } }").GetDiagnostics().Verify();
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Indexer_ExpressionBody_ErrorCase()
{
UsingTree("interface async { async this[async i] => null; }").GetDiagnostics().Verify(
// (1,39): error CS8026: Feature 'expression-bodied indexer' is not available in C# 5. Please use language version 6 or greater.
// interface async { async this[async i] => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied indexer", "6").WithLocation(1, 39)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.InterfaceKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ThisKeyword);
N(SyntaxKind.BracketedParameterList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Indexer()
{
UsingTree("interface async { async this[async i] { get; } }").GetDiagnostics().Verify();
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.InterfaceDeclaration);
{
N(SyntaxKind.InterfaceKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.IndexerDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ThisKeyword);
N(SyntaxKind.BracketedParameterList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Parameter);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.AccessorList);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.GetAccessorDeclaration);
{
N(SyntaxKind.GetKeyword);
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(16044, "https://github.com/dotnet/roslyn/issues/16044")]
public void AsyncAsType_Property_ExplicitInterface()
{
UsingTree("class async : async { async async.async => null; }").GetDiagnostics().Verify(
// (1,41): error CS8026: Feature 'expression-bodied property' is not available in C# 5. Please use language version 6 or greater.
// class async : async { async async.async => null; }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "=> null").WithArguments("expression-bodied property", "6").WithLocation(1, 41)
);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.BaseList);
{
N(SyntaxKind.ColonToken);
N(SyntaxKind.SimpleBaseType);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
}
}
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.PropertyDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.ExplicitInterfaceSpecifier);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "async");
}
N(SyntaxKind.DotToken);
}
N(SyntaxKind.IdentifierToken, "async");
N(SyntaxKind.ArrowExpressionClause);
{
N(SyntaxKind.EqualsGreaterThanToken);
N(SyntaxKind.NullLiteralExpression);
{
N(SyntaxKind.NullKeyword);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
}
}
| -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/Lowering/LocalRewriter/LocalRewriter_Field.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitFieldAccess(BoundFieldAccess node)
{
BoundExpression? rewrittenReceiver = VisitExpression(node.ReceiverOpt);
return MakeFieldAccess(node.Syntax, rewrittenReceiver, node.FieldSymbol, node.ConstantValue, node.ResultKind, node.Type, node);
}
private BoundExpression MakeFieldAccess(
SyntaxNode syntax,
BoundExpression? rewrittenReceiver,
FieldSymbol fieldSymbol,
ConstantValue? constantValueOpt,
LookupResultKind resultKind,
TypeSymbol type,
BoundFieldAccess? oldNodeOpt = null)
{
if (fieldSymbol.ContainingType.IsTupleType)
{
return MakeTupleFieldAccess(syntax, fieldSymbol, rewrittenReceiver);
}
BoundExpression result = oldNodeOpt != null ?
oldNodeOpt.Update(rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type) :
new BoundFieldAccess(syntax, rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type);
if (fieldSymbol.IsFixedSizeBuffer)
{
// a reference to a fixed buffer is translated into its address
result = new BoundAddressOfOperator(syntax, result, type, false);
}
return result;
}
/// <summary>
/// Converts access to a tuple instance into access into the underlying ValueTuple(s).
///
/// For instance, tuple.Item8
/// produces fieldAccess(field=Item1, receiver=fieldAccess(field=Rest, receiver=ValueTuple for tuple))
/// </summary>
private BoundExpression MakeTupleFieldAccess(
SyntaxNode syntax,
FieldSymbol tupleField,
BoundExpression? rewrittenReceiver)
{
var tupleType = tupleField.ContainingType;
NamedTypeSymbol currentLinkType = tupleType;
FieldSymbol underlyingField = tupleField.TupleUnderlyingField;
if ((object)underlyingField == null)
{
// Use-site error must have been reported elsewhere.
return _factory.BadExpression(tupleField.Type);
}
if (rewrittenReceiver?.Kind == BoundKind.DefaultExpression)
{
// Optimization: `default((int, string)).Item2` is simply `default(string)`
return new BoundDefaultExpression(syntax, tupleField.Type);
}
if (!TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything2))
{
WellKnownMember wellKnownTupleRest = NamedTypeSymbol.GetTupleTypeMember(NamedTypeSymbol.ValueTupleRestPosition, NamedTypeSymbol.ValueTupleRestPosition);
var tupleRestField = (FieldSymbol?)NamedTypeSymbol.GetWellKnownMemberInType(currentLinkType.OriginalDefinition, wellKnownTupleRest, _diagnostics, syntax);
if (tupleRestField is null)
{
// error tolerance for cases when Rest is missing
return _factory.BadExpression(tupleField.Type);
}
// make nested field accesses to Rest
do
{
FieldSymbol nestedFieldSymbol = tupleRestField.AsMember(currentLinkType);
rewrittenReceiver = _factory.Field(rewrittenReceiver, nestedFieldSymbol);
currentLinkType = (NamedTypeSymbol)currentLinkType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[NamedTypeSymbol.ValueTupleRestPosition - 1].Type;
}
while (!TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything2));
}
// make a field access for the most local access
return _factory.Field(rewrittenReceiver, underlyingField);
}
private BoundExpression MakeTupleFieldAccessAndReportUseSiteDiagnostics(BoundExpression tuple, SyntaxNode syntax, FieldSymbol field)
{
// Use default field rather than implicitly named fields since
// fields from inferred names are not usable in C# 7.0.
field = field.CorrespondingTupleField ?? field;
UseSiteInfo<AssemblySymbol> useSiteInfo = field.GetUseSiteInfo();
if (useSiteInfo.DiagnosticInfo?.Severity != DiagnosticSeverity.Error)
{
useSiteInfo = useSiteInfo.AdjustDiagnosticInfo(null);
}
_diagnostics.Add(useSiteInfo, syntax.Location);
return MakeTupleFieldAccess(syntax, field, tuple);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitFieldAccess(BoundFieldAccess node)
{
BoundExpression? rewrittenReceiver = VisitExpression(node.ReceiverOpt);
return MakeFieldAccess(node.Syntax, rewrittenReceiver, node.FieldSymbol, node.ConstantValue, node.ResultKind, node.Type, node);
}
private BoundExpression MakeFieldAccess(
SyntaxNode syntax,
BoundExpression? rewrittenReceiver,
FieldSymbol fieldSymbol,
ConstantValue? constantValueOpt,
LookupResultKind resultKind,
TypeSymbol type,
BoundFieldAccess? oldNodeOpt = null)
{
if (fieldSymbol.ContainingType.IsTupleType)
{
return MakeTupleFieldAccess(syntax, fieldSymbol, rewrittenReceiver);
}
BoundExpression result = oldNodeOpt != null ?
oldNodeOpt.Update(rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type) :
new BoundFieldAccess(syntax, rewrittenReceiver, fieldSymbol, constantValueOpt, resultKind, type);
if (fieldSymbol.IsFixedSizeBuffer)
{
// a reference to a fixed buffer is translated into its address
result = new BoundAddressOfOperator(syntax, result, type, false);
}
return result;
}
/// <summary>
/// Converts access to a tuple instance into access into the underlying ValueTuple(s).
///
/// For instance, tuple.Item8
/// produces fieldAccess(field=Item1, receiver=fieldAccess(field=Rest, receiver=ValueTuple for tuple))
/// </summary>
private BoundExpression MakeTupleFieldAccess(
SyntaxNode syntax,
FieldSymbol tupleField,
BoundExpression? rewrittenReceiver)
{
var tupleType = tupleField.ContainingType;
NamedTypeSymbol currentLinkType = tupleType;
FieldSymbol underlyingField = tupleField.TupleUnderlyingField;
if ((object)underlyingField == null)
{
// Use-site error must have been reported elsewhere.
return _factory.BadExpression(tupleField.Type);
}
if (rewrittenReceiver?.Kind == BoundKind.DefaultExpression)
{
// Optimization: `default((int, string)).Item2` is simply `default(string)`
return new BoundDefaultExpression(syntax, tupleField.Type);
}
if (!TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything2))
{
WellKnownMember wellKnownTupleRest = NamedTypeSymbol.GetTupleTypeMember(NamedTypeSymbol.ValueTupleRestPosition, NamedTypeSymbol.ValueTupleRestPosition);
var tupleRestField = (FieldSymbol?)NamedTypeSymbol.GetWellKnownMemberInType(currentLinkType.OriginalDefinition, wellKnownTupleRest, _diagnostics, syntax);
if (tupleRestField is null)
{
// error tolerance for cases when Rest is missing
return _factory.BadExpression(tupleField.Type);
}
// make nested field accesses to Rest
do
{
FieldSymbol nestedFieldSymbol = tupleRestField.AsMember(currentLinkType);
rewrittenReceiver = _factory.Field(rewrittenReceiver, nestedFieldSymbol);
currentLinkType = (NamedTypeSymbol)currentLinkType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[NamedTypeSymbol.ValueTupleRestPosition - 1].Type;
}
while (!TypeSymbol.Equals(underlyingField.ContainingType, currentLinkType, TypeCompareKind.ConsiderEverything2));
}
// make a field access for the most local access
return _factory.Field(rewrittenReceiver, underlyingField);
}
private BoundExpression MakeTupleFieldAccessAndReportUseSiteDiagnostics(BoundExpression tuple, SyntaxNode syntax, FieldSymbol field)
{
// Use default field rather than implicitly named fields since
// fields from inferred names are not usable in C# 7.0.
field = field.CorrespondingTupleField ?? field;
UseSiteInfo<AssemblySymbol> useSiteInfo = field.GetUseSiteInfo();
if (useSiteInfo.DiagnosticInfo?.Severity != DiagnosticSeverity.Error)
{
useSiteInfo = useSiteInfo.AdjustDiagnosticInfo(null);
}
_diagnostics.Add(useSiteInfo, syntax.Location);
return MakeTupleFieldAccess(syntax, field, tuple);
}
}
}
| -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/Interactive/InteractiveEvaluatorLanguageInfoProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
internal abstract class InteractiveEvaluatorLanguageInfoProvider
{
public abstract string LanguageName { get; }
public abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver, ImmutableArray<string> imports);
public abstract ParseOptions ParseOptions { get; }
public abstract CommandLineParser CommandLineParser { get; }
public abstract bool IsCompleteSubmission(string text);
public abstract string InteractiveResponseFileName { get; }
public abstract Type ReplServiceProviderType { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.Editor.Interactive
{
internal abstract class InteractiveEvaluatorLanguageInfoProvider
{
public abstract string LanguageName { get; }
public abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver, ImmutableArray<string> imports);
public abstract ParseOptions ParseOptions { get; }
public abstract CommandLineParser CommandLineParser { get; }
public abstract bool IsCompleteSubmission(string text);
public abstract string InteractiveResponseFileName { get; }
public abstract Type ReplServiceProviderType { get; }
}
}
| -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/IntelliSense/AsyncCompletion/ItemManager.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.PatternMatching;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem;
using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion
{
internal class ItemManager : IAsyncCompletionItemManager
{
/// <summary>
/// Used for filtering non-Roslyn data only.
/// </summary>
private readonly CompletionHelper _defaultCompletionHelper;
private readonly RecentItemsManager _recentItemsManager;
/// <summary>
/// For telemetry.
/// </summary>
private readonly object _targetTypeCompletionFilterChosenMarker = new();
internal ItemManager(RecentItemsManager recentItemsManager)
{
// Let us make the completion Helper used for non-Roslyn items case-sensitive.
// We can change this if get requests from partner teams.
_defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true);
_recentItemsManager = recentItemsManager;
}
public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync(
IAsyncCompletionSession session,
AsyncCompletionSessionInitialDataSnapshot data,
CancellationToken cancellationToken)
{
if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isTargetTypeFilterEnabled) && isTargetTypeFilterEnabled)
{
AsyncCompletionLogger.LogSessionHasTargetTypeFilterEnabled();
// This method is called exactly once, so use the opportunity to set a baseline for telemetry.
if (data.InitialList.Any(i => i.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)))
{
AsyncCompletionLogger.LogSessionContainsTargetTypeFilter();
}
}
if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTypeImportCompletionEnabled) && isTypeImportCompletionEnabled)
{
AsyncCompletionLogger.LogSessionWithTypeImportCompletionEnabled();
}
// Sort by default comparer of Roslyn CompletionItem
var sortedItems = data.InitialList.OrderBy(GetOrAddRoslynCompletionItem).ToImmutableArray();
return Task.FromResult(sortedItems);
}
public Task<FilteredCompletionModel?> UpdateCompletionListAsync(
IAsyncCompletionSession session,
AsyncCompletionSessionDataSnapshot data,
CancellationToken cancellationToken)
=> Task.FromResult(UpdateCompletionList(session, data, cancellationToken));
// We might need to handle large amount of items with import completion enabled,
// so use a dedicated pool to minimize/avoid array allocations (especially in LOH)
// Set the size of pool to 1 because we don't expect UpdateCompletionListAsync to be
// called concurrently, which essentially makes the pooled list a singleton,
// but we still use ObjectPool for concurrency handling just to be robust.
private static readonly ObjectPool<List<MatchResult<VSCompletionItem>>> s_listOfMatchResultPool
= new(factory: () => new(), size: 1);
private FilteredCompletionModel? UpdateCompletionList(
IAsyncCompletionSession session,
AsyncCompletionSessionDataSnapshot data,
CancellationToken cancellationToken)
{
if (!session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions))
{
// This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger.
// For now, the default hasSuggestedItemOptions is false.
hasSuggestedItemOptions = false;
}
hasSuggestedItemOptions |= data.DisplaySuggestionItem;
var filterText = session.ApplicableToSpan.GetText(data.Snapshot);
var reason = data.Trigger.Reason;
var initialRoslynTriggerKind = Helpers.GetRoslynTriggerKind(data.InitialTrigger);
// Check if the user is typing a number. If so, only proceed if it's a number
// directly after a <dot>. That's because it is actually reasonable for completion
// to be brought up after a <dot> and for the user to want to filter completion
// items based on a number that exists in the name of the item. However, when
// we are not after a dot (i.e. we're being brought up after <space> is typed)
// then we don't want to filter things. Consider the user writing:
//
// dim i =<space>
//
// We'll bring up the completion list here (as VB has completion on <space>).
// If the user then types '3', we don't want to match against Int32.
if (filterText.Length > 0 && char.IsNumber(filterText[0]))
{
if (!IsAfterDot(data.Snapshot, session.ApplicableToSpan))
{
// Dismiss the session.
return null;
}
}
// We need to filter if
// 1. a non-empty strict subset of filters are selected
// 2. a non-empty set of expanders are unselected
var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander));
var selectedNonExpanderFilters = nonExpanderFilterStates.SelectAsArray(f => f.IsSelected, f => f.Filter);
var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length;
var unselectedExpanders = data.SelectedFilters.SelectAsArray(f => !f.IsSelected && f.Filter is CompletionExpander, f => f.Filter);
var needToFilterExpanded = unselectedExpanders.Length > 0;
if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled)
{
// Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled
if (needToFilter &&
!session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) &&
selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches))
{
AsyncCompletionLogger.LogTargetTypeFilterChosenInSession();
// Make sure we only record one enabling of the filter per session
session.Properties.AddProperty(_targetTypeCompletionFilterChosenMarker, _targetTypeCompletionFilterChosenMarker);
}
}
var filterReason = Helpers.GetFilterReason(data.Trigger);
// We prefer using the original snapshot, which should always be available from items provided by Roslyn's CompletionSource.
// Only use data.Snapshot in the theoretically possible but rare case when all items we are handling are from some non-Roslyn CompletionSource.
var snapshotForDocument = TryGetInitialTriggerLocation(data, out var intialTriggerLocation)
? intialTriggerLocation.Snapshot
: data.Snapshot;
var document = snapshotForDocument?.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
var completionService = document?.GetLanguageService<CompletionService>();
var completionRules = completionService?.GetRules() ?? CompletionRules.Default;
var completionHelper = document != null ? CompletionHelper.GetHelper(document) : _defaultCompletionHelper;
// DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed.
// This conforms with the original VS 2010 behavior.
if (initialRoslynTriggerKind == CompletionTriggerKind.Insertion &&
data.Trigger.Reason == CompletionTriggerReason.Backspace &&
completionRules.DismissIfLastCharacterDeleted &&
session.ApplicableToSpan.GetText(data.Snapshot).Length == 0)
{
// Dismiss the session
return null;
}
var options = document?.Project.Solution.Options;
var highlightMatchingPortions = options?.GetOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, document?.Project.Language) ?? false;
// Nothing to highlight if user hasn't typed anything yet.
highlightMatchingPortions = highlightMatchingPortions && filterText.Length > 0;
// Use a monotonically increasing integer to keep track the original alphabetical order of each item.
var currentIndex = 0;
var initialListOfItemsToBeIncluded = s_listOfMatchResultPool.Allocate();
try
{
// Filter items based on the selected filters and matching.
foreach (var item in data.InitialSortedList)
{
cancellationToken.ThrowIfCancellationRequested();
if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters))
{
continue;
}
if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders))
{
continue;
}
if (TryCreateMatchResult(
completionHelper,
item,
filterText,
initialRoslynTriggerKind,
filterReason,
_recentItemsManager.RecentItems,
highlightMatchingPortions: highlightMatchingPortions,
currentIndex,
out var matchResult))
{
initialListOfItemsToBeIncluded.Add(matchResult);
currentIndex++;
}
}
if (initialListOfItemsToBeIncluded.Count == 0)
{
return HandleAllItemsFilteredOut(reason, data.SelectedFilters, completionRules);
}
// Sort the items by pattern matching results.
// Note that we want to preserve the original alphabetical order for items with same pattern match score,
// but `List<T>.Sort` isn't stable. Therefore we have to add a monotonically increasing integer
// to `MatchResult` to achieve this.
initialListOfItemsToBeIncluded.Sort(MatchResult<VSCompletionItem>.SortingComparer);
var showCompletionItemFilters = options?.GetOption(CompletionOptions.ShowCompletionItemFilters, document?.Project.Language) ?? true;
var updatedFilters = showCompletionItemFilters
? GetUpdatedFilters(initialListOfItemsToBeIncluded, data.SelectedFilters)
: ImmutableArray<CompletionFilterWithState>.Empty;
// If this was deletion, then we control the entire behavior of deletion ourselves.
if (initialRoslynTriggerKind == CompletionTriggerKind.Deletion)
{
return HandleDeletionTrigger(reason, initialListOfItemsToBeIncluded, filterText, updatedFilters, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper);
}
Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod;
if (completionService == null)
{
filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(completionHelper, itemsWithPatternMatches, text);
}
else
{
filterMethod = (itemsWithPatternMatches, text) => completionService.FilterItems(document, itemsWithPatternMatches, text);
}
return HandleNormalFiltering(
filterMethod,
filterText,
updatedFilters,
filterReason,
data.Trigger.Character,
initialListOfItemsToBeIncluded,
hasSuggestedItemOptions,
highlightMatchingPortions,
completionHelper);
}
finally
{
// Don't call ClearAndFree, which resets the capacity to a default value.
initialListOfItemsToBeIncluded.Clear();
s_listOfMatchResultPool.Free(initialListOfItemsToBeIncluded);
}
static bool TryGetInitialTriggerLocation(AsyncCompletionSessionDataSnapshot data, out SnapshotPoint intialTriggerLocation)
{
var firstItem = data.InitialSortedList.FirstOrDefault(static item => item.Properties.ContainsProperty(CompletionSource.TriggerLocation));
if (firstItem != null)
{
return firstItem.Properties.TryGetProperty(CompletionSource.TriggerLocation, out intialTriggerLocation);
}
intialTriggerLocation = default;
return false;
}
static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> activeNonExpanderFilters)
{
if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter)))
{
return false;
}
return true;
}
static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> unselectedExpanders)
{
var associatedWithUnselectedExpander = false;
foreach (var itemFilter in item.Filters)
{
if (itemFilter is CompletionExpander)
{
if (!unselectedExpanders.Contains(itemFilter))
{
// If any of the associated expander is selected, the item should be included in the expanded list.
return false;
}
associatedWithUnselectedExpander = true;
}
}
// at this point, the item either:
// 1. has no expander filter, therefore should be included
// 2. or, all associated expanders are unselected, therefore should be excluded
return associatedWithUnselectedExpander;
}
}
private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan)
{
var position = applicableToSpan.GetStartPoint(snapshot).Position;
return position > 0 && snapshot[position - 1] == '.';
}
private FilteredCompletionModel? HandleNormalFiltering(
Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod,
string filterText,
ImmutableArray<CompletionFilterWithState> filters,
CompletionFilterReason filterReason,
char typeChar,
List<MatchResult<VSCompletionItem>> itemsInList,
bool hasSuggestedItemOptions,
bool highlightMatchingPortions,
CompletionHelper completionHelper)
{
// Not deletion. Defer to the language to decide which item it thinks best
// matches the text typed so far.
// Ask the language to determine which of the *matched* items it wants to select.
var matchingItems = itemsInList.Where(r => r.MatchedFilterText)
.SelectAsArray(t => (t.RoslynCompletionItem, t.PatternMatch));
var chosenItems = filterMethod(matchingItems, filterText);
int selectedItemIndex;
VSCompletionItem? uniqueItem = null;
MatchResult<VSCompletionItem> bestOrFirstMatchResult;
if (chosenItems.Length == 0)
{
// We do not have matches: pick the one with longest common prefix or the first item from the list.
selectedItemIndex = 0;
bestOrFirstMatchResult = itemsInList[0];
var longestCommonPrefixLength = bestOrFirstMatchResult.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText);
for (var i = 1; i < itemsInList.Count; ++i)
{
var item = itemsInList[i];
var commonPrefixLength = item.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText);
if (commonPrefixLength > longestCommonPrefixLength)
{
selectedItemIndex = i;
bestOrFirstMatchResult = item;
longestCommonPrefixLength = commonPrefixLength;
}
}
}
else
{
var recentItems = _recentItemsManager.RecentItems;
// Of the items the service returned, pick the one most recently committed
var bestItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems);
// Determine if we should consider this item 'unique' or not. A unique item
// will be automatically committed if the user hits the 'invoke completion'
// without bringing up the completion list. An item is unique if it was the
// only item to match the text typed so far, and there was at least some text
// typed. i.e. if we have "Console.$$" we don't want to commit something
// like "WriteLine" since no filter text has actually been provided. However,
// if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed.
selectedItemIndex = itemsInList.IndexOf(i => Equals(i.RoslynCompletionItem, bestItem));
bestOrFirstMatchResult = itemsInList[selectedItemIndex];
var deduplicatedListCount = matchingItems.Count(r => !r.RoslynCompletionItem.IsPreferredItem());
if (deduplicatedListCount == 1 &&
filterText.Length > 0)
{
uniqueItem = itemsInList[selectedItemIndex].EditorCompletionItem;
}
}
// Check that it is a filter symbol. We can be called for a non-filter symbol.
// If inserting a non-filter character (neither IsPotentialFilterCharacter, nor Helpers.IsFilterCharacter), we should dismiss completion
// except cases where this is the first symbol typed for the completion session (string.IsNullOrEmpty(filterText) or string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase)).
// In the latter case, we should keep the completion because it was confirmed just before in InitializeCompletion.
if (filterReason == CompletionFilterReason.Insertion &&
!string.IsNullOrEmpty(filterText) &&
!string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase) &&
!IsPotentialFilterCharacter(typeChar) &&
!Helpers.IsFilterCharacter(bestOrFirstMatchResult.RoslynCompletionItem, typeChar, filterText))
{
return null;
}
var isHardSelection = IsHardSelection(
filterText, bestOrFirstMatchResult.RoslynCompletionItem, bestOrFirstMatchResult.MatchedFilterText, hasSuggestedItemOptions);
var updateSelectionHint = isHardSelection ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected;
return new FilteredCompletionModel(
GetHighlightedList(itemsInList, filterText, highlightMatchingPortions, completionHelper), selectedItemIndex, filters,
updateSelectionHint, centerSelection: true, uniqueItem);
}
private static FilteredCompletionModel? HandleDeletionTrigger(
CompletionTriggerReason filterTriggerKind,
List<MatchResult<VSCompletionItem>> matchResults,
string filterText,
ImmutableArray<CompletionFilterWithState> filters,
bool hasSuggestedItemOptions,
bool highlightMatchingSpans,
CompletionHelper completionHelper)
{
var matchingItems = matchResults.Where(r => r.MatchedFilterText);
if (filterTriggerKind == CompletionTriggerReason.Insertion &&
!matchingItems.Any())
{
// The user has typed something, but nothing in the actual list matched what
// they were typing. In this case, we want to dismiss completion entirely.
// The thought process is as follows: we aggressively brought up completion
// to help them when they typed delete (in case they wanted to pick another
// item). However, they're typing something that doesn't seem to match at all
// The completion list is just distracting at this point.
return null;
}
MatchResult<VSCompletionItem>? bestMatchResult = null;
var moreThanOneMatchWithSamePriority = false;
foreach (var currentMatchResult in matchingItems)
{
if (bestMatchResult == null)
{
// We had no best result yet, so this is now our best result.
bestMatchResult = currentMatchResult;
}
else
{
var match = currentMatchResult.CompareTo(bestMatchResult.Value, filterText);
if (match > 0)
{
moreThanOneMatchWithSamePriority = false;
bestMatchResult = currentMatchResult;
}
else if (match == 0)
{
moreThanOneMatchWithSamePriority = true;
}
}
}
int index;
bool hardSelect;
// If we had a matching item, then pick the best of the matching items and
// choose that one to be hard selected. If we had no actual matching items
// (which can happen if the user deletes down to a single character and we
// include everything), then we just soft select the first item.
if (bestMatchResult != null)
{
// Only hard select this result if it's a prefix match
// We need to do this so that
// * deleting and retyping a dot in a member access does not change the
// text that originally appeared before the dot
// * deleting through a word from the end keeps that word selected
// This also preserves the behavior the VB had through Dev12.
hardSelect = !hasSuggestedItemOptions && bestMatchResult.Value.EditorCompletionItem.FilterText.StartsWith(filterText, StringComparison.CurrentCultureIgnoreCase);
index = matchResults.IndexOf(bestMatchResult.Value);
}
else
{
index = 0;
hardSelect = false;
}
return new FilteredCompletionModel(
GetHighlightedList(matchResults, filterText, highlightMatchingSpans, completionHelper), index, filters,
hardSelect ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected,
centerSelection: true,
uniqueItem: moreThanOneMatchWithSamePriority ? null : bestMatchResult.GetValueOrDefault().EditorCompletionItem);
}
private static ImmutableArray<CompletionItemWithHighlight> GetHighlightedList(
List<MatchResult<VSCompletionItem>> matchResults,
string filterText,
bool highlightMatchingPortions,
CompletionHelper completionHelper)
{
return matchResults.SelectAsArray(matchResult =>
{
var highlightedSpans = GetHighlightedSpans(matchResult, completionHelper, filterText, highlightMatchingPortions);
return new CompletionItemWithHighlight(matchResult.EditorCompletionItem, highlightedSpans);
});
static ImmutableArray<Span> GetHighlightedSpans(
MatchResult<VSCompletionItem> matchResult,
CompletionHelper completionHelper,
string filterText,
bool highlightMatchingPortions)
{
if (highlightMatchingPortions)
{
if (matchResult.RoslynCompletionItem.HasDifferentFilterText)
{
// The PatternMatch in MatchResult is calculated based on Roslyn item's FilterText,
// which can be used to calculate highlighted span for VSCompletion item's DisplayText w/o doing the matching again.
// However, if the Roslyn item's FilterText is different from its DisplayText,
// we need to do the match against the display text of the VS item directly to get the highlighted spans.
return completionHelper.GetHighlightedSpans(
matchResult.EditorCompletionItem.DisplayText, filterText, CultureInfo.CurrentCulture).SelectAsArray(s => s.ToSpan());
}
var patternMatch = matchResult.PatternMatch;
if (patternMatch.HasValue)
{
// Since VS item's display text is created as Prefix + DisplayText + Suffix,
// we can calculate the highlighted span by adding an offset that is the length of the Prefix.
return patternMatch.Value.MatchedSpans.SelectAsArray(s_highlightSpanGetter, matchResult.RoslynCompletionItem);
}
}
// If there's no match for Roslyn item's filter text which is identical to its display text,
// then we can safely assume there'd be no matching to VS item's display text.
return ImmutableArray<Span>.Empty;
}
}
private static FilteredCompletionModel? HandleAllItemsFilteredOut(
CompletionTriggerReason triggerReason,
ImmutableArray<CompletionFilterWithState> filters,
CompletionRules completionRules)
{
if (triggerReason == CompletionTriggerReason.Insertion)
{
// If the user was just typing, and the list went to empty *and* this is a
// language that wants to dismiss on empty, then just return a null model
// to stop the completion session.
if (completionRules.DismissIfEmpty)
{
return null;
}
}
// If the user has turned on some filtering states, and we filtered down to
// nothing, then we do want the UI to show that to them. That way the user
// can turn off filters they don't want and get the right set of items.
// If we are going to filter everything out, then just preserve the existing
// model (and all the previously filtered items), but switch over to soft
// selection.
var selection = UpdateSelectionHint.SoftSelected;
return new FilteredCompletionModel(
ImmutableArray<CompletionItemWithHighlight>.Empty, selectedItemIndex: 0,
filters, selection, centerSelection: true, uniqueItem: null);
}
private static ImmutableArray<CompletionFilterWithState> GetUpdatedFilters(
List<MatchResult<VSCompletionItem>> filteredList,
ImmutableArray<CompletionFilterWithState> filters)
{
// See which filters might be enabled based on the typed code
using var _ = PooledHashSet<CompletionFilter>.GetInstance(out var textFilteredFilters);
textFilteredFilters.AddRange(filteredList.SelectMany(n => n.EditorCompletionItem.Filters));
// When no items are available for a given filter, it becomes unavailable.
// Expanders always appear available as long as it's presented.
return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter)));
}
/// <summary>
/// Given multiple possible chosen completion items, pick the one that has the
/// best MRU index, or the one with highest MatchPriority if none in MRU.
/// </summary>
private static RoslynCompletionItem GetBestCompletionItemBasedOnMRU(
ImmutableArray<RoslynCompletionItem> chosenItems, ImmutableArray<string> recentItems)
{
Debug.Assert(chosenItems.Length > 0);
// Try to find the chosen item has been most recently used.
var bestItem = chosenItems[0];
for (int i = 1, n = chosenItems.Length; i < n; i++)
{
var chosenItem = chosenItems[i];
var mruIndex1 = GetRecentItemIndex(recentItems, bestItem);
var mruIndex2 = GetRecentItemIndex(recentItems, chosenItem);
if ((mruIndex2 < mruIndex1) ||
(mruIndex2 == mruIndex1 && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem()))
{
bestItem = chosenItem;
}
}
// If our best item appeared in the MRU list, use it
if (GetRecentItemIndex(recentItems, bestItem) <= 0)
{
return bestItem;
}
// Otherwise use the chosen item that has the highest
// matchPriority.
for (int i = 1, n = chosenItems.Length; i < n; i++)
{
var chosenItem = chosenItems[i];
var bestItemPriority = bestItem.Rules.MatchPriority;
var currentItemPriority = chosenItem.Rules.MatchPriority;
if ((currentItemPriority > bestItemPriority) ||
((currentItemPriority == bestItemPriority) && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem()))
{
bestItem = chosenItem;
}
}
return bestItem;
}
private static int GetRecentItemIndex(ImmutableArray<string> recentItems, RoslynCompletionItem item)
{
var index = recentItems.IndexOf(item.FilterText);
return -index;
}
private static RoslynCompletionItem GetOrAddRoslynCompletionItem(VSCompletionItem vsItem)
{
if (!vsItem.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem))
{
roslynItem = RoslynCompletionItem.Create(
displayText: vsItem.DisplayText,
filterText: vsItem.FilterText,
sortText: vsItem.SortText,
displayTextSuffix: vsItem.Suffix);
vsItem.Properties.AddProperty(CompletionSource.RoslynItem, roslynItem);
}
return roslynItem;
}
private static bool TryCreateMatchResult(
CompletionHelper completionHelper,
VSCompletionItem item,
string filterText,
CompletionTriggerKind initialTriggerKind,
CompletionFilterReason filterReason,
ImmutableArray<string> recentItems,
bool highlightMatchingPortions,
int currentIndex,
out MatchResult<VSCompletionItem> matchResult)
{
var roslynItem = GetOrAddRoslynCompletionItem(item);
return CompletionHelper.TryCreateMatchResult(completionHelper, roslynItem, item, filterText, initialTriggerKind, filterReason, recentItems, highlightMatchingPortions, currentIndex, out matchResult);
}
// PERF: Create a singleton to avoid lambda allocation on hot path
private static readonly Func<TextSpan, RoslynCompletionItem, Span> s_highlightSpanGetter
= (span, item) => span.MoveTo(item.DisplayTextPrefix?.Length ?? 0).ToSpan();
private static bool IsHardSelection(
string filterText,
RoslynCompletionItem item,
bool matchedFilterText,
bool useSuggestionMode)
{
if (item == null || useSuggestionMode)
{
return false;
}
// We don't have a builder and we have a best match. Normally this will be hard
// selected, except for a few cases. Specifically, if no filter text has been
// provided, and this is not a preselect match then we will soft select it. This
// happens when the completion list comes up implicitly and there is something in
// the MRU list. In this case we do want to select it, but not with a hard
// selection. Otherwise you can end up with the following problem:
//
// dim i as integer =<space>
//
// Completion will comes up after = with 'integer' selected (Because of MRU). We do
// not want 'space' to commit this.
// If all that has been typed is punctuation, then don't hard select anything.
// It's possible the user is just typing language punctuation and selecting
// anything in the list will interfere. We only allow this if the filter text
// exactly matches something in the list already.
if (filterText.Length > 0 && IsAllPunctuation(filterText) && filterText != item.DisplayText)
{
return false;
}
// If the user hasn't actually typed anything, then don't hard select any item.
// The only exception to this is if the completion provider has requested the
// item be preselected.
if (filterText.Length == 0)
{
// Item didn't want to be hard selected with no filter text.
// So definitely soft select it.
if (item.Rules.SelectionBehavior != CompletionItemSelectionBehavior.HardSelection)
{
return false;
}
// Item did not ask to be preselected. So definitely soft select it.
if (item.Rules.MatchPriority == MatchPriority.Default)
{
return false;
}
}
// The user typed something, or the item asked to be preselected. In
// either case, don't soft select this.
Debug.Assert(filterText.Length > 0 || item.Rules.MatchPriority != MatchPriority.Default);
// If the user moved the caret left after they started typing, the 'best' match may not match at all
// against the full text span that this item would be replacing.
if (!matchedFilterText)
{
return false;
}
// There was either filter text, or this was a preselect match. In either case, we
// can hard select this.
return true;
}
private static bool IsAllPunctuation(string filterText)
{
foreach (var ch in filterText)
{
if (!char.IsPunctuation(ch))
{
return false;
}
}
return true;
}
/// <summary>
/// A potential filter character is something that can filter a completion lists and is
/// *guaranteed* to not be a commit character.
/// </summary>
private static bool IsPotentialFilterCharacter(char c)
{
// TODO(cyrusn): Actually use the right Unicode categories here.
return char.IsLetter(c)
|| char.IsNumber(c)
|| c == '_';
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.PatternMatching;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem;
using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion
{
internal class ItemManager : IAsyncCompletionItemManager
{
/// <summary>
/// Used for filtering non-Roslyn data only.
/// </summary>
private readonly CompletionHelper _defaultCompletionHelper;
private readonly RecentItemsManager _recentItemsManager;
/// <summary>
/// For telemetry.
/// </summary>
private readonly object _targetTypeCompletionFilterChosenMarker = new();
internal ItemManager(RecentItemsManager recentItemsManager)
{
// Let us make the completion Helper used for non-Roslyn items case-sensitive.
// We can change this if get requests from partner teams.
_defaultCompletionHelper = new CompletionHelper(isCaseSensitive: true);
_recentItemsManager = recentItemsManager;
}
public Task<ImmutableArray<VSCompletionItem>> SortCompletionListAsync(
IAsyncCompletionSession session,
AsyncCompletionSessionInitialDataSnapshot data,
CancellationToken cancellationToken)
{
if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isTargetTypeFilterEnabled) && isTargetTypeFilterEnabled)
{
AsyncCompletionLogger.LogSessionHasTargetTypeFilterEnabled();
// This method is called exactly once, so use the opportunity to set a baseline for telemetry.
if (data.InitialList.Any(i => i.Filters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches)))
{
AsyncCompletionLogger.LogSessionContainsTargetTypeFilter();
}
}
if (session.TextView.Properties.TryGetProperty(CompletionSource.TypeImportCompletionEnabled, out bool isTypeImportCompletionEnabled) && isTypeImportCompletionEnabled)
{
AsyncCompletionLogger.LogSessionWithTypeImportCompletionEnabled();
}
// Sort by default comparer of Roslyn CompletionItem
var sortedItems = data.InitialList.OrderBy(GetOrAddRoslynCompletionItem).ToImmutableArray();
return Task.FromResult(sortedItems);
}
public Task<FilteredCompletionModel?> UpdateCompletionListAsync(
IAsyncCompletionSession session,
AsyncCompletionSessionDataSnapshot data,
CancellationToken cancellationToken)
=> Task.FromResult(UpdateCompletionList(session, data, cancellationToken));
// We might need to handle large amount of items with import completion enabled,
// so use a dedicated pool to minimize/avoid array allocations (especially in LOH)
// Set the size of pool to 1 because we don't expect UpdateCompletionListAsync to be
// called concurrently, which essentially makes the pooled list a singleton,
// but we still use ObjectPool for concurrency handling just to be robust.
private static readonly ObjectPool<List<MatchResult<VSCompletionItem>>> s_listOfMatchResultPool
= new(factory: () => new(), size: 1);
private FilteredCompletionModel? UpdateCompletionList(
IAsyncCompletionSession session,
AsyncCompletionSessionDataSnapshot data,
CancellationToken cancellationToken)
{
if (!session.Properties.TryGetProperty(CompletionSource.HasSuggestionItemOptions, out bool hasSuggestedItemOptions))
{
// This is the scenario when the session is created out of Roslyn, in some other provider, e.g. in Debugger.
// For now, the default hasSuggestedItemOptions is false.
hasSuggestedItemOptions = false;
}
hasSuggestedItemOptions |= data.DisplaySuggestionItem;
var filterText = session.ApplicableToSpan.GetText(data.Snapshot);
var reason = data.Trigger.Reason;
var initialRoslynTriggerKind = Helpers.GetRoslynTriggerKind(data.InitialTrigger);
// Check if the user is typing a number. If so, only proceed if it's a number
// directly after a <dot>. That's because it is actually reasonable for completion
// to be brought up after a <dot> and for the user to want to filter completion
// items based on a number that exists in the name of the item. However, when
// we are not after a dot (i.e. we're being brought up after <space> is typed)
// then we don't want to filter things. Consider the user writing:
//
// dim i =<space>
//
// We'll bring up the completion list here (as VB has completion on <space>).
// If the user then types '3', we don't want to match against Int32.
if (filterText.Length > 0 && char.IsNumber(filterText[0]))
{
if (!IsAfterDot(data.Snapshot, session.ApplicableToSpan))
{
// Dismiss the session.
return null;
}
}
// We need to filter if
// 1. a non-empty strict subset of filters are selected
// 2. a non-empty set of expanders are unselected
var nonExpanderFilterStates = data.SelectedFilters.WhereAsArray(f => !(f.Filter is CompletionExpander));
var selectedNonExpanderFilters = nonExpanderFilterStates.SelectAsArray(f => f.IsSelected, f => f.Filter);
var needToFilter = selectedNonExpanderFilters.Length > 0 && selectedNonExpanderFilters.Length < nonExpanderFilterStates.Length;
var unselectedExpanders = data.SelectedFilters.SelectAsArray(f => !f.IsSelected && f.Filter is CompletionExpander, f => f.Filter);
var needToFilterExpanded = unselectedExpanders.Length > 0;
if (session.TextView.Properties.TryGetProperty(CompletionSource.TargetTypeFilterExperimentEnabled, out bool isExperimentEnabled) && isExperimentEnabled)
{
// Telemetry: Want to know % of sessions with the "Target type matches" filter where that filter is actually enabled
if (needToFilter &&
!session.Properties.ContainsProperty(_targetTypeCompletionFilterChosenMarker) &&
selectedNonExpanderFilters.Any(f => f.DisplayText == FeaturesResources.Target_type_matches))
{
AsyncCompletionLogger.LogTargetTypeFilterChosenInSession();
// Make sure we only record one enabling of the filter per session
session.Properties.AddProperty(_targetTypeCompletionFilterChosenMarker, _targetTypeCompletionFilterChosenMarker);
}
}
var filterReason = Helpers.GetFilterReason(data.Trigger);
// We prefer using the original snapshot, which should always be available from items provided by Roslyn's CompletionSource.
// Only use data.Snapshot in the theoretically possible but rare case when all items we are handling are from some non-Roslyn CompletionSource.
var snapshotForDocument = TryGetInitialTriggerLocation(data, out var intialTriggerLocation)
? intialTriggerLocation.Snapshot
: data.Snapshot;
var document = snapshotForDocument?.TextBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
var completionService = document?.GetLanguageService<CompletionService>();
var completionRules = completionService?.GetRules() ?? CompletionRules.Default;
var completionHelper = document != null ? CompletionHelper.GetHelper(document) : _defaultCompletionHelper;
// DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed.
// This conforms with the original VS 2010 behavior.
if (initialRoslynTriggerKind == CompletionTriggerKind.Insertion &&
data.Trigger.Reason == CompletionTriggerReason.Backspace &&
completionRules.DismissIfLastCharacterDeleted &&
session.ApplicableToSpan.GetText(data.Snapshot).Length == 0)
{
// Dismiss the session
return null;
}
var options = document?.Project.Solution.Options;
var highlightMatchingPortions = options?.GetOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems, document?.Project.Language) ?? false;
// Nothing to highlight if user hasn't typed anything yet.
highlightMatchingPortions = highlightMatchingPortions && filterText.Length > 0;
// Use a monotonically increasing integer to keep track the original alphabetical order of each item.
var currentIndex = 0;
var initialListOfItemsToBeIncluded = s_listOfMatchResultPool.Allocate();
try
{
// Filter items based on the selected filters and matching.
foreach (var item in data.InitialSortedList)
{
cancellationToken.ThrowIfCancellationRequested();
if (needToFilter && ShouldBeFilteredOutOfCompletionList(item, selectedNonExpanderFilters))
{
continue;
}
if (needToFilterExpanded && ShouldBeFilteredOutOfExpandedCompletionList(item, unselectedExpanders))
{
continue;
}
if (TryCreateMatchResult(
completionHelper,
item,
filterText,
initialRoslynTriggerKind,
filterReason,
_recentItemsManager.RecentItems,
highlightMatchingPortions: highlightMatchingPortions,
currentIndex,
out var matchResult))
{
initialListOfItemsToBeIncluded.Add(matchResult);
currentIndex++;
}
}
if (initialListOfItemsToBeIncluded.Count == 0)
{
return HandleAllItemsFilteredOut(reason, data.SelectedFilters, completionRules);
}
// Sort the items by pattern matching results.
// Note that we want to preserve the original alphabetical order for items with same pattern match score,
// but `List<T>.Sort` isn't stable. Therefore we have to add a monotonically increasing integer
// to `MatchResult` to achieve this.
initialListOfItemsToBeIncluded.Sort(MatchResult<VSCompletionItem>.SortingComparer);
var showCompletionItemFilters = options?.GetOption(CompletionOptions.ShowCompletionItemFilters, document?.Project.Language) ?? true;
var updatedFilters = showCompletionItemFilters
? GetUpdatedFilters(initialListOfItemsToBeIncluded, data.SelectedFilters)
: ImmutableArray<CompletionFilterWithState>.Empty;
// If this was deletion, then we control the entire behavior of deletion ourselves.
if (initialRoslynTriggerKind == CompletionTriggerKind.Deletion)
{
return HandleDeletionTrigger(reason, initialListOfItemsToBeIncluded, filterText, updatedFilters, hasSuggestedItemOptions, highlightMatchingPortions, completionHelper);
}
Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod;
if (completionService == null)
{
filterMethod = (itemsWithPatternMatches, text) => CompletionService.FilterItems(completionHelper, itemsWithPatternMatches, text);
}
else
{
filterMethod = (itemsWithPatternMatches, text) => completionService.FilterItems(document, itemsWithPatternMatches, text);
}
return HandleNormalFiltering(
filterMethod,
filterText,
updatedFilters,
filterReason,
data.Trigger.Character,
initialListOfItemsToBeIncluded,
hasSuggestedItemOptions,
highlightMatchingPortions,
completionHelper);
}
finally
{
// Don't call ClearAndFree, which resets the capacity to a default value.
initialListOfItemsToBeIncluded.Clear();
s_listOfMatchResultPool.Free(initialListOfItemsToBeIncluded);
}
static bool TryGetInitialTriggerLocation(AsyncCompletionSessionDataSnapshot data, out SnapshotPoint intialTriggerLocation)
{
var firstItem = data.InitialSortedList.FirstOrDefault(static item => item.Properties.ContainsProperty(CompletionSource.TriggerLocation));
if (firstItem != null)
{
return firstItem.Properties.TryGetProperty(CompletionSource.TriggerLocation, out intialTriggerLocation);
}
intialTriggerLocation = default;
return false;
}
static bool ShouldBeFilteredOutOfCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> activeNonExpanderFilters)
{
if (item.Filters.Any(filter => activeNonExpanderFilters.Contains(filter)))
{
return false;
}
return true;
}
static bool ShouldBeFilteredOutOfExpandedCompletionList(VSCompletionItem item, ImmutableArray<CompletionFilter> unselectedExpanders)
{
var associatedWithUnselectedExpander = false;
foreach (var itemFilter in item.Filters)
{
if (itemFilter is CompletionExpander)
{
if (!unselectedExpanders.Contains(itemFilter))
{
// If any of the associated expander is selected, the item should be included in the expanded list.
return false;
}
associatedWithUnselectedExpander = true;
}
}
// at this point, the item either:
// 1. has no expander filter, therefore should be included
// 2. or, all associated expanders are unselected, therefore should be excluded
return associatedWithUnselectedExpander;
}
}
private static bool IsAfterDot(ITextSnapshot snapshot, ITrackingSpan applicableToSpan)
{
var position = applicableToSpan.GetStartPoint(snapshot).Position;
return position > 0 && snapshot[position - 1] == '.';
}
private FilteredCompletionModel? HandleNormalFiltering(
Func<ImmutableArray<(RoslynCompletionItem, PatternMatch?)>, string, ImmutableArray<RoslynCompletionItem>> filterMethod,
string filterText,
ImmutableArray<CompletionFilterWithState> filters,
CompletionFilterReason filterReason,
char typeChar,
List<MatchResult<VSCompletionItem>> itemsInList,
bool hasSuggestedItemOptions,
bool highlightMatchingPortions,
CompletionHelper completionHelper)
{
// Not deletion. Defer to the language to decide which item it thinks best
// matches the text typed so far.
// Ask the language to determine which of the *matched* items it wants to select.
var matchingItems = itemsInList.Where(r => r.MatchedFilterText)
.SelectAsArray(t => (t.RoslynCompletionItem, t.PatternMatch));
var chosenItems = filterMethod(matchingItems, filterText);
int selectedItemIndex;
VSCompletionItem? uniqueItem = null;
MatchResult<VSCompletionItem> bestOrFirstMatchResult;
if (chosenItems.Length == 0)
{
// We do not have matches: pick the one with longest common prefix or the first item from the list.
selectedItemIndex = 0;
bestOrFirstMatchResult = itemsInList[0];
var longestCommonPrefixLength = bestOrFirstMatchResult.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText);
for (var i = 1; i < itemsInList.Count; ++i)
{
var item = itemsInList[i];
var commonPrefixLength = item.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(filterText);
if (commonPrefixLength > longestCommonPrefixLength)
{
selectedItemIndex = i;
bestOrFirstMatchResult = item;
longestCommonPrefixLength = commonPrefixLength;
}
}
}
else
{
var recentItems = _recentItemsManager.RecentItems;
// Of the items the service returned, pick the one most recently committed
var bestItem = GetBestCompletionItemBasedOnMRU(chosenItems, recentItems);
// Determine if we should consider this item 'unique' or not. A unique item
// will be automatically committed if the user hits the 'invoke completion'
// without bringing up the completion list. An item is unique if it was the
// only item to match the text typed so far, and there was at least some text
// typed. i.e. if we have "Console.$$" we don't want to commit something
// like "WriteLine" since no filter text has actually been provided. However,
// if "Console.WriteL$$" is typed, then we do want "WriteLine" to be committed.
selectedItemIndex = itemsInList.IndexOf(i => Equals(i.RoslynCompletionItem, bestItem));
bestOrFirstMatchResult = itemsInList[selectedItemIndex];
var deduplicatedListCount = matchingItems.Count(r => !r.RoslynCompletionItem.IsPreferredItem());
if (deduplicatedListCount == 1 &&
filterText.Length > 0)
{
uniqueItem = itemsInList[selectedItemIndex].EditorCompletionItem;
}
}
// Check that it is a filter symbol. We can be called for a non-filter symbol.
// If inserting a non-filter character (neither IsPotentialFilterCharacter, nor Helpers.IsFilterCharacter), we should dismiss completion
// except cases where this is the first symbol typed for the completion session (string.IsNullOrEmpty(filterText) or string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase)).
// In the latter case, we should keep the completion because it was confirmed just before in InitializeCompletion.
if (filterReason == CompletionFilterReason.Insertion &&
!string.IsNullOrEmpty(filterText) &&
!string.Equals(filterText, typeChar.ToString(), StringComparison.OrdinalIgnoreCase) &&
!IsPotentialFilterCharacter(typeChar) &&
!Helpers.IsFilterCharacter(bestOrFirstMatchResult.RoslynCompletionItem, typeChar, filterText))
{
return null;
}
var isHardSelection = IsHardSelection(
filterText, bestOrFirstMatchResult.RoslynCompletionItem, bestOrFirstMatchResult.MatchedFilterText, hasSuggestedItemOptions);
var updateSelectionHint = isHardSelection ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected;
return new FilteredCompletionModel(
GetHighlightedList(itemsInList, filterText, highlightMatchingPortions, completionHelper), selectedItemIndex, filters,
updateSelectionHint, centerSelection: true, uniqueItem);
}
private static FilteredCompletionModel? HandleDeletionTrigger(
CompletionTriggerReason filterTriggerKind,
List<MatchResult<VSCompletionItem>> matchResults,
string filterText,
ImmutableArray<CompletionFilterWithState> filters,
bool hasSuggestedItemOptions,
bool highlightMatchingSpans,
CompletionHelper completionHelper)
{
var matchingItems = matchResults.Where(r => r.MatchedFilterText);
if (filterTriggerKind == CompletionTriggerReason.Insertion &&
!matchingItems.Any())
{
// The user has typed something, but nothing in the actual list matched what
// they were typing. In this case, we want to dismiss completion entirely.
// The thought process is as follows: we aggressively brought up completion
// to help them when they typed delete (in case they wanted to pick another
// item). However, they're typing something that doesn't seem to match at all
// The completion list is just distracting at this point.
return null;
}
MatchResult<VSCompletionItem>? bestMatchResult = null;
var moreThanOneMatchWithSamePriority = false;
foreach (var currentMatchResult in matchingItems)
{
if (bestMatchResult == null)
{
// We had no best result yet, so this is now our best result.
bestMatchResult = currentMatchResult;
}
else
{
var match = currentMatchResult.CompareTo(bestMatchResult.Value, filterText);
if (match > 0)
{
moreThanOneMatchWithSamePriority = false;
bestMatchResult = currentMatchResult;
}
else if (match == 0)
{
moreThanOneMatchWithSamePriority = true;
}
}
}
int index;
bool hardSelect;
// If we had a matching item, then pick the best of the matching items and
// choose that one to be hard selected. If we had no actual matching items
// (which can happen if the user deletes down to a single character and we
// include everything), then we just soft select the first item.
if (bestMatchResult != null)
{
// Only hard select this result if it's a prefix match
// We need to do this so that
// * deleting and retyping a dot in a member access does not change the
// text that originally appeared before the dot
// * deleting through a word from the end keeps that word selected
// This also preserves the behavior the VB had through Dev12.
hardSelect = !hasSuggestedItemOptions && bestMatchResult.Value.EditorCompletionItem.FilterText.StartsWith(filterText, StringComparison.CurrentCultureIgnoreCase);
index = matchResults.IndexOf(bestMatchResult.Value);
}
else
{
index = 0;
hardSelect = false;
}
return new FilteredCompletionModel(
GetHighlightedList(matchResults, filterText, highlightMatchingSpans, completionHelper), index, filters,
hardSelect ? UpdateSelectionHint.Selected : UpdateSelectionHint.SoftSelected,
centerSelection: true,
uniqueItem: moreThanOneMatchWithSamePriority ? null : bestMatchResult.GetValueOrDefault().EditorCompletionItem);
}
private static ImmutableArray<CompletionItemWithHighlight> GetHighlightedList(
List<MatchResult<VSCompletionItem>> matchResults,
string filterText,
bool highlightMatchingPortions,
CompletionHelper completionHelper)
{
return matchResults.SelectAsArray(matchResult =>
{
var highlightedSpans = GetHighlightedSpans(matchResult, completionHelper, filterText, highlightMatchingPortions);
return new CompletionItemWithHighlight(matchResult.EditorCompletionItem, highlightedSpans);
});
static ImmutableArray<Span> GetHighlightedSpans(
MatchResult<VSCompletionItem> matchResult,
CompletionHelper completionHelper,
string filterText,
bool highlightMatchingPortions)
{
if (highlightMatchingPortions)
{
if (matchResult.RoslynCompletionItem.HasDifferentFilterText)
{
// The PatternMatch in MatchResult is calculated based on Roslyn item's FilterText,
// which can be used to calculate highlighted span for VSCompletion item's DisplayText w/o doing the matching again.
// However, if the Roslyn item's FilterText is different from its DisplayText,
// we need to do the match against the display text of the VS item directly to get the highlighted spans.
return completionHelper.GetHighlightedSpans(
matchResult.EditorCompletionItem.DisplayText, filterText, CultureInfo.CurrentCulture).SelectAsArray(s => s.ToSpan());
}
var patternMatch = matchResult.PatternMatch;
if (patternMatch.HasValue)
{
// Since VS item's display text is created as Prefix + DisplayText + Suffix,
// we can calculate the highlighted span by adding an offset that is the length of the Prefix.
return patternMatch.Value.MatchedSpans.SelectAsArray(s_highlightSpanGetter, matchResult.RoslynCompletionItem);
}
}
// If there's no match for Roslyn item's filter text which is identical to its display text,
// then we can safely assume there'd be no matching to VS item's display text.
return ImmutableArray<Span>.Empty;
}
}
private static FilteredCompletionModel? HandleAllItemsFilteredOut(
CompletionTriggerReason triggerReason,
ImmutableArray<CompletionFilterWithState> filters,
CompletionRules completionRules)
{
if (triggerReason == CompletionTriggerReason.Insertion)
{
// If the user was just typing, and the list went to empty *and* this is a
// language that wants to dismiss on empty, then just return a null model
// to stop the completion session.
if (completionRules.DismissIfEmpty)
{
return null;
}
}
// If the user has turned on some filtering states, and we filtered down to
// nothing, then we do want the UI to show that to them. That way the user
// can turn off filters they don't want and get the right set of items.
// If we are going to filter everything out, then just preserve the existing
// model (and all the previously filtered items), but switch over to soft
// selection.
var selection = UpdateSelectionHint.SoftSelected;
return new FilteredCompletionModel(
ImmutableArray<CompletionItemWithHighlight>.Empty, selectedItemIndex: 0,
filters, selection, centerSelection: true, uniqueItem: null);
}
private static ImmutableArray<CompletionFilterWithState> GetUpdatedFilters(
List<MatchResult<VSCompletionItem>> filteredList,
ImmutableArray<CompletionFilterWithState> filters)
{
// See which filters might be enabled based on the typed code
using var _ = PooledHashSet<CompletionFilter>.GetInstance(out var textFilteredFilters);
textFilteredFilters.AddRange(filteredList.SelectMany(n => n.EditorCompletionItem.Filters));
// When no items are available for a given filter, it becomes unavailable.
// Expanders always appear available as long as it's presented.
return filters.SelectAsArray(n => n.WithAvailability(n.Filter is CompletionExpander ? true : textFilteredFilters.Contains(n.Filter)));
}
/// <summary>
/// Given multiple possible chosen completion items, pick the one that has the
/// best MRU index, or the one with highest MatchPriority if none in MRU.
/// </summary>
private static RoslynCompletionItem GetBestCompletionItemBasedOnMRU(
ImmutableArray<RoslynCompletionItem> chosenItems, ImmutableArray<string> recentItems)
{
Debug.Assert(chosenItems.Length > 0);
// Try to find the chosen item has been most recently used.
var bestItem = chosenItems[0];
for (int i = 1, n = chosenItems.Length; i < n; i++)
{
var chosenItem = chosenItems[i];
var mruIndex1 = GetRecentItemIndex(recentItems, bestItem);
var mruIndex2 = GetRecentItemIndex(recentItems, chosenItem);
if ((mruIndex2 < mruIndex1) ||
(mruIndex2 == mruIndex1 && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem()))
{
bestItem = chosenItem;
}
}
// If our best item appeared in the MRU list, use it
if (GetRecentItemIndex(recentItems, bestItem) <= 0)
{
return bestItem;
}
// Otherwise use the chosen item that has the highest
// matchPriority.
for (int i = 1, n = chosenItems.Length; i < n; i++)
{
var chosenItem = chosenItems[i];
var bestItemPriority = bestItem.Rules.MatchPriority;
var currentItemPriority = chosenItem.Rules.MatchPriority;
if ((currentItemPriority > bestItemPriority) ||
((currentItemPriority == bestItemPriority) && !bestItem.IsPreferredItem() && chosenItem.IsPreferredItem()))
{
bestItem = chosenItem;
}
}
return bestItem;
}
private static int GetRecentItemIndex(ImmutableArray<string> recentItems, RoslynCompletionItem item)
{
var index = recentItems.IndexOf(item.FilterText);
return -index;
}
private static RoslynCompletionItem GetOrAddRoslynCompletionItem(VSCompletionItem vsItem)
{
if (!vsItem.Properties.TryGetProperty(CompletionSource.RoslynItem, out RoslynCompletionItem roslynItem))
{
roslynItem = RoslynCompletionItem.Create(
displayText: vsItem.DisplayText,
filterText: vsItem.FilterText,
sortText: vsItem.SortText,
displayTextSuffix: vsItem.Suffix);
vsItem.Properties.AddProperty(CompletionSource.RoslynItem, roslynItem);
}
return roslynItem;
}
private static bool TryCreateMatchResult(
CompletionHelper completionHelper,
VSCompletionItem item,
string filterText,
CompletionTriggerKind initialTriggerKind,
CompletionFilterReason filterReason,
ImmutableArray<string> recentItems,
bool highlightMatchingPortions,
int currentIndex,
out MatchResult<VSCompletionItem> matchResult)
{
var roslynItem = GetOrAddRoslynCompletionItem(item);
return CompletionHelper.TryCreateMatchResult(completionHelper, roslynItem, item, filterText, initialTriggerKind, filterReason, recentItems, highlightMatchingPortions, currentIndex, out matchResult);
}
// PERF: Create a singleton to avoid lambda allocation on hot path
private static readonly Func<TextSpan, RoslynCompletionItem, Span> s_highlightSpanGetter
= (span, item) => span.MoveTo(item.DisplayTextPrefix?.Length ?? 0).ToSpan();
private static bool IsHardSelection(
string filterText,
RoslynCompletionItem item,
bool matchedFilterText,
bool useSuggestionMode)
{
if (item == null || useSuggestionMode)
{
return false;
}
// We don't have a builder and we have a best match. Normally this will be hard
// selected, except for a few cases. Specifically, if no filter text has been
// provided, and this is not a preselect match then we will soft select it. This
// happens when the completion list comes up implicitly and there is something in
// the MRU list. In this case we do want to select it, but not with a hard
// selection. Otherwise you can end up with the following problem:
//
// dim i as integer =<space>
//
// Completion will comes up after = with 'integer' selected (Because of MRU). We do
// not want 'space' to commit this.
// If all that has been typed is punctuation, then don't hard select anything.
// It's possible the user is just typing language punctuation and selecting
// anything in the list will interfere. We only allow this if the filter text
// exactly matches something in the list already.
if (filterText.Length > 0 && IsAllPunctuation(filterText) && filterText != item.DisplayText)
{
return false;
}
// If the user hasn't actually typed anything, then don't hard select any item.
// The only exception to this is if the completion provider has requested the
// item be preselected.
if (filterText.Length == 0)
{
// Item didn't want to be hard selected with no filter text.
// So definitely soft select it.
if (item.Rules.SelectionBehavior != CompletionItemSelectionBehavior.HardSelection)
{
return false;
}
// Item did not ask to be preselected. So definitely soft select it.
if (item.Rules.MatchPriority == MatchPriority.Default)
{
return false;
}
}
// The user typed something, or the item asked to be preselected. In
// either case, don't soft select this.
Debug.Assert(filterText.Length > 0 || item.Rules.MatchPriority != MatchPriority.Default);
// If the user moved the caret left after they started typing, the 'best' match may not match at all
// against the full text span that this item would be replacing.
if (!matchedFilterText)
{
return false;
}
// There was either filter text, or this was a preselect match. In either case, we
// can hard select this.
return true;
}
private static bool IsAllPunctuation(string filterText)
{
foreach (var ch in filterText)
{
if (!char.IsPunctuation(ch))
{
return false;
}
}
return true;
}
/// <summary>
/// A potential filter character is something that can filter a completion lists and is
/// *guaranteed* to not be a commit character.
/// </summary>
private static bool IsPotentialFilterCharacter(char c)
{
// TODO(cyrusn): Actually use the right Unicode categories here.
return char.IsLetter(c)
|| char.IsNumber(c)
|| c == '_';
}
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.